Repository navigation
feat(tiktok): add comment automation and rename the comment-automation tables - #1215
Merged
Merged
Conversation
TikTok joins the shared comment-automation pipeline as a fifth channel, alongside messenger, instagram, instagramFacebook and threads. It supports public replies, liking and hiding, and reuses the existing analytics counters, so the stat columns work with no channel-specific code. Capabilities differ from the other channels in two ways. TikTok CAN like and hide a comment (business/comment/like/, business/comment/hide/), unlike Threads. It CANNOT send a private reply: its Send API addresses an existing conversation_id that only the contact can open, so there is nothing to anchor a comment DM to. Both gates became allowlists so a future channel defaults to "cannot" rather than inheriting a capability by omission. Two traps worth naming: - TikTok used to store the DM conversation_id in Conversation.sourceId, the slot reserved repo-wide for comment threads keyed by post id. With TikTok comments a contact would hold two non-null-sourceId conversations and findDMByContact would return the wrong one, silently breaking DM routing, read receipts and broadcasts. The id now lives on additionalAttributes.channelConversationId, dmConversationUsesSourceId is gone, and a data migration backfills existing rows. - The comment.update webhook sends 19-digit snowflake ids as JSON numbers, which JSON.parse rounds away. They are quoted back into strings before parsing, with a test proving a plain parse really does corrupt them. Still pending, both marked TODO(tiktok-comments) in place and deliberately not guessed because a wrong value breaks connecting the channel entirely: the write scope for reply/like/hide/delete, and the event_type used to subscribe to comment.update. Migrations are generated but not applied. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ation The table serves five channels — messenger, instagram, instagramFacebook, threads and tiktok — so the FB prefix is factually wrong for three of them. Every object added after the original table had already dropped it (commentAutomationReplyChannel, commentAutomationMissReason, commentAutomationStatsRepository, CommentAutomationChannelType); this finishes the job across all four tables, their 14 indexes, 13 foreign keys, 4 primary keys and the one remaining FB-prefixed enum type. Two things the migration has to do by hand, because Postgres will not: - Renaming a table leaves its indexes and constraints under the old names, and drizzle matches them by name — so each one is re-pointed explicitly. The same trap the PlatformSetting -> Tenant migration documented. - Three foreign keys carried hashed names (FBCommentAutomationEvent_ LOfdyJGW0vJy_fkey and friends) because the generated name exceeded Postgres' 63-byte limit with the parent table named twice. Dropping the prefix brings them to 61 bytes, so they become readable again; the new names are taken from the snapshot rather than guessed. Deliberately NOT renamed: the templateResourceCategory enum value `fbCommentAutomations`, the `fbCommentAutomation` resourceKind, and the matching key in the template import/export document schema. Those are persisted data, not identifiers — changing them is a data migration on stored templates, which is a separate decision. Migration is generated but not applied. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…y name The first version named each old constraint explicitly, taking the names from the schema snapshot. It failed on the first foreign key: this database calls it FBCommentAutomation_folderId_fkey, Postgres' own default, while the snapshot calls it FBCommentAutomation_folderId_Folder_id_fkey. Inspecting the live database showed three naming conventions side by side — the two older tables carry Postgres defaults, the two newer ones drizzle's longer form, and two foreign keys are hashed because the generated name passed the 63-byte limit. Any migration that names the old constraint therefore breaks on whichever half of a given database does not match, and would break differently elsewhere. Constraints are now found by (table, type, columns, target table) and renamed to the name the snapshot expects, which is stable across all three conventions. A generic sweep then clears the prefix from Postgres-named NOT NULL constraints, and a final assertion fails loudly if anything is left — a rename that silently skipped would leave the database and the snapshot disagreeing with nothing to show for it. Verified by replaying the whole migration inside a transaction and rolling back: 22 statements, four tables renamed, no leftover prefix, rows intact. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
TikTok delivers comment events within five minutes rather than in real time, and the write scopes for reply/like/hide/delete are still pending approval — the badge sets the expectation so the delay reads as a known limitation rather than a fault. The flag is opt-in per card (`beta: true` in TOOLS_CONFIG) rather than inferred, so no other tool picks it up by accident; a test covers both directions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two ways the TikTok comment path could answer a comment it should not. A retry re-ran `recordAndDispatchReply`, which dispatches unconditionally. `business/comment/reply/create/` takes no client-side key, so the second run posts a second visible reply with no id to resume from — the same reason Threads was already capped. The cap becomes an allowlist so a channel added without a decision keeps the default policy rather than inheriting a cap it may not need. `resolveTiktokCommenterIdentity` returning undefined disabled the only self-authorship guard TikTok has: `fromId === integrationIdentifier` can never match, because the webhook reports a `unique_identifier` while the integration is keyed by `open_id`. A transient failure therefore let the account reply to its own comment. An unresolved lookup now means "authorship unknown" — the comment still reaches the inbox, but the automation is withheld. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`unique_identifier` keys the commenter's Contact. Falling back to `comment_id` keyed it by the comment instead, so one person became a brand-new Contact on every comment they wrote — inflating MAC quota and firing `replyToNewContactsOnly` every time. A comment nobody can be attributed to is dropped with a warning; the `delete` branch needs no commenter and is unaffected. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`Conversation` carries no inbox or channel column — only `contactId` and `sourceId` — so both steps asked the contact instead: "does it have any tiktok ContactInbox?". A contact that also has a Meta inbox owns comment conversations keyed by a Facebook or Instagram post id, and those matched too. Step 2 then nulls the `sourceId` of a Meta comment thread, losing the post anchor irreversibly; a contact holding two such threads has both rows nulled from the same snapshot, violating `Conversation_contactId_dm_key` and aborting the migration part-way. Both steps now restrict themselves to contacts whose inboxes are all TikTok. A cross-channel contact is left untouched and keeps sending through the `sourceId` fallback in `resolveChannelConversationId`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The query file resolved pagination and ordering itself, computed `pageCount`,
and imported `commentAutomationModel` directly. A `.query.ts` is a request
adapter — it may shape a service's response, but where-builders and page maths
belong behind the service boundary. `listTiktokAutomations` now takes the
request input and returns `{ data, pageCount }`, mirroring `list` on the
Messenger side.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`comment.list` is what makes TikTok deliver `comment.update` webhooks at all, so every account authorized before comment automation shipped receives no comment events — silently, with a connection that otherwise looks healthy. The granted scopes are now recorded in `auth.metadata.scopes` at every write site (callback, `refreshAuth`, the refresh cron), and the settings list flags a connection missing one. A connection with no recorded scopes counts as needing re-authorization: that is exactly the population this exists to surface, and the refresh cron re-stamps the real list, so one that does hold the scope stops being flagged on its own. `listIntegrationTiktoks` returned the whole row to a `"use client"` component, which serializes it into the RSC payload the browser receives — including the `auth` column holding the app client secret, the access token and the refresh token. It now projects onto `IntegrationTiktokResource`, the shape the child components already declared, and resolves the scope check server-side. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The worker has been writing `CommentAutomationEvent` rows for TikTok since the channel shipped — `recordReplyEvent` is channel-agnostic and the analytics service filters by workspace, not by automation type — but there was no route to read them, so the replies chart, Bot replies table and Error Logs panel were written, retained for 30 days, purged, and never seen. Error Logs matters most here: the comment write scope is still pending, so failed replies are expected and there was nowhere to look at them. Nothing downstream needed changing. The route reuses `getTiktokComment`, which already scopes to the caller's workspace and to the `tiktok` type, so a Facebook automation id resolves to a 404 rather than someone else's dashboard. Threads has the same gap and is deliberately left alone — it predates this branch and deserves its own change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
TikTok's consent screen lets each permission be unticked individually, so a
partial grant is an ordinary outcome, not an edge case. The callback stored
whatever came back and the connection looked healthy; the first message then
failed with nothing explaining why. Chatwoot refuses the same case outright.
Only the CORE scopes are refused — identity plus Business Messaging, the five
the code actually reads. A grant missing just the comment-automation scopes
still gives a working DM inbox, and rejecting it would leave a workspace that
only wants DMs unable to connect at all; that case keeps surfacing as the
re-authorize warning on the settings list. The profile scopes are requested but
never enforced, because nothing reads a field behind them and refusing over a
permission the product does not use would turn a cosmetic choice on TikTok's
consent screen into a hard failure.
The refusal has to reach the user, which took two more changes. TikTok's
authorize `referer` pointed at `/space/{id}`, and that page redirects to
whichever section the member can access, dropping the query string on the way —
so an `?error=` relayed back would never have reached the toast. It now points
at the channels settings page, the way Threads already did; a successful
connect lands there too instead of on the dashboard. And
`useChannelDuplicatedError` only understood one error code, so it becomes
`useChannelConnectError` over a union. Its two namespaces are deliberately
uneven — `duplicated` has a line per channel, `missingScopes` only TikTok — so
the key resolution goes through `t.has` and degrades to the generic copy rather
than rendering a raw key for a channel with no line of its own.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
CI failed with "Non-commutative migrations detected": this branch's migrations and main's `20260917072620_whatsapp_calling_consolidated` were generated from the same two parents, so merging produced two heads and drizzle-kit refused to diff against a forked DAG. Nothing was wrong locally, because the branch did not carry main's migration until now — the conflict only exists on the merge commit CI builds. The snapshots are re-linked rather than regenerated. `add_tiktok_comment_automation_type` now descends from the WhatsApp migration, and its `ddl` is that parent's plus the one enum value its own SQL adds — verified to be the only semantic difference between the two. The rename migration keeps its id and parent and takes drizzle-kit's rendering of the current schema, which differs from what it held by exactly the 80 WhatsApp entities and nothing else. Two sibling conflicts remain and are deliberately untouched: both predate this branch, exist identically on main (`add_integration_threads`, `facebook_marketing_messages`), and drizzle-kit does not flag either, because those pairs commute. Repairing them would rewrite history this PR has no business touching. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`receiveMessage` only mapped `type: "text"` and `type: "image"`, so a `share_post` DM produced a Message row with no text and no attachment that still broadcast to the inbox and fired `message:received` for every flow and automation listening. It now renders as TikTok's own `embed_url`, with the video id kept on `contentAttributes` as a `shared_post` entity. The webhook carries no author handle, so the canonical `tiktok.com/@<user>/video/<id>` form cannot be built without inventing one, and `tiktok.com/video/<id>` is a hard 404 — the player URL is used verbatim. `share_post` parses with `.catch(undefined)`: a shape TikTok changes under us must cost the link, never the customer's message. A DM that still renders to nothing is now logged, so the next unrendered content type is visible rather than silently blank. Also records what a production payload and TikTok's `comment.update` docs settle about identity: `content.unique_identifier` is the globally unique user id the comment webhook sends for a commenter, and it equals `from_user.id` on an inbound DM — which is why a commenter and a DM sender already resolve to one ContactInbox, with no merge step. It stays unread here, because on an `im_send_msg` echo the roles reverse and TikTok does not document whose id it then holds; `from_user`/`to_user` remain the only identity source. Tests lock both directions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
sung17
marked this pull request as ready for review
September 19, 2026 13:43
hello-jackytruong
referenced
this pull request
in hello-jackytruong/ChatWorkAI
Nov 22, 2026
…n tables (#1215) * feat(tiktok): add comment automation for business account videos TikTok joins the shared comment-automation pipeline as a fifth channel, alongside messenger, instagram, instagramFacebook and threads. It supports public replies, liking and hiding, and reuses the existing analytics counters, so the stat columns work with no channel-specific code. Capabilities differ from the other channels in two ways. TikTok CAN like and hide a comment (business/comment/like/, business/comment/hide/), unlike Threads. It CANNOT send a private reply: its Send API addresses an existing conversation_id that only the contact can open, so there is nothing to anchor a comment DM to. Both gates became allowlists so a future channel defaults to "cannot" rather than inheriting a capability by omission. Two traps worth naming: - TikTok used to store the DM conversation_id in Conversation.sourceId, the slot reserved repo-wide for comment threads keyed by post id. With TikTok comments a contact would hold two non-null-sourceId conversations and findDMByContact would return the wrong one, silently breaking DM routing, read receipts and broadcasts. The id now lives on additionalAttributes.channelConversationId, dmConversationUsesSourceId is gone, and a data migration backfills existing rows. - The comment.update webhook sends 19-digit snowflake ids as JSON numbers, which JSON.parse rounds away. They are quoted back into strings before parsing, with a test proving a plain parse really does corrupt them. Still pending, both marked TODO(tiktok-comments) in place and deliberately not guessed because a wrong value breaks connecting the channel entirely: the write scope for reply/like/hide/delete, and the event_type used to subscribe to comment.update. Migrations are generated but not applied. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(database): rename FBCommentAutomation tables to CommentAutomation The table serves five channels — messenger, instagram, instagramFacebook, threads and tiktok — so the FB prefix is factually wrong for three of them. Every object added after the original table had already dropped it (commentAutomationReplyChannel, commentAutomationMissReason, commentAutomationStatsRepository, CommentAutomationChannelType); this finishes the job across all four tables, their 14 indexes, 13 foreign keys, 4 primary keys and the one remaining FB-prefixed enum type. Two things the migration has to do by hand, because Postgres will not: - Renaming a table leaves its indexes and constraints under the old names, and drizzle matches them by name — so each one is re-pointed explicitly. The same trap the PlatformSetting -> Tenant migration documented. - Three foreign keys carried hashed names (FBCommentAutomationEvent_ LOfdyJGW0vJy_fkey and friends) because the generated name exceeded Postgres' 63-byte limit with the parent table named twice. Dropping the prefix brings them to 61 bytes, so they become readable again; the new names are taken from the snapshot rather than guessed. Deliberately NOT renamed: the templateResourceCategory enum value `fbCommentAutomations`, the `fbCommentAutomation` resourceKind, and the matching key in the template import/export document schema. Those are persisted data, not identifiers — changing them is a data migration on stored templates, which is a separate decision. Migration is generated but not applied. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(database): rename comment-automation constraints by lookup, not by name The first version named each old constraint explicitly, taking the names from the schema snapshot. It failed on the first foreign key: this database calls it FBCommentAutomation_folderId_fkey, Postgres' own default, while the snapshot calls it FBCommentAutomation_folderId_Folder_id_fkey. Inspecting the live database showed three naming conventions side by side — the two older tables carry Postgres defaults, the two newer ones drizzle's longer form, and two foreign keys are hashed because the generated name passed the 63-byte limit. Any migration that names the old constraint therefore breaks on whichever half of a given database does not match, and would break differently elsewhere. Constraints are now found by (table, type, columns, target table) and renamed to the name the snapshot expects, which is stable across all three conventions. A generic sweep then clears the prefix from Postgres-named NOT NULL constraints, and a final assertion fails loudly if anything is left — a rename that silently skipped would leave the database and the snapshot disagreeing with nothing to show for it. Verified by replaying the whole migration inside a transaction and rolling back: 22 statements, four tables renamed, no leftover prefix, rows intact. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(tools): mark the TikTok comment automation card as Beta TikTok delivers comment events within five minutes rather than in real time, and the write scopes for reply/like/hide/delete are still pending approval — the badge sets the expectation so the delay reads as a known limitation rather than a fault. The flag is opt-in per card (`beta: true` in TOOLS_CONFIG) rather than inferred, so no other tool picks it up by accident; a test covers both directions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(tiktok): fail closed on comment retry and unknown authorship Two ways the TikTok comment path could answer a comment it should not. A retry re-ran `recordAndDispatchReply`, which dispatches unconditionally. `business/comment/reply/create/` takes no client-side key, so the second run posts a second visible reply with no id to resume from — the same reason Threads was already capped. The cap becomes an allowlist so a channel added without a decision keeps the default policy rather than inheriting a cap it may not need. `resolveTiktokCommenterIdentity` returning undefined disabled the only self-authorship guard TikTok has: `fromId === integrationIdentifier` can never match, because the webhook reports a `unique_identifier` while the integration is keyed by `open_id`. A transient failure therefore let the account reply to its own comment. An unresolved lookup now means "authorship unknown" — the comment still reaches the inbox, but the automation is withheld. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(tiktok): drop a comment event that identifies no commenter `unique_identifier` keys the commenter's Contact. Falling back to `comment_id` keyed it by the comment instead, so one person became a brand-new Contact on every comment they wrote — inflating MAC quota and firing `replyToNewContactsOnly` every time. A comment nobody can be attributed to is dropped with a warning; the `delete` branch needs no commenter and is unaffected. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(database): scope the tiktok dm backfill to tiktok-only contacts `Conversation` carries no inbox or channel column — only `contactId` and `sourceId` — so both steps asked the contact instead: "does it have any tiktok ContactInbox?". A contact that also has a Meta inbox owns comment conversations keyed by a Facebook or Instagram post id, and those matched too. Step 2 then nulls the `sourceId` of a Meta comment thread, losing the post anchor irreversibly; a contact holding two such threads has both rows nulled from the same snapshot, violating `Conversation_contactId_dm_key` and aborting the migration part-way. Both steps now restrict themselves to contacts whose inboxes are all TikTok. A cross-channel contact is left untouched and keeps sending through the `sourceId` fallback in `resolveChannelConversationId`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(tiktok): own comment automation list pagination in the service The query file resolved pagination and ordering itself, computed `pageCount`, and imported `commentAutomationModel` directly. A `.query.ts` is a request adapter — it may shape a service's response, but where-builders and page maths belong behind the service boundary. `listTiktokAutomations` now takes the request input and returns `{ data, pageCount }`, mirroring `list` on the Messenger side. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(tiktok): warn when a connection must re-authorize for comments `comment.list` is what makes TikTok deliver `comment.update` webhooks at all, so every account authorized before comment automation shipped receives no comment events — silently, with a connection that otherwise looks healthy. The granted scopes are now recorded in `auth.metadata.scopes` at every write site (callback, `refreshAuth`, the refresh cron), and the settings list flags a connection missing one. A connection with no recorded scopes counts as needing re-authorization: that is exactly the population this exists to surface, and the refresh cron re-stamps the real list, so one that does hold the scope stops being flagged on its own. `listIntegrationTiktoks` returned the whole row to a `"use client"` component, which serializes it into the RSC payload the browser receives — including the `auth` column holding the app client secret, the access token and the refresh token. It now projects onto `IntegrationTiktokResource`, the shape the child components already declared, and resolves the scope check server-side. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(tiktok): add the per-automation comment analytics page The worker has been writing `CommentAutomationEvent` rows for TikTok since the channel shipped — `recordReplyEvent` is channel-agnostic and the analytics service filters by workspace, not by automation type — but there was no route to read them, so the replies chart, Bot replies table and Error Logs panel were written, retained for 30 days, purged, and never seen. Error Logs matters most here: the comment write scope is still pending, so failed replies are expected and there was nowhere to look at them. Nothing downstream needed changing. The route reuses `getTiktokComment`, which already scopes to the caller's workspace and to the `tiktok` type, so a Facebook automation id resolves to a 404 rather than someone else's dashboard. Threads has the same gap and is deliberately left alone — it predates this branch and deserves its own change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(tiktok): refuse a connect that withheld a required scope TikTok's consent screen lets each permission be unticked individually, so a partial grant is an ordinary outcome, not an edge case. The callback stored whatever came back and the connection looked healthy; the first message then failed with nothing explaining why. Chatwoot refuses the same case outright. Only the CORE scopes are refused — identity plus Business Messaging, the five the code actually reads. A grant missing just the comment-automation scopes still gives a working DM inbox, and rejecting it would leave a workspace that only wants DMs unable to connect at all; that case keeps surfacing as the re-authorize warning on the settings list. The profile scopes are requested but never enforced, because nothing reads a field behind them and refusing over a permission the product does not use would turn a cosmetic choice on TikTok's consent screen into a hard failure. The refusal has to reach the user, which took two more changes. TikTok's authorize `referer` pointed at `/space/{id}`, and that page redirects to whichever section the member can access, dropping the query string on the way — so an `?error=` relayed back would never have reached the toast. It now points at the channels settings page, the way Threads already did; a successful connect lands there too instead of on the dashboard. And `useChannelDuplicatedError` only understood one error code, so it becomes `useChannelConnectError` over a union. Its two namespaces are deliberately uneven — `duplicated` has a line per channel, `missingScopes` only TikTok — so the key resolution goes through `t.has` and degrades to the generic copy rather than rendering a raw key for a channel with no line of its own. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(database): relink the tiktok migrations onto main's chain head CI failed with "Non-commutative migrations detected": this branch's migrations and main's `20260917072620_whatsapp_calling_consolidated` were generated from the same two parents, so merging produced two heads and drizzle-kit refused to diff against a forked DAG. Nothing was wrong locally, because the branch did not carry main's migration until now — the conflict only exists on the merge commit CI builds. The snapshots are re-linked rather than regenerated. `add_tiktok_comment_automation_type` now descends from the WhatsApp migration, and its `ddl` is that parent's plus the one enum value its own SQL adds — verified to be the only semantic difference between the two. The rename migration keeps its id and parent and takes drizzle-kit's rendering of the current schema, which differs from what it held by exactly the 80 WhatsApp entities and nothing else. Two sibling conflicts remain and are deliberately untouched: both predate this branch, exist identically on main (`add_integration_threads`, `facebook_marketing_messages`), and drizzle-kit does not flag either, because those pairs commute. Repairing them would rewrite history this PR has no business touching. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(tiktok): render a shared-post dm instead of an empty message row `receiveMessage` only mapped `type: "text"` and `type: "image"`, so a `share_post` DM produced a Message row with no text and no attachment that still broadcast to the inbox and fired `message:received` for every flow and automation listening. It now renders as TikTok's own `embed_url`, with the video id kept on `contentAttributes` as a `shared_post` entity. The webhook carries no author handle, so the canonical `tiktok.com/@<user>/video/<id>` form cannot be built without inventing one, and `tiktok.com/video/<id>` is a hard 404 — the player URL is used verbatim. `share_post` parses with `.catch(undefined)`: a shape TikTok changes under us must cost the link, never the customer's message. A DM that still renders to nothing is now logged, so the next unrendered content type is visible rather than silently blank. Also records what a production payload and TikTok's `comment.update` docs settle about identity: `content.unique_identifier` is the globally unique user id the comment webhook sends for a commenter, and it equals `from_user.id` on an inbound DM — which is why a commenter and a DM sender already resolve to one ContactInbox, with no merge step. It stays unread here, because on an `im_send_msg` echo the roles reverse and TikTok does not document whose id it then holds; `from_user`/`to_user` remain the only identity source. Tests lock both directions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Deathgiver <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds TikTok as the fifth channel on the shared comment-automation pipeline, then finishes the rename the codebase had already started.
Still draft: three migrations need applying, and two TikTok values are still pending from the developer portal — see Blocking below.
What's here
TikTok comment automation — public replies, liking and hiding on comments under business-account videos, plus the per-automation analytics page the other channels have.
Capabilities differ from the existing channels in two ways:
TikTok can like and hide (unlike Threads) but cannot send a private reply: its Send API addresses an existing
conversation_idthat only the contact can open, so there is nothing to anchor a comment DM to. Both gates became allowlists so a future channel defaults to "cannot" rather than inheriting a capability by omission.Table rename —
FBCommentAutomation→CommentAutomation(and the three sibling tables). The table serves five channels, three of which are not Facebook. Every object added after the original table had already dropped the prefix; this finishes the job across 4 tables, 14 indexes, 13 foreign keys, 4 primary keys and the one remaining FB-prefixed enum type.Connect-time scope enforcement — TikTok's consent screen lets each permission be unticked individually, so a partial grant is an ordinary outcome, not an edge case. The callback used to store whatever came back and the connection looked healthy until the first message failed. It now refuses a grant missing a core scope (identity plus Business Messaging — the five the code actually reads) before anything is persisted, and relays the user back with a toast. A grant missing only the comment scopes still connects: DMs work without them, and refusing would leave a DM-only workspace unable to connect at all. That case raises the re-authorize warning on the settings list instead.
What the delivery columns say for TikTok
Worth setting expectations, because it looks like a bug and is not one. The five delivery columns (Sent / Delivered / Seen / Clicked / Failed) and
repliesCountmeasure the DM, not the public comment reply —countsTowardStatsonly countsprivate, because a public reply has no delivery receipt and no reader, and counting it would dilute every rate on the list. TikTok has no private reply, so those six read----permanently. Misses is the one counter that moves, and the cell already suppresses its percentage when the denominator is nothing but the misses themselves.The analytics page is unaffected — event rows are written for both channels, and it reads the public ones.
Traps worth knowing about
Snowflake ids. The
comment.updatewebhook sends 19-digit ids as JSON numbers, whichJSON.parserounds away —7247303576418566913becomes...567000, and every later API call then addresses a comment that does not exist, with no error to explain it. They are quoted back into strings before parsing, and a test proves a plain parse really does corrupt them.Conversation.sourceId. TikTok used to store the DMconversation_idin the slot reserved repo-wide for comment threads keyed by post id. With TikTok comments a contact would hold two non-null-sourceId conversations andfindDMByContactwould return the wrong one — silently breaking DM routing, read receipts and broadcasts. The id now lives onadditionalAttributes.channelConversationId,dmConversationUsesSourceIdis gone, and a data migration backfills existing rows. (Chatwoot stores its TikTokconversation_idthe same way, onConversation.additional_attributes— this is the upstream convention, not a local invention.)The DM backfill only touches TikTok-only contacts.
Conversationcarries no inbox or channel column — onlycontactIdandsourceId— so "is this a TikTok conversation?" can only be asked of the contact. A contact that also has a Meta inbox owns comment conversations keyed by a Facebook post id, and those are indistinguishable here. Without the restriction, step 2 nulls thesourceIdof a Meta comment thread (losing the post anchor irreversibly), and a contact holding two such threads has both nulled from the same snapshot — violatingConversation_contactId_dm_keyand aborting the migration part-way.TikTok's
ownerflag is the only self-authorship check that channel has.fromId === integrationIdentifiercan never fire: the webhook reports aunique_identifierwhile the integration is keyed byopen_id. So an unresolved enrichment lookup means "authorship unknown", not "ordinary commenter" — the comment is still ingested, but the automation is withheld, because answering a comment that may be the business's own would have the account replying to itself on a channel whose reply no retry policy can retract.The public reply is not idempotent.
business/comment/reply/create/takes no client-side key, so a retry after a partial failure posts a second visible reply.SINGLE_ATTEMPT_COMMENT_AUTOMATION_CHANNELScaps both TikTok and Threads at one attempt; it is an allowlist, so a new channel keeps the default policy only once someone has checked the channel deduplicates for itself.Constraint names are not uniform. The rename migration renames constraints by lookup —
(table, type, columns, target table)— not by their old name. This database carries three conventions side by side: Postgres' own defaults on the two older tables, drizzle's longer form on the two newer ones, and two hashed names where the generated name passed the 63-byte limit. Naming the old constraint explicitly fails on whichever half a given database does not match; the first version of this migration did exactly that and broke on the first foreign key.The migration chain was relinked after merging main. This branch and main's
20260917072620_whatsapp_calling_consolidatedwere generated from the same two parents, so the merge produced two heads and drizzle-kit refused to diff a forked DAG ("Non-commutative migrations detected" — it only shows up on the merge commit CI builds, never locally). The two snapshots are re-linked, not regenerated: the enum migration now descends from the WhatsApp one and carries its parent'sddlplus the single enum value its own SQL adds, and the rename migration keeps its id and parent while taking drizzle-kit's rendering of the current schema — verified to differ from what it held by exactly the 80 WhatsApp entities and nothing else. Two older sibling conflicts are deliberately untouched: they exist identically on main and drizzle-kit does not flag them, because those pairs commute.Deliberately not renamed: the
templateResourceCategoryenum valuefbCommentAutomations, thefbCommentAutomationresourceKind, and the matching key in the template import/export document schema. Those are persisted data, not identifiers — changing them is a data migration on stored templates, which is a separate decision.Known limitation: one person can become two contacts
A TikTok user who both comments and sends a DM becomes two
Contactrows. Comments key the contact byunique_identifier; DMs key it byopen_id, and TikTok exposes nothing that bridges the two id spaces. The repo already has the machinery to link them (ContactInbox.sourceUserId+resolveWithSourceUserIdFallback, built for WhatsApp BSUID vs phone), but it needs one payload carrying both ids, and no TikTok payload does today. Chatwoot does not hit this because it has no TikTok comment support at all.Related and not yet verified: the code assumes
unique_identifieris stable per commenter. If TikTok scopes it per video instead, one person commenting on two videos would also become two contacts. Cheapest check: have one test account comment on two videos of the same page and compare theunique_identifierin both webhook payloads.Verification
pnpm test— 58/58 tasks greenpnpm lint— clean, including i18n parity across all 20 locales and the schema drift guardcheck-types— clean across database, business, analytics, flow-config, worker, builderinvariant-guardclean on the working-tree diffBlocking before this leaves draft
Migrations not applied (three, in order):
20260917000000_normalize_tiktok_dm_conversation— data backfill. Count the rows it will skip first, and the cross-channel contacts it now leaves alone:20260917093208_add_tiktok_comment_automation_type20260918000000_rename_comment_automation_tablesAfter applying, these must all return zero rows:
Ordering matters. The backfill must run before or with the code deploy, not after. Between a code deploy and the backfill, every TikTok DM conversation still carries a non-null
sourceIdwhile the new code looks forsourceId IS NULL, sofindDMByContactmisses: minigame outcome messages return silently, flow variables reading a conversation field return null, broadcast audience counts show zero TikTok contacts, delivery skips them, and read receipts stop. Outbound send keeps working throughout (it goes throughresolveChannelConversationId), which is what makes the symptom hard to read — "sends fine, but broadcast says nobody is there".The same applies permanently to the rows the backfill deliberately skips. An earlier version of this description said those rows "still send correctly, so nothing breaks"; that is true only of the send path —
findDMByContactkeeps missing them, so the five surfaces above stay broken for those contacts until they are reconciled by hand.Two values still needed from the TikTok developer portal, both marked
TODO(tiktok-comments)in place and deliberately not guessed — a wrong scope string makes TikTok reject the whole authorize request, which would break connecting the channel at all, not just comments:TIKTOK_COMMENT_AUTOMATION_SCOPES(integrations/tiktok/src/lib/scopes.ts), not the core list — otherwise a workspace that only wants DMs could no longer connect. Until it lands, the re-authorize warning detects accounts that cannot receive comments, not ones that cannot reply, and every write call is rejected by TikTok at runtime with nothing visible in the UI (like/hide failures do not reach Error Logs; only worker logs record them).event_typeused to subscribe tocomment.update(integrations/tiktok/src/apis/webhook.ts) — without it, comment events only reach apps whose subscription was configured by hand in the portal.One open product decision: the three visibility actions (
set_to_hidden/set_to_friends_only/set_to_public) are currently dropped with a log. The only job that could take them,updateIncomingComment, rewrites the message text, which is not what a visibility change alters. Reflecting hidden state in the inbox needs a new job — out of scope here.Existing TikTok connections must re-authorize to pick up the new scopes; the settings list now flags them.
Follow-ups found while reviewing, deliberately left out
Each is pre-existing on main and unrelated to this branch:
metadata.scopeis written at callback and read nowhere, whileauth/spreadsheetsis a sensitive scope with its own checkbox on Google's consent screen — the same shape as the TikTok bug fixed here, with the data already in hand.recordReplyEventis channel-agnostic, so every Threads public reply writes aCommentAutomationEventrow that is retained for 30 days, purged, and never readable.code— a back button is enough — lands the user on a bare 500.googleCalendaris the one case that does it properly and is a ready-made template.facebookAdsomitsauth_type: "rerequest", which three sibling integrations carry with an explicit comment warning that without it Facebook silently skips a previously-declined permission and returns a token that looks successful.🤖 Generated with Claude Code