Repository navigation
feat(chat): pick one daily suggestion per person and brand each morning (W2-24) - #1872
Conversation
The daily suggestions job (CHAT-26 §3–§7), server only, behind CHAT_AGENTIC and CHAT_AGENTIC_ORGS. Every hour (node-cron, '7 * * * *') it picks, by rules and with no AI call, at most one open Action Center action for each person whose morning it is (07:00–12:00 in their time zone) and writes it to chat_suggestions (00422). Off, it reads nothing. - Who: admins and managers get a feed made for them; agency partners only once their own feed is on (the Inbox makes it, W2-25); analysts never. Never on demo or paused brands, nor in a read-only workspace. - Candidates: new and in_progress actions, not deleted, unassigned or the person's own. Skipped: suggested in the last 14 days, removed, put off until a time still ahead, or waiting in Chat's Needs you (an agent run needs_you on the action, or a waiting run on one of its tasks). - Rank: priority score with the candidate queue's capped wait lift (scoreCandidate), +5 when Start now opens it in the Content Editor, and another category first when yesterday's was the same and the scores are within 5. - At most one a day and 7 in any 7 days; the unique (user, brand, sent_on) index makes a second run send nothing twice. - Summary: structured fields only (kind and the payload keys a title reads, priority score/level/reason, wait, Start now method/pages/ minutes at 4 a page, the play when an action carries one); the web writes the words from en.json. - Rows older than 14 days are deleted; a feed unused for 30 days while suggestions kept coming is paused and stays paused. - Time zone: the person's latest Chat answer's zone, else the one most of the workspace reads in, else UTC (no profile zone is stored yet). - Events daily_suggestion_sent and daily_suggestions_paused go to PostHog's batch endpoint from the server (lib/product-events.js), only when POSTHOG_KEY is set; logs carry counts and codes only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and keep brands apart Review fixes for the daily suggestions job (CHAT-26), on top of 9e9f70382. - Pause: 30 days from the first suggestion since the last use, with at least 7 sent since that use and none used. Suggestions are kept only 14 days, so the job marks the feed (an update; the trigger stamps updated_at) when it sends the first one after a use, and counts from there. A feed that got one after a long quiet spell isn't paused the next day. - A removed suggestion keeps its action away even when it was put off first and its week is over. - A feed made or turned back on today (created_at or updated_at on the person's today) that got none yesterday starts tomorrow morning (CHAT-26 §5), with no new column. - Each brand runs in its own try/catch; the run's events go to PostHog once, at its end, whatever failed. - Candidates: the unassigned open actions and those assigned to the people due, 500 of each, so actions assigned to others never take the places. People are read page by page. - Summary size counts a byte per comma and colon (jsonb's text adds a space after each), under a 20,000-byte ceiling. - Server events carry $geoip_disable, as posthog-node does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk
left a comment
There was a problem hiding this comment.
I reviewed what this PR adds: server/src/lib/chat-suggestions/* (job, rules, summary), product-events.js, the server.js start, and the three exports in chat-flag.js and content-published.js. It adds no migration and reads and writes 00418, 00419 and 00422, which are on main. Approving with 87aa37a: a merge of current main and one fix commit, with a test that fails without it.
The fix commit
A cut emoji fails the brand's whole insert. clip in summary.js cuts payload texts with slice(0, max), which counts UTF-16 units. When the 300th (or the 1,000th for why, or the 100th for the play's id) unit is the first half of an emoji, the cut leaves a lone surrogate. JSON.stringify writes it as \ud83d, and Postgres refuses that in jsonb ("Unicode low surrogate must follow a high surrogate"). All of the brand's rows go in one upsert, so nobody in that brand would get a suggestion. The same action would still rank first the next hour and the next day, so it would keep failing.
clip now drops a trailing first half. The new titlePayload test ("never cuts an emoji in half") covers a long prompt text, why and a target label, and checks that a whole emoji before the cut stays. It fails without the fix.
No open action has a text that long today, so this hasn't happened yet. It only needs one long prompt text with an emoji.
What we checked
-
How it starts.
server.jscallsstartDailySuggestions()only insidechatAgenticDeployed(). It's an in-processnode-cronat :07 every hour, with no route, so there's no secret to compare. A run still going makes the next tick skip (running), and a crash is logged. -
Chat off.
runDailySuggestionsreturns before any read withoutCHAT_AGENTIC=true.loadBrandsfilters byCHAT_AGENTIC_ORGSin the query (.in('organization_id', …)) and again withchatAgenticEnabled. The 14-day delete runs for every workspace, which is fine because it only removes what's expired. -
Who's skipped.
- Demo brands (
is_demo = false) and paused brands (is_active) are left out. - Read-only workspaces are left out on the cloud with the same
isSubscriptionActiverule the web'sassertWritableuses. - Analysts and unknown roles are left out (
roleFeed→never). - Agency partners only get suggestions once a feed exists for them, and W2-25 creates it.
- People come from
profilesby the workspace's id. Someone who left keeps a feed row, but it's never matched again. - A feed that's
offorpausedis never sent.
- Demo brands (
-
One a day.
- The morning window is 07:00–12:00 local.
sent_onis the person's local day. - The unique
(user_id, brand_id, sent_on)withignoreDuplicatesis the backstop. MIN_GAP_HOURS(12) stops a second one in a morning when the zone changes.- Rolling 7 in 7 days.
- Rows older than 14 days are deleted. A new or turned-back-on feed waits until the next morning.
- The morning window is 07:00–12:00 local.
-
Retries and two servers. Events come only from the rows the upsert actually inserted, so a second run sends no duplicate events. A pause is a conditional update on
status = 'on'and theupdated_atthat was read, so only one run pauses a feed and counts it. -
Pause. The feed pauses when 30 days have passed since the first suggestion after the last use, and at least 7 unused suggestions are still kept. The
updated_atmark keeps the count from restarting when the 14-day delete removes the first row. A feed that gets one suggestion after a long gap isn't paused. -
No AI call.
rules.jsandsummary.jsare pure. Ranking is the priority score, the queue's wait lift, +5 for Start now, and variety within 5 points. The summary holds structured fields only, kept under 20,000 bytes counted as jsonb's text (the check is 32,000). -
Which actions.
- The brand's own actions with
new/in_progressthat aren't deleted. - Unassigned ones or the person's own. Assigned ones are read per chunk of the people due, so other people's assignments don't fill the 500.
- Not ones suggested to that person in the last 14 days, removed, put off for a week, or waiting in Needs you.
- All roles can read the brand's actions, and agency partners use every brand today.
- The brand's own actions with
-
The action is never changed. The job only writes
chat_suggestionsandchat_suggestion_feeds. It only readsactions,action_tasks,chat_agent_runsandchat_task_state. -
Bounded work.
- Brands and profiles are read 1,000 rows a page.
- Up to 500 candidates per brand, plus 500 per chunk of assigned people.
- At most 300 recent answers per workspace for time zones.
INlists go throughselectInChunks.- Only workspaces with someone in their morning read past their profiles.
- Each workspace and brand has its own try/catch, and events go out once in
finally.
-
Time zones. The zone comes from
chat_messages.timezone, which the web already validates (validTimezone). It's checked again withIntl. The format cache only grows with real zone names. -
Events.
product-events.jsposts to PostHog's/batch/with a 10 s timeout, 500 a request. It never throws, and it sends nothing withoutPOSTHOG_KEY. Properties are ids, category, level, booleans and counts, with$geoip_disable. Thedistinct_idis the user id, the same one the web'sidentifyuses. -
Embeds: three, each with a hint and each over exactly one foreign key:
chat_messages→chat_conversations(chat_messages_conversation_id_fkey);chat_task_state→action_tasks(chat_task_state_action_task_id_fkey);chat_task_state→chat_runs(chat_task_state_run_id_fkey).
The statuses filtered on (
needs_you,waiting) are in the tables' checks. -
Logs: codes and counts only.
Follow-ups (not blocking)
- Already on your list: when Agency partners get chosen brands, the job should read the feed's brand against them. Today they use every brand, so nothing to do yet.
- Until people have Chat answers, every zone is the workspace's or UTC. At launch everyone starts at 07:00 UTC (10:00 in UTC+3), and it moves to their own zone after their first answer. CHAT-12's profile zone fixes this for good.
- The pause count uses
updated_atas its mark. Any later feature that updates a feed for another reason (for example, a settings field) would restart the 30 days. Afirst_unused_atcolumn would make it explicit when one is added. - There's no time limit for a run. At today's size it's a few dozen small queries, and the
runningguard covers a slow hour. Worth a deadline once there are hundreds of workspaces.
Manual test (third-party: PostHog)
With POSTHOG_KEY/POSTHOG_HOST set on a test server and CHAT_AGENTIC=true for one test workspace, run runDailySuggestions() once in that workspace's morning. Check in PostHog that:
daily_suggestion_sentarrives on the person's existing profile (same distinct id as the web);- it has no location properties;
- a second run in the same hour sends nothing.
Without the key, check that the log says nothing was sent and no request goes out.
Tests
On this branch (this PR's head fafa8adcb + current main 703a68600 merged in, clean + the fix):
chat-suggestions+product-events: 73 passing. The new test fails without the fix.- Full server suite: 337 files, 4,661 passing (3 skipped).
- Prettier and eslint on the changed server files: clean.
plan-row.test.ts: passing. The PR touches no web code.- Merging on current main: clean.
gkhngyk
left a comment
There was a problem hiding this comment.
Merging in order with the other approved PRs. This head merges current main; its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build.
Summary
Chat W2-24: the job that picks each person's daily suggestion (CHAT-26 §3–§7): one open Action Center action a morning, per person and brand, chosen by rules with no AI call. Server only, behind
CHAT_AGENTIC(andCHAT_AGENTIC_ORGS). The Inbox rows and the detail page come in W2-25 and W2-26.Built on main, but deploy after #1853. The code adds no migration. It reads and writes the tables from 00418, 00419 and 00422 (
chat_suggestions,chat_suggestion_feeds,chat_task_state,chat_agent_runs), so it must ship after #1853's migrations. While Chat is off it reads nothing.When it runs
server.jsonly when Chat is deployed.Time zone order
Profile and workspace zones come with CHAT-12.
Who gets suggestions (CHAT-26 §6; DECISIONS V)
brands.is_demo);Candidates
new,in_progress), unassigned or assigned to the person. Two queries of up to 500 each, so other people's assignments don't fill the window.Ranking
What's stored (
summary)Keeping and pausing
Rows older than 14 days are deleted.
A feed pauses only when both are true:
A single suggestion after a long gap never pauses it the next day.
A feed created or turned back on today waits until the next morning (§5).
Isolation
Events:
daily_suggestion_sentanddaily_suggestions_pausedgo to PostHog through a small newserver/src/lib/product-events.js(fetch to/batch/, no new package).$geoip_disable: true.POSTHOG_KEY, nothing is sent.Related issue
None. Chat Wave 2 (W2-24, CHAT-26).
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
cd server && npx vitest run src/lib/chat-suggestions src/lib/product-events.test.js. The tests cover:CHAT_AGENTIC=true, start the server and call the job once (runDailySuggestions). It should write one row per Admin or Manager and brand with open actions, between 07:00 and 12:00 in their zone.The PostgREST joins (
!fk!innerhints, the embed filters) were run read-only against the dev database. They return without errors, and none is ambiguous.Checklist
yarn lintpasses (run fromweb/): web isn't touchedyarn typecheckpasses (run fromweb/): web isn't touchedyarn format:checkpasses (run fromweb/): web isn't touchedhelp/(or no user-visible change): nothing user-visible yet (W2-25 adds the Inbox and its Help)Server on this branch (current main + the two commits):
npm run formatchanges nothing,npm run lintis clean, andnpm testpasses 337 files / 4,639 tests (3 skipped).For production (@gkhngyk):
CHAT_AGENTIC=true. Restart the server after the flag is on.POSTHOG_KEYandPOSTHOG_HOSTto the server environment, with the same values as the web'sNEXT_PUBLIC_POSTHOG_*.Follow-ups, not in this PR
🤖 Generated with Claude Code