Commit graph

37 commits

Author SHA1 Message Date
Paulo Castellano
58d8e066b5
Add workspace webhooks and drop the unused automation webhook node (#326)
* Add workspace webhooks and drop the unused automation webhook node.

Give workspaces HMAC-signed outgoing webhooks for the post lifecycle, with retry, auto-pause, replay, and live logs, and keep HTTP Request as the only outbound automation node.

* Tighten webhook controller and validation after review.

Drop the redundant workspace redirects, prune logs without counting, and validate events/status with Rule::enum.

* Move leftover webhook UI copy behind i18n.

HTTP status phrases, delete-cancel, and validation attribute names were still English literals.

* Build the webhook-paused email through Maizzle.

The hand-written Blade skipped the shared layout, header, and footer used by the other mail templates.

* Cover real webhook dispatch paths and restyle the webhook pages.

* Ask for the shared delete keyword when confirming a webhook delete.

The endpoint URL is a poor confirm string; posts and assets already use the common "delete" keyword.

* Fix webhook review blockers so CI can go green.

Drop leftover French automation keys, stop mutating Inertia log props, and show delivered_at instead of created_at.

* Close the remaining webhook review gaps.

Keep Echo log updates across infinite scroll, align the channel with the policy, persist log ids across retries, and fail unknown automation nodes without throwing.

* Stop webhook delivery after disable and record last sent only on success.

Queued jobs now skip paused or disabled endpoints unless the user replays, and changing the URL re-pings it first.

* Limit webhooks to owners and admins, and encrypt signing secrets.

Members can no longer create or inspect outgoing integrations, and secrets stay encrypted at rest.

* Cover webhook secret hiding, skip-ping, and failed-delivery edges.

* Send the full post on webhooks after labels and platforms are saved.

* Fix webhook payloads for integer media ids and type webhook status.

* Split the webhook show page into focused components.

* Reset live webhook logs when switching endpoints.

* Keep the newest webhook logs at the top after live merges.

* Cast media item ids to string without the extra scalar check.

* Add post.unscheduled webhooks and put the log id on the envelope.

Unscheduling is now a first-class event, and receivers can send the delivery id back so we can find the matching log.

* Translate webhook event names in the UI.

* Make the webhook show page full-width and stop stacking flash toasts.

* Translate remaining webhook UI copy in every locale.

* Sign webhook pings and drop author email from the payload.

* Send signed webhook tests after create instead of pinging on save.

Create and update only block private URLs so the receiver can copy the secret first. The show page then sends a signed webhook.test with an object data envelope.

* Polish webhook test UX and always mint the dispatch log id in the job.

Keep send-test in the actions menu (its own group) and drop the leftover constructor param so retries reuse the serialized id instead of a caller-supplied one.
2026-09-04 09:43:29 -03:00
Grigory Frolov
0db9e0706d
Visible Terms and Privacy links on the auth screens (#317)
* feat: visible Terms/Privacy links on the auth screens

Social-platform app reviews (TikTok explicitly) require both links to be
reachable from the public site without logging in or opening a menu.

* Cover the legal links with tests and tidy the layout

The links are a compliance artifact an outside reviewer checks, but
nothing asserted they exist. A refactor of this layout could drop the
footer silently and the next platform submission would fail the same
check that prompted the PR. A feature test asserts the shared prop
reaches both guest screens and carries whatever the install configured,
and a browser test asserts the two links actually render to a logged-out
visitor.

Declares legal on SharedData, so the props read through the interface
rather than its index signature and the inline cast goes away.

Adds rel="noopener noreferrer" to both anchors, matching every other
target="_blank" in the codebase, and orders the imports the way eslint
expects so the file lands clean rather than relying on --fix in CI.

Drops the comment explaining why the links are there: that rationale
belongs in the commit and the pull request, and the sibling comments in
this file describe markup rather than justify decisions.

* Reuse the legal sentence the register screen already had

The register screen has shown "By continuing, you agree to our Terms of
Service and Privacy Policy" in production for a long time, translated
into all sixteen locales. Only the login screen was missing it, and the
two URLs were hardcoded inside the translated string, so a self-hosted
install could not point them at its own documents.

So this keeps what already worked and changes only those two things. The
markup moves into one component, which the login screen now renders as
well. The translated sentence keeps its wording and its link labels; only
the href becomes an i18n placeholder that the component fills from
config. That is one line per locale, and no new translation keys.

Reverting the footer out of AuthSplitLayout also stops the links from
appearing on the workspace index and create screens, which reach that
layout too and are seen after login rather than before it.

The sentence no longer hides on a self-hosted install. It was hidden
because it named TryPost's own documents; now that the URLs are
configuration, an install that sets them wants it shown.

A feature test covers the shared prop on both screens and the placeholder
in every locale; a browser test covers the rendered sentence, since the
links are a compliance artifact an outside reviewer checks and nothing
guarded them.

* Let the browser assertions do their own waiting

The test hand-rolled a polling loop in injected JavaScript to wait for
the element to mount, because the project notes say browser assertions do
not wait for SPA paint.

They do. visit() returns a PendingAwaitablePage backed by
AwaitableWebpage, whose __call wraps every method in
Execution::waitForExpectation and retries until the Playwright timeout,
which defaults to five seconds. The plugin even deprecates waitForText in
favour of assertSee for this reason. The loop was re-implementing the
retry that already surrounded each call, less well and with a helper
whose name has to be unique across the whole suite because these are
global functions.

Halves the file and drops the injected script. assertSeeLink also says
more than the old check did: it asserts the labels are links, not just
text that happens to appear.

---------

Co-authored-by: Paulo Castellano <paulo@castellanos.llc>
2026-09-01 18:20:38 -03:00
Paulo Castellano
02e44b9785
Connect the Pages a login only reaches through a Business Portfolio (#301)
* fix: Facebook Page fetch missing New Pages Experience pages

/me/accounts silently omits Pages that live under Meta's newer
"New Pages Experience" / Business Portfolio model, even when the
token's granular scopes show the Page was explicitly granted -
confirmed via Meta's own Access Token Debugger against a live
account whose Page returned zero results from /me/accounts but
resolved fine when queried directly by ID.

Falls back through Business Manager's owned_pages/client_pages
(via the existing business_management scope) when /me/accounts
comes back empty, so Pages under that model are still found.

* fix: Instagram-via-Facebook has the same New Pages Experience gap

Same root cause and fix as the FacebookController fetchPages()
fallback - the Page/Instagram-linked-Page lookup goes through the
same /me/accounts call and is subject to the same Meta-side gap.

* refactor: one place finds every Page a Meta login can publish to

Both controllers walked /me/accounts and, when it came back empty, the
Business Portfolio edges behind it. ManagedPages now owns that walk for
the Facebook and Instagram-via-Facebook flows alike.

Three behaviour changes come with it:

The portfolio edges are read on every connect, not only when /me/accounts
is empty, and merged by Page id. Someone holding one Page by a classic
role and the rest through a portfolio was auto-connected to that single
Page and never offered the others.

/me/businesses is read only once /me/permissions confirms the login
granted business_management, and a failure anywhere along the portfolio
walk leaves the /me/accounts list standing. It used to escape into the
callback's catch, turning "no pages" into "could not connect" for every
login without the scope.

Pages the login cannot get an access_token for are dropped. Connecting
one produces an account that cannot publish.

* test: pin the Page a login only reaches through a portfolio

Covers the merge with /me/accounts, the access_token filter, the
business_management gate, and a failing portfolio edge leaving the
/me/accounts list intact — plus the connect flow end to end on both
Meta platforms.

The Instagram-via-Facebook request count moves from five to six for
the /me/permissions check.

* refactor: read the portfolio edges without asking permission first

The /me/permissions check saved a rejected /me/businesses call on logins
without business_management, at the cost of running a path nobody had
verified against a live account. The edges already fail soft, so the
check bought log tidiness and nothing else.

* test: cover the portfolio walk's remaining shapes

The multi-Page selection flow behind a portfolio — the case #292 asked a
maintainer to check — plus pages spread across two portfolios, a
paginated edge, a portfolio entry with no id, and a portfolio page
merging with one /me/accounts already returned.

* test: stop the Meta connect tests from calling Graph for real

Http::fake only stubs the URLs it is given; anything else goes out over
the network. These files stubbed /me/accounts and left /me — and now
/me/businesses — unstubbed, so the suite was issuing live requests to
graph.facebook.com on every run. They came back 400 and the code under
test swallowed them, so nothing ever went red while the assertions were
measuring Meta's answer instead of the fixture's.

Every Graph call the connect flow makes is stubbed now, and the files
prevent stray requests so a missing one fails loudly. Inertia's SSR
endpoint is allowed through; it is not what these tests are about.

* fix: tell a denied portfolio edge apart from a throttled one

GraphPaginator throws so no caller reads a failed fetch as an empty list
and auto-connects whatever arrived first. Swallowing that exception on
the portfolio edges gave the invariant away: a 429 on owned_pages left
the merged list holding only the /me/accounts page, and the callback
connected it with no picker.

The exception now carries whether the failure was transient, classified
by GraphError, which already owns Meta's rate-limit and transient code
table. A denied permission reads as "this login reaches no portfolio
pages"; a throttle, a 5xx or a truncated walk is raised.

The walk also stops at MAX_PORTFOLIOS and logs what it skipped. Each
portfolio costs two more paginated edges inside a synchronous OAuth
callback, and nothing bounded that loop.

* fix: three ways the portfolio walk misread what Meta returned

Concurrent Instagram lookups. The Instagram description ran one request
per Page, in sequence, at a 15s timeout each. That list used to be the
Pages someone holds a role on — a handful. It is now the union with
every portfolio's owned_pages and client_pages, so a portfolio holding
hundreds of Pages serialised the OAuth callback past any gateway
timeout, for exactly the accounts the portfolio walk exists to reach.
Meta's ids= batching is no help: each Page carries its own access token
and one call takes one token. The lookups run in concurrent rounds.

A Page without a token is not a Page you don't have. Meta lets someone
decline pages_read_engagement on its per-permission toggles and still
lists the Page, without an access_token. Dropping it inside the walk
left the caller saying "no Pages found, you need to be an admin of at
least one" to an admin. ManagedPages returns everything Meta listed and
publishable() separates what can be posted to, so the callbacks can
tell the two apart and say which one happened.

Stored scopes are what Meta granted. The scope list was written to the
account's scopes column straight from the request, claiming access the
login may have refused — business_management above all, which needs
Advanced Access and is declined by default without it. It now comes
from /me/permissions, falling back to the request when Meta cannot be
asked.

* fix: only drop a scope Meta says was refused

PublishToSocialPlatform::failForMissingScopes() blocks a post when a
platform's required publish scope is absent from the account's scopes
column, so writing that column from /me/permissions can dead-end an
account. Meta does not document that the endpoint echoes scope strings
verbatim, and the edge is paginated, so a scope it never mentions is
unknown rather than refused and stays. Only declined and expired drop.

* fix: keep the portfolio walk honest and cheap

Raise instead of truncating. The ceiling logged a warning and returned
whatever fit, which is the one thing this module refuses to do
everywhere else: if the walk cannot finish, the real list is unknown,
and a truncated list holding exactly one Page would have been
auto-connected without ever showing the picker. It now raises, and the
ceiling rises to GraphPaginator::MAX_PAGES' 100 since the walk no
longer pays for it serially.

Read the edges concurrently. Up to two paginated edges per portfolio ran
back to back inside the OAuth callback. They run in rounds now; a URL
that does not come back cleanly still goes through GraphPaginator, which
owns the single place that logs a Graph failure and decides whether it
is a rejection or an unknown.

Prefer the record that carries a token. Merging kept whichever copy of a
Page id arrived first, and /me/accounts always arrives first — so a Page
listed there without a token buried the portfolio copy that had one, and
the login was told its permission was missing for a Page it could reach.

Describe only the Instagram accounts that survive. The per-Page lookup
ran before filterConnectableIdentities discarded them, spending a
BUC-rate-limited call on every Page only to throw the answer away. The
filter reads instagram_business_account.id straight off the raw Page, so
it needs no lookup to run first.

Two Instagram tests mocked Socialite without usingGraphVersion, so the
callback threw, the generic catch answered, and asserting only
success=false passed on the error path instead of the one under test.

* test: pin that pages survive past the first pooled round

The concurrency test drove 30 portfolios with every edge empty, so the
merge across rounds was never exercised with data in it.

* fix: keep the paging-host guard on the pooled edge walk

GraphPaginator refuses to follow a paging.next that points off the host
the walk started from, so a tampered response cannot carry the access
token somewhere else. Reading the first page of each edge through the
pool and handing its paging.next straight back to GraphPaginator made
that URL the *start* of a new walk, which is the one URL the guard
trusts implicitly — so the first hop went unchecked.

The host is compared before the hand-off now, and a mismatch re-walks
the edge from the beginning so GraphPaginator's own guard is what
refuses it, with its logging.

* fix: stop a cut-short walk from passing for a complete one

optional() was written for "this edge may be forbidden" and answers a
rejection with an empty list. Following paging.next through it gave a
rejected cursor the same answer: page one of a 250-Page portfolio came
back and the rest was dropped, and a single connectable Page in that
fragment would have been auto-connected with no picker. The same hole
sat on /me/businesses, where GraphPaginator is all-or-nothing — a
failure on page two threw away the portfolios page one had already
listed, degrading the connect back to /me/accounts alone in silence.

The exception now carries how many pages arrived. Only a rejection on
the very first request reads as "this edge is not readable"; anything
after that is a fragment and raises. Cursors skip optional() entirely.

A login Meta reports as refusing business_management also stops walking
the edges at all. The controllers already read /me/permissions for the
scopes column, so the answer costs nothing, and the walk was otherwise
spending a request on a certain 403 — and logging it at error level —
on every successful connect by such a login.

An Instagram account with an empty Name connected as display_name null:
data_get's default only fires on an absent key, and describeRound always
writes the key.

* test: pin reconnecting a card only the portfolio still reaches

A card whose Page moved behind a portfolio is the reconnect shape of the
bug this branch fixes, and nothing covered it: the walk has to find the
Page, and filterConnectableIdentities has to keep the original card
rather than offering the portfolio's other Pages.

* fix: an unreadable portfolio must not deny the pages that were readable

The portfolio edges are additive, but every failure in them was raised
and the callback's generic catch turned it into "error connecting" — so
one throttled edge among sixty denied a login the Pages /me/accounts had
already returned, and each retry burned more of the quota that caused it.
Only /me/accounts failing is fatal now; everything else marks the walk
incomplete and keeps what arrived.

What the raise was protecting is kept where it belongs: a lone Page is
only taken without asking when the walk saw everything, or when a
reconnect has already pinned which Page is wanted. Otherwise the picker
opens, and the login can see for itself that its Page is not there.

The ceiling stops pretending. It compared the count after walking every
page of /me/businesses — up to ten thousand ids — so the runaway it
existed to bound had already happened. One request, one page, and more
portfolios than that is an incomplete walk rather than a failed one.

A pooled edge that fails is classified where it lands instead of being
re-fetched, halving the cost of the common client_pages rejection, and
GraphPaginator logs a confirmed rejection at warning: it is Meta
answering the question, not something going wrong.

A login that declined the permission its platform needs to publish is
refused at connect. Meta issues a Page token off pages_show_list, so
declining pages_manage_posts still produced a green account whose every
scheduled post was then hard-failed by failForMissingScopes.

Test fakes address Graph through the config rather than a literal host,
which is what CLAUDE.md asks for and what the newer tests already did.

* fix: an incomplete walk must not answer as if it were sure

Marking the walk incomplete stopped the auto-connect, but every dead end
after it still gave a definitive answer. A login whose only Pages sit
behind a throttled portfolio was told "no Facebook Pages found, you need
to be an admin of at least one" — the exact sentence this branch exists
to stop showing to admins, now arriving for a different reason. The
already-connected and missing-permission answers were equally sure of
themselves.

When the walk could not see everything and there is nothing to offer,
it says so and asks for a retry.

* fix: stop every Inertia test from calling an SSR server

inertia.ssr.enabled defaulted to true and nothing in phpunit.xml turned
it off, so every test rendering an Inertia page issued a real request to
the SSR endpoint. The project does not use SSR, so those calls only ever
failed and fell back to client rendering — quietly, on every run.

Defaulting it off is what the project already assumed, and it retires
the allowStrayRequests hole the Meta connect tests were carrying to work
around it. INERTIA_SSR_ENABLED still turns it back on.

* fix: a taken slot is a fact, not a guess about the listing

Routing every short listing to "try again in a moment" swallowed
network_taken: a workspace that already holds its one Facebook account
was told to retry, forever, whenever a portfolio edge was throttled. That
answer comes from our own rows and does not depend on how far the walk
got. all_connected and page_not_found do, and still yield.

Also: an off-host cursor now stops the edge instead of re-reading page
one, which cost a request and could follow an on-host cursor on the
retry, quietly undoing the guard. Cursor follow-ups are budgeted, since
they cannot be pooled and were the one unbounded serial path left. The
exception's fetched count lost its last reader two commits ago and is
gone. Comments trimmed throughout.

* fix: bound the cursor walk by requests, and keep what it read

MAX_CONTINUATIONS counted edges, not requests: each one then handed off
to GraphPaginator, which follows up to a hundred more pages by itself.
The budget the docblock promised was fifty times larger than it claimed.
Cursors are now followed one budgeted request at a time, so the count
means what it says, and pages already read survive a cut-off instead of
being thrown away with the exception.

A refused /me/businesses is no longer read as "this login has no
portfolios". For a single edge a rejection answers the question; for the
index of edges it means we could not look — and answering complete there
auto-connected the one /me/accounts page while hiding every portfolio
Page, which is this branch's own bug wearing a different hat.

SSR goes back to its shipped default. Turning it off in config to quiet
the test suite would have disabled it wherever it is actually started —
docker/Dockerfile builds the bundle. phpunit.xml carries the switch now,
next to PULSE, TELESCOPE and NIGHTWATCH, and CLAUDE.md records why.

* refactor: one Meta connect flow instead of two kept in step by hand

The Facebook and Instagram-via-Facebook callbacks ran the same twenty-five
lines: the profile touch Meta's review wants, the granted-scope read and
the publish-scope refusal, the page walk, and the answer for a walk with
nothing to offer. They only matched because both were edited side by side,
every round, which is a guarantee nobody should be making by hand.

graphApi() moves to SocialController and reads the host by platform value,
so it serves every network rather than the two that had copied it, and
graphVersion() derives from it instead of reading config a second time.

select() stays as it is. The two differ in the middle — different identity
keys, different connect shapes — and folding them would be abstraction for
its own sake.

* fix: default Inertia SSR off, where this project already stands

Nothing in the repo starts an SSR process, so the shipped default was
describing a setup that does not exist. With it off the test env needs no
override of its own, and CLAUDE.md records that turning it on means
starting the process, not just flipping the env.

* fix: one rule for a refused portfolio, and a clock on the walk

Last round I made a refused /me/businesses mark the walk incomplete, on
the argument that refusing the index means "we could not look". That was
wrong in the case that matters most: an app without Advanced Access for
business_management gets that refusal on every single connect, so every
login on such an install lost auto-connect and every login without Pages
was told to retry forever. Self-hosted in Live mode is exactly that.

The rule that holds everywhere: a Page this login cannot enumerate is a
Page it cannot get a token for, so it was never connectable, and the list
of connectable Pages is complete. Only an unknown — a throttle, a hiccup,
a budget or a ceiling — leaves the walk unable to vouch for itself. Index
and edge now answer the same way, which is also what makes the two
readable together.

The per-request budgets were each bounded while their sum was not: ten
pooled rounds plus twenty-five cursor requests can outlive nginx's
fastcgi_read_timeout of 120s. The walk now carries a deadline and returns
what it has.

touchProfile exists only because Meta's review wants the call. It had no
timeout and no guard, so a hung /me could stall the callback to the
gateway timeout or fail a connect outright, over a response nobody reads.

* docs: the walk's contract changed under its own docblock

It still said any failure marks the walk incomplete, which stopped being
true when a refusal became an answer. A docblock describing an invariant
the code no longer holds is how this branch got two of its bugs.

* fix: put the whole callback inside the budget it advertises

meta_page_walk_seconds bounded the portfolio half of the walk and nothing
else. /me/accounts could paginate a hundred pages at fifteen seconds
each, and the Instagram lookups pooled in rounds that were themselves
serial — a portfolio with three hundred linked Pages is fifteen rounds,
after the walk had already spent its own budget. Both honour the deadline
now. The lookups skip rather than drop: the Page still connects, only its
handle and avatar arrive empty. The first request is always made; the
budget bounds what comes after it.

A Graph body that is valid JSON but not an object — a proxy answering
"throttled" — reached GraphError::isTransient, whose parameter is ?array,
and under strict_types raised a TypeError. That is an Error, so it walked
past both callbacks' catch(\Exception) and 500'd the popup instead of
showing a message.

Refusing a login before any listing has happened no longer borrows the
wording for "we found your Pages but not the permission to post to them".

composer run dev no longer starts an SSR process for SSR that is off, and
CLAUDE.md no longer claims nothing in the repo starts one, which
composer.json contradicted.

* fix: say what actually gets a Page token, per Meta's own reference

The Page node reference is explicit: access_token is "only returned if
the User making the request has a role (other than Live Contributor) on
the Page". Being an admin of the portfolio that owns a Page lists it but
does not grant that role, so the walk can surface Pages this login will
never get a token for.

The popup told those users to reconnect and accept every permission,
which cannot produce a Page role and so could never work. It now names
the role as well.

I rejected this in review on the grounds that a portfolio Page had been
published to successfully in the wild. That proved a token comes back
when the login holds a role, not that one always does.

* fix: one budget for the callback, not one per phase of it

The walk and the Instagram lookups each opened a full
meta_page_walk_seconds, on top of the profile touch and the permission
read, so the callback's worst case was several times the single bounded
budget config/trypost.php advertises. They share one deadline now, taken
once and passed down. META_PAGE_WALK_SECONDS joins .env.example.

An Instagram account described past that deadline arrived with no handle
and no name, and a lone one was then persisted with display_name null —
a blank, unidentifiable card. It falls back to the Page's own name.

Two docblocks were describing behaviour the code does not have.
/me/accounts is the base every other Page is added to, so running out of
budget there aborts rather than degrades, and the class now says so
instead of promising a partial list. GrantedPermissions justified
treating an absent permission as unknown but said nothing about a failed
request, which lands in the same place for a different reason.

* fix: a Pages throttle on a user token was reading as a refusal

Meta's BUC rate-limit table lists code 32 for the Pages API when called
with a User token. GraphError did not carry it, because until this branch
nothing in the app called a Pages surface that way — the publishers use
Page tokens, where the same throttle arrives as 80001.

The portfolio walk does: /me/accounts, /me/businesses and both edges are
read with the user token straight out of OAuth. So an ordinary throttle
came back as code 32, was classified as a confirmed rejection, and the
walk concluded this login simply reaches no portfolio Pages — vouching
for a list missing all of them and auto-connecting whatever /me/accounts
happened to hold. A rate limit was producing the exact silence the
complete flag exists to prevent.

* fix: a reconnect no longer loses its handle to a slow Graph

persistIdentity updates a reconnected card with whatever it is handed,
so a described-with-nulls card overwrote a working account's username
and avatar. Skipping the Instagram lookup — which the shared budget now
does whenever the walk spent it — produced exactly that card. A lookup
that never ran says nothing about a handle the account already has, so
those two keys are left out when it did not.

Refusing the portfolio index goes back to marking the walk incomplete. I
had it that way, reversed it, and this settles it: Meta's Page reference
returns access_token for a Page the login holds a role on, and a Page can
carry that token on a portfolio edge while /me/accounts omits it — which
is this branch's entire premise. So refusing one edge does say those
Pages are unreachable, but refusing the index says no edge was read at
all, and the Pages behind it may well have been connectable. Silently
vouching for a list without them is the original bug.

The budget also starts before the walk and now shapes each request's own
timeout, so no single call can outlive it by fifteen seconds.

composer dev:ssr was a slower alias of composer dev once the SSR process
came out of it.

---------

Co-authored-by: StoriaJames <james@storia.tech>
2026-08-26 10:42:59 -03:00
Hafiz Muhammad Moaz
91c3d86d86
Allow multiple social accounts per network via env (#286)
* feat: expose self-hosted mode to the accounts UI

SocialAccountObserver already bypasses the one-account-per-network
guard when trypost.self_hosted is true, but the frontend had no way
to know that and always collapsed a network to a single card once
any account existed - so self-hosted deployments could not surface
a second LinkedIn (or Instagram) connection even though the backend
would allow creating it.

* feat: allow connecting multiple accounts per network when self-hosted

NetworkConnectGrid always collapsed a network (LinkedIn profile/page,
Instagram standalone/Facebook) to a single card once any account
existed, with no way to trigger another OAuth flow - even though
SocialAccountObserver already allows unlimited accounts per network
in self-hosted mode. A self-hoster connecting their personal LinkedIn
profile had no path back to the connect flow to also add a company
page (or a second company page/showcase page).

Render one card per connected account instead of collapsing to the
first, and keep a standing "Connect another" card available for a
network's existing connections when self-hosted. Hosted mode is
unchanged: still one card per network, matching the backend's
still-enforced one-account-per-network limit there.

* test: cover the selfHosted prop on accounts and onboarding pages

Backend behavior for connecting a second identity per network in
self-hosted mode was already covered (LinkedInControllerTest,
NetworkUniquenessTest) - these just confirm the new prop the frontend
now depends on is actually present and reflects config correctly.

* style: apply prettier formatting

Pre-existing drift in this file unrelated to the selfHosted change.

* refactor: read selfHosted from shared Inertia props

The flag is already shared by HandleInertiaRequests, so the accounts
and onboarding controllers do not need to pass it again.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: gate multiple social accounts with a dedicated env

Cloud cannot flip SELF_HOSTED, so one-per-network is now ALLOW_MULTIPLE_SOCIAL_ACCOUNTS (default false).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: tighten multiple-account gates after review

Keep every connected identity visible, share occupiesNetwork, and return network_taken instead of a generic connect error.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: bind reconnect to the card and unique social identity

Reconnect now updates the selected account, and a unique index plus connectIdentity keep the same platform identity from being inserted twice.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: build the OAuth URL before opening the popup

Keep the popup opener URL-only so reconnect query params are assembled at the call site.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: drop dead social-account guards and slim the connect grid

Skip migration cleanup that production never needs, trust the platform enum in the observer, and move card theming out of the grid.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: scope social reconnect to the current network

Drop dead instanceof/isset guards and filter reconnect targets in the query so a stale session cannot update another network's card.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: slim connectable-identity filtering

Index OAuth identities by id so reconnect and occupancy use only/except instead of hand-rolled filters.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: slim social identity persist helpers

Drop the unused occupiesNetwork exception and persist reconnects with update() instead of fill/save/fresh.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: keep reconnect updates on the original social card

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: run the suite with multiple social accounts enabled

phpunit.xml forced ALLOW_MULTIPLE_SOCIAL_ACCOUNTS=false, overriding the
true value in .env.ci. That broke eight tests across Automation, MCP,
PostApi, RefreshExpiringTokens and VerifyUpcomingConnections which only
needed two accounts of one network as a fixture, not as a rule under test.

Match .env.ci instead. Every test that exercises the one-per-network rule
already sets the config itself; the accounts index test was the only one
leaning on the implicit default, so it now pins it.

* fix: align the multi-account fallback with the self-hosted default

allow_multiple_social_accounts fell back to env('SELF_HOSTED', false)
while self_hosted itself defaults to env('SELF_HOSTED', true). A
self-hosted install that never wrote SELF_HOSTED to its .env resolved to
false and silently lost multiple accounts per network on upgrade, which
is the opposite of what the documented fallback promises.

* fix: collapse duplicate identities before adding the unique index

Installs predating the index can hold the same identity twice: the
network guard was bypassed for multi-account installs and Pinterest
always created a fresh row. Creating the index on that data aborts
migrate mid-deploy.

Keep the newest row per identity and move its post_platforms over before
dropping the duplicates - the FK is nullOnDelete, so deleting outright
would orphan drafts and scheduled posts.

* fix: refuse a reconnect that authorized a different identity

connectIdentity overwrote platform_user_id with whatever the provider
returned, so reconnecting a card while signed into another account
repointed the row - and every draft and scheduled post bound to it - at
a stranger. LinkedIn guarded this at the controller and Facebook via its
filtered page list; nothing covered X, TikTok, Threads, Discord,
Bluesky, Mastodon, Pinterest, Instagram or Telegram.

Enforce the identity match at the single choke point every connect flow
goes through. Every call site already maps NetworkAlreadyConnectedException
to network_taken, so the refusal surfaces without new plumbing.

Also restore the null-platform guard in the observer: occupiesNetwork
type-hints a non-nullable Platform, so a row without one died with a
TypeError instead of the database's NOT NULL error.

* fix: filter connectable identities on every picker step

YouTubeController::select re-fetched the channels and matched the posted
id straight off the raw list, unlike callback and selectChannel. With a
live youtube_oauth session it let a POST name any channel the Google
account owns and bind it to the reconnect target. It also read the
reconnect from the session while the connect below it read
youtube_oauth.reconnect_id, so the two could disagree - pass the
resolved account through instead.

filterConnectableIdentities also short-circuited in multi-account mode,
and the unique index is scoped to platform rather than network. That let
one Instagram account connect twice, once directly and once via
Facebook, publishing every Instagram post to it twice. The existing
except() already spans networkPlatformValues(), so dropping the
short-circuit closes it.

* refactor: type the connect cards and drop the dead accounts grid

The cards computed inferred account as a required ConnectedAccount and
then pushed undefined onto it (TS2345). CI only runs eslint so it stayed
green, but vue-tsc and editors flag it.

SocialAccountsGrid is referenced nowhere; its reconnect button was
updated in this branch without passing the card id, which would have
been a bug had anything rendered it.

* test: keep the suite on the cloud one-account-per-network default

CI runs the Cloud build, so the suite baseline should be the Cloud
default rather than the self-hosted one. Put phpunit.xml and .env.ci
back to false and make the eight tests that merely need two accounts of
one network as a fixture opt in for themselves.

This also un-deads the config()->set(true) calls the branch had already
added to AuthenticationTest, SyncAccountUsageTest, HasUsageTraitTest and
SocialAccountObserverTest, which the forced true had turned into no-ops.

* fix: connect standalone instagram instead of reopening the picker

The picker emits an already-resolved connect method, but this branch
rewired @select from openOAuthPopup to startConnect. startConnect sends
a bare 'instagram' straight back into its own picker branch, so choosing
"Instagram" closed the dialog and immediately reopened it - the OAuth
window never opened and the standalone flow was unreachable. Only the
via-Facebook button still worked.

Split the URL-opening tail out of startConnect and let the dialog call
that directly.

* fix: reject a telegram reconnect before burning the connect code

The nonce was consumed before connectIdentity ran, so posting /connect in
the wrong chat spent the one-off code and forced the user to generate a
new one. Check the identity first and report wrong_chat instead of
network_taken, which told them to disconnect an account when the real fix
was posting in the channel they were reconnecting.

* fix: leave one target per post when merging duplicate accounts

post_platforms has no unique on (post_id, social_account_id), so a post
holding a row per duplicate account ended up with two enabled rows aimed
at the surviving account and would publish to it twice. Keep one row per
post, preferring a published one so history survives.

* refactor: collapse the repeated connect-flow boilerplate

Four shapes were copy-pasted across the connect controllers:

- the session + permission guard opening 16 actions, now connectWorkspace()
  throwing a ConnectPopupException that renders the popup itself
- the reconnected/connected ternary in 13 places, now connectedCallback()
- the "nothing left to connect" branch in 4 places, now
  noConnectableIdentities()
- validatedReconnectId() re-querying what reconnectAccount() already does

Facebook, Instagram-via-Facebook and YouTube also re-queried the reconnect
account three or four times per callback; it is resolved once and passed
down. The three GET pickers skipped the manageAccounts check their POST
siblings had, and pick it up from the shared guard.

Drops the color key from connectableOptions and the matching frontend
field - nothing read it. Platform::color() stays; the disconnection
emails use it.

* fix: keep an expired connect popup out of the error log

ConnectPopupException escapes to the framework handler so it can render
itself, which also meant report() ran first: every session_expired and
workspace_not_found popup filed an ERROR and a Nightwatch issue for what
used to be a silent return. A stale popup is a normal outcome, so it now
implements ShouldntReport.

The Mastodon and Threads guards also cleared their provider session
after connectWorkspace(), so a workspace that vanished mid-flow left the
client secret and the OAuth state behind. Clear first, then resolve.
clearMastodonSession() no longer touches social_connect_workspace -
whatever closes the popup already does.

* fix: stop telling users to disconnect an account that is not the problem

Two flows reused popup_callback.network_taken - "This workspace already
has an account for this network. Disconnect it first." - for situations
where that is neither true nor actionable:

- reconnecting a card while signed into a different account on the
  provider, now wrong_account
- an empty picker in multi-account mode, where every page or channel on
  that login is simply already connected, now all_connected

NetworkAlreadyConnectedException carries the message key so the catch
sites stay one line. handleCallback() also drops its $platform argument;
it read $this->platform for the reconnect lookup and the identity filter
either way, so a caller passing a different platform would have scoped
the lookup to the wrong network.

* refactor: filter linkedin identities with the shared helper

The picker hand-rolled its own reconnect narrowing because the profile
and the pages arrive in two different shapes. Flatten them into one pool
of LinkedIn identities, run the shared filter, and split them again for
the view - the same path Facebook, YouTube and Instagram already take.

Side effect worth having: the picker previously only narrowed on a
reconnect, so it would offer an identity that is already connected and
only fail once the user picked it. It now hides taken identities up
front and says so when nothing is left.

* fix: keep the linkedin picker's own empty state

Routing the picker through the shared filter made every empty pool look
like "nothing left to take", including the pool LinkedIn never filled.
A self-hoster running pages-only who administers no page was told the
network was already connected, or that every account on the login was
taken - both false - and the picker's own "you are not an admin of any
LinkedIn page" state became unreachable.

Only treat it as taken when filtering is what emptied it. Splitting the
pool back also compared the person id loosely on one side and strictly
on the other; one predicate now drives both.

Threads had two forget() calls for a key the top of the action already
clears, and YouTube's picker resolved the reconnect account twice on the
failure path.

* fix: keep the enabled row when collapsing duplicate post targets

SyncPostPlatforms seeds a disabled post_platforms row for every account
in the workspace, so the usual duplicate is one row the user actually
checked next to one they never saw - both pending, both created in the
same second. Ordering only by published-then-newest made that a coin
flip, and PublishPost iterates enabled() only, so half the time a
scheduled post would silently stop reaching that account and take its
caption and per-platform meta with it. This runs once against production
data and the dropped row is gone, so enabled now beats disabled.

Also: the empty-pool exit from the LinkedIn picker was the only one
leaving linkedin_pending - and its tokens - in the session. The
rationale comments move to the docblocks they belong in, and usePage()
comes out of the cards computed.

* fix: stop the migration destroying publish history and automations

Two ways the one-shot merge lost data that cannot be rebuilt:

Surplus published post_platforms rows were deleted. Two duplicate
accounts really could each have published, and each row carries the
platform_post_id for a live post on the network - dropping one leaves
that post unmanageable and invisible to metrics. The docblock claimed
published beat everything; now the code does, and only unpublished
repeats collapse.

Automation nodes persist social_account_id inside a JSON column with no
foreign key, so deleting the loser left RunGenerateNode skipping that
target, or generating nothing at all when it was the node's only
account. The ids are rewritten - current and legacy shapes both - and
entries the merge just turned into duplicates are collapsed.

Ordering is now total (null created_at sorts oldest on every engine,
then id) so a rehearsal on a replica keeps the same rows as the real
run. The LinkedIn picker also passes onboardingProgress inline: it
clears linkedin_pending on the empty path, and a deferred reload would
re-GET the route and swap the empty state for a session-expired popup.

* fix: make the identity merge auditable and stop a second delivery

Self-hosted installs run this unattended and it cannot be undone, so
each collapsed group now logs the workspace, the identity, which row was
kept, which were dropped, and how many post_platforms and automations it
touched. down() says plainly that it drops the index only.

Two narrower fixes:

A post holding a published row plus an enabled unpublished row for the
same account kept both, and PostPlatform::scopeEnabled() filters on
`enabled` alone with no status check - so a republish would deliver the
same content to that identity twice. Once a published row exists, every
unpublished repeat goes.

The automation dedupe ran on every automation in the workspace, not just
the ones the merge rewrote. A node legitimately holding two entries for
one account under different content types would be collapsed to
whichever came first in the array. It now runs only where an id was
actually substituted.

* test: rehearse the identity merge against a messy database

Every test on this migration so far covered a case someone thought to
write, which is why three separate review rounds each found a defect the
earlier ones missed. This builds a deliberately messy database instead -
three workspaces, four networks, one to three copies of each identity,
posts mixing published, pending and failed rows across the duplicates
with enabled flags varying, and automations referencing them in both the
current and legacy JSON shapes - then runs the real migration and
asserts what must be true afterwards rather than what happens to a
particular fixture.

Invariants: no duplicate identity survives, no published row is ever
destroyed, no post ends up enabled twice against one account, nothing in
post_platforms or automations points at a deleted account, and the
newest row of each identity is the one kept.

The generator is seeded, so a failure reproduces, and it asserts its own
output is adversarial - roughly nine duplicate groups and fourteen
published rows - so it cannot quietly degrade into passing on an empty
problem. Verified by mutation: dropping the automation repoint, the
published guard, or the repeated-target collapse each fails exactly the
invariant that covers it.

* fix: stop the youtube picker refetching itself into a cleared session

HandleInertiaRequests defers onboardingProgress for anyone mid-onboarding
- exactly the people connecting their first accounts - so Inertia
re-GETs the picker route right after it mounts. For Facebook and
Instagram that re-entry is harmless and deliberately left deferred, but
YouTube calls the Google API again, and fetchChannels() turns any
failure into an empty list that clears the connect session and swaps the
mounted picker for an error the user cannot retry from. Same guard the
LinkedIn picker already got.

LinkedIn also answered a reconnect that authorized a different identity
with "Page not found", including in the person branch where no page is
involved. Every other platform says wrong_account, which this PR added.

* refactor: drop the unreachable youtube channel picker

Google's own delegation screen already lists every channel on the
account and makes the user pick one before it issues the token, so
channels?mine=true always answers with that single channel and
count($channels) === 1 always won. The picker behind it was never
reached - its Vue page was deleted back in 7c00c338 (January) and
nothing broke, which is the clearest evidence it was dead.

Removes selectChannel(), select(), both routes, the youtube_oauth
session payload and the tests that drove them. If Google ever does
return more than one, the callback connects the first and logs a warning
rather than routing to a screen that no longer exists.

* fix: serialize connects so two popups cannot seat one network twice

The observer's occupiesNetwork() is a check-then-insert with nothing
holding the gap, and the new unique index covers the identity, not the
network. Two tabs finishing OAuth at the same moment for *different*
identities on one network both passed the exists() check and both
inserted, leaving a Cloud workspace with the two accounts the rule
exists to prevent. The same-identity race was already safe - the unique
violation is caught and re-queried.

A database constraint cannot hold this: allow_multiple_social_accounts
is a runtime flag, so the rule is on for Cloud and off for self-hosted,
and an index cannot read config. Lock per workspace and network instead,
the way markAsDisconnected() and ConnectionVerifier already do.

This covers connectIdentity(), which every OAuth flow and the Telegram
action go through. A direct create() still answers to the observer
alone, and a self-hosted install running file cache across several nodes
locks per node.

* fix: handle a busy connect lock on the telegram path

Every other caller funnels LockTimeoutException into its generic
\Exception catch and closes the popup with error_connecting. Telegram
has no such catch, so the new lock could 500 the webhook - and because
the nonce is spent before connectIdentity runs, Telegram's retry of the
same update short-circuits on the consumed code and returns without
dispatching anything. The dialog would spin forever on a code that can
no longer be used.

Also restores coverage the picker removal dropped: the deleted select
tests were the only ones driving a multi-channel response, so nothing
exercised the reconnect narrowing to its own card, or multi-account mode
skipping an already-connected channel. Both are back against the
callback, and removing the narrowing in filterConnectableIdentities
fails them.

* fix: stop the instagram login seating an account already held via facebook

filterConnectableIdentities() drops every identity already connected on the
network, which is what keeps one Instagram account from being seated twice
under its two platforms. Every flow that persists an identity ran it except
the direct Instagram Login callback, so the guard only held in one direction:
InstagramFacebookController refused an account already connected as
`instagram`, but the reverse was allowed through.

With multiple accounts per network enabled the observer's network check is
bypassed and the unique index does not span platforms, so authorizing the
same account through the direct flow created a second row. Both then seed a
post_platform row and the post goes out twice to one account.

* fix: name the real reason when a linkedin profile reconnect switches member

Reconnecting a card narrows the authorized identities to that card's own, so
authorizing a different LinkedIn login empties the pool. selectIdentity()
reported that as "Page not found." for every card, including personal
profiles where no page was ever involved.

A profile reconnect has no page to be missing: an empty pool there can only
mean this login is a different member. Say so with the wrong_account wording
select() already uses for the same condition. Page reconnects keep
page_not_found, where the organization really can be absent from the login.

* fix: surface the busy telegram connect instead of a generic failure

The connect lock timing out dispatches its own 'busy' reason so the dialog
can tell the user to retry, but the dialog only mapped network_taken and
wrong_chat and fell back to error_generic for everything else. The reason
reached the browser and died there, leaving "Could not start the connection"
for a case that just needs another moment.

* test: cover reconnect on every flow that gained it

rememberConnectSession() gave Instagram, TikTok, Threads, Mastodon and
Bluesky a reconnect path they did not have before — TikTok had been actively
clearing social_reconnect_id on connect — and none of them had a test for it.
Facebook, LinkedIn, YouTube, X, Discord, Pinterest and Telegram already did.

Each now covers both halves: authorizing the same identity refreshes the
existing card and reports it as a reconnect, and authorizing a different one
is refused with wrong_account instead of quietly seating a stranger on the
card and every post scheduled against it.

* fix: repair what a reconnect leaves behind when it cannot proceed cleanly

Two things connectIdentity got wrong once the reconnect path existed.

A reconnect through the other variant of a network moves the card to the new
platform — same identity, different API flavor. Post targets carry their own
platform snapshot, and that snapshot picks the publisher, the queue and the
scopes checked before publishing. Left behind, it failed every pending post on
a permission the account no longer needs: an Instagram card moved to the
Facebook variant still demanded instagram_business_content_publish and stopped
with "Missing permissions". Pending targets now follow the card and reset a
content type the new platform cannot publish; published targets keep theirs,
since they record what really went out under a platform_post_id from that API.

The network lock timing out also arrived as a raw LockTimeoutException, which
every OAuth callback filed through its generic catch: an error log and "Error
connecting account" for the exact race the lock exists to absorb. It now
carries a busy messageKey through the branch each flow already handles, the
same way the Telegram path already reported it.

* refactor: resolve the linkedin reconnect card once per select

select() already looked the card up before deciding whether the chosen
identity matches it, then connectPerson() and connectOrganization() looked it
up again on their own — two identical queries per submit, and two places that
could disagree about what is being reconnected. The caller passes what it
already holds.

* test: render the grid's multi-account branch

phpunit.xml forces ALLOW_MULTIPLE_SOCIAL_ACCOUNTS false and no browser test
overrode it, so the card the flag exists to add never rendered anywhere. The
pair pins both sides: a taken network offers no second card when multiples are
off, and offers one when they are on.

* test: pin why the linkedin select guards exist

connectIdentity() already refuses a mismatched reconnect and answers with the
same wrong_account message, so every existing test passes with the two guards
in select() deleted — which is exactly how they would get deleted. What they
actually buy is skipping the avatar download that building the connect payload
runs first.

Both now assert the fetch never happens, so the guards fail loudly instead of
looking redundant.

* fix: carry retrying targets through a variant move, atomically

Two holes in the move added a commit ago.

It only carried pending targets, but a retrying one is not finished either —
the publish job reschedules itself and reads the snapshot fresh on the next
attempt, so leaving it behind meant it retried against the old variant until
it exhausted its budget on a permission the account no longer needs. Failed
and published targets stay put; a publishing one has a job mid-flight already
working from the snapshot it read.

The card and its targets also moved in three separate statements, so a crash
between them left exactly the split this was meant to close. They share a
transaction now.

* chore: drop the dusk selectors nothing reads

Laravel Dusk is not installed — no laravel/dusk requirement, no DuskTestCase,
no browse(). Browser tests run on pest-plugin-browser driving Playwright, and
its @selector resolves to data-testid. The 45 dusk attributes left across 18
components selected nothing.

CLAUDE.md was the reason they kept coming back: it told every agent to add
them. Its browser-testing section now describes the setup that exists —
data-testid targeting, the wait helper these tests need because assertions do
not auto-wait on SPA paint, and why BrowserTestCase keeps Vite real.

Verified before removing: every @selector used in tests/Browser resolves to a
data-testid, seven of them through bound :data-testid, so none depended on a
dusk attribute.

* chore: drop the last one-account-per-network helper

hasConnectedPlatform() has no callers left anywhere — app, tests, views or
routes. It sat directly above getSocialAccount(), which this branch already
removed, and is the same leftover from when a workspace could hold one account
per platform.

---------

Co-authored-by: Paulo Castellano <paulo@castellanos.llc>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 07:28:14 -03:00
Paulo Castellano
0eff22dc0d
Remove the post-templates feature (#296)
* Remove the post-templates feature

Removes the browsable post-templates catalog end to end: routes
(app.post-templates.index/apply), controller, form requests, resource,
Registry/PostTemplateData/TemplateNotFoundException services, the
templates:report console command, the templates/ catalog (36 files
across en/es/pt-BR), the templates Index.vue page, the template card
on the post Create.vue choice screen, and its i18n keys across all 16
locales.

Also removes TemplateContextResolver, which fed catalog examples into
PostContentGenerator's AI prompt. The "examples" block (with its
heading) is removed from generator.blade.php rather than left empty;
AI generation no longer references the templates catalog.

The AI content-template system under app/Ai/Templates (image/tweet
card templates for the AI post wizard) and TemplateImageGenerator are
unrelated and untouched.

* Update FormRequest naming examples after the post-templates removal

CLAUDE.md and the Cursor rules cited ApplyPostTemplateRequest and
IndexPostTemplateRequest as naming examples. Both classes were deleted
with the feature, so the guidance pointed at files that no longer exist.

* Share the AiTemplate type between the create screen and the AI wizard

Create.vue and AiPostWizard.vue each declared their own AiTemplate
interface, and they had drifted: the wizard's carried
applies_brand_visuals, the create screen's did not. TypeScript treated
them as unrelated types with the same name, which surfaced as a TS2719
error where the templates prop is passed between them.

The backend sends seven fields (PostController::create), so the shared
declaration follows the payload rather than the union of the two copies.
2026-08-19 09:34:26 -03:00
Paulo Castellano
15f87aebe4
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout

Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Nest welcome connect copy under a connect array.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Require a connected social account before welcome checkout.

Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden the welcome connect step after review.

Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refactor social account status handling across components

Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest

Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.

* Inline welcome connect PostHog platforms from the current workspace.

Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Inline Stripe checkout into the welcome connect store.

startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move welcome connect validation into the controller.

The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Show welcome toasts and cover remaining connect cases.

Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Rename WelcomeEvent::dashboardFunnel() to funnel().

Co-authored-by: Cursor <cursoragent@cursor.com>

* Identify connected platforms from the social account observer.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Queue connected-platform identify on the posthog queue.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Identify connected platforms on workspace and account groups, and keep the account union on the owner.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Skip welcome connect validation when the controller would redirect the user away.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move current-goal membership onto the Goal enum.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 19:37:43 -03:00
Paulo Castellano
de54ea24f9
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend

These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:

- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
  dispatched, gated on !is_invite. auth_provider derived from
  google_id/github_id presence, same values the frontend session-based
  flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
  existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
  StripeEventListener::handleSubscriptionCreated (webhook-driven — more
  reliable than the old frontend flow, which depended on the user staying
  on billing/Processing.vue). Conversion value/currency/transaction_id
  read from the subscription webhook payload; transaction_id is the
  Stripe subscription id rather than the old Checkout Session id.

Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).

useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.

* chore: remove now-dead GTM dataLayer pushes from useTracking.ts

All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.

Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().

datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.

* feat: split checkout.completed into trial.started / checkout.completed / trial.converted

checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:

- trial.started: subscription created with status trialing. No
  conversion_value (nothing has been charged) — carries trial_ends_at
  instead.
- checkout.completed: subscription created with status active (coupon or
  immediate full-price checkout) — unchanged behavior, still carries
  conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
  customer.subscription.updated via Stripe's own previous_attributes.status
  transitioning from trialing to active. This is the Stripe-recommended way
  to detect what changed in an .updated webhook, and doesn't depend on our
  own DB write ordering — Cashier's WebhookController dispatches
  WebhookReceived before it syncs the local subscription row, so trusting
  our own stripe_status here would be fragile.

TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.

Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).

* refactor: derive auth_provider from the created User model, not the input array

$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.

* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate

Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:

1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
   routes with no query params at all — invite, redirect and email were
   silently dropped the moment someone clicked "Sign up with Google"
   instead of using the email form. The person got a brand-new
   independent account + workspace instead of joining the inviter's
   account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
   the `registration.enabled` middleware that gates /register in
   self-hosted mode — so self-hosted installs could be signed up into via
   OAuth with no invite at all, bypassing the intended lock.

Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
  OAuth round-trip via session (PreservesAttributionParameters' pattern,
  but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
  onto the Google/GitHub links; Register.vue and Login.vue pass their
  props through.
- registerNewUser() now passes the same `is_invite` semantics
  RegisterRequest already uses for the email flow, and both
  registerNewUser()/loginExistingUser() honor the pending redirect (same
  target AcceptInvite.vue already sends the email flow to), so accepting
  via OAuth now lands back on the invite page authenticated, exactly like
  email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
  the callback resolves an identity) since /redirect is shared with
  login and can't tell new vs. returning users apart beforehand.

New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.

* refactor: replace client-supplied redirect param with server-resolved invite redirect

Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.

* refactor: use Request::string() for invite id, trim comments

Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.

* refactor: tighten Invite::fromId, drop redundant is_string check

* test: cover GitHub invite acceptance and self-hosted gate scenarios

Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.

* refactor: fold null-account check into owner_id guard via nullsafe operator

* refactor: dedupe Stripe conversion tracking jobs and properties

TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.

* refactor: extract named status helpers in StripeEventListener

currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().

* refactor: drop redundant persona from Stripe PostHog event properties

Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.

* refactor: drop redundant plan property in TrackBilling

PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.

* feat: log PostHog payloads to laravel.log in local environment

Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.

* fix: cold-review pass — dead code, ordering bug, missing test coverage

- Fire checkout.started only after the price-ID guard, not before it, so a
  misconfigured plan can't record a phantom checkout.started for a checkout
  that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
  attribution parameters happens after the self-hosted invite gate, not
  before — a rejected attempt no longer discards UTM/click-id attribution
  (GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
  displayed a 5s cosmetic transition before redirecting home, its tracking
  call was already removed, and app.calendar's own middleware handles
  onboarding redirects regardless of entry point. The 3 post-registration
  redirects now go straight to app.welcome (was silently dropped to
  app.home in an earlier pass of this cleanup — welcome is correct, that
  was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
  persona/conversion props (and the Stripe API call in BillingController
  that only existed to populate them), unused auth_provider session flash
  across 3 controllers, unused captureEvent() export in posthog.ts, and
  unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
  (AuthenticatedSessionController's invite-redirect branch had zero
  coverage), and a regression test locking in the checkout.started
  ordering fix.

* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug

- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
  match the authenticated provider account's email, mirroring the check
  RegisterRequest already enforces for the web form. Previously an invite
  for one email could be completed by signing in with a different Google/
  GitHub account, leaving a permanently workspace-less orphaned account
  (AcceptInvite's WrongEmail path never runs the shell-account cleanup,
  since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
  (matching PreservesAttributionParameters, which it claimed to mirror but
  didn't). It previously only wrote when the invite param was present,
  so a stale invite id from an aborted OAuth attempt could leak into a
  later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
  conversion as 'yearly' when both the webhook price id and the plan's
  stripe_yearly_price_id are null (null === null) — now requires the plan
  price id to be non-null before comparing, matching the equivalent guard
  in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
  BillingController::processing() — its only consumer (the frontend
  trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
  and TrackBilling — neither reads $account->owner, only owner_id.

* fix: normalize invite email casing at creation; resolve PostHogService via container

- CreateInvite::execute() now lowercases the invite email before storing it.
  Invite acceptance/decline/registration all compare it verbatim against
  User.email (itself always lowercase), so a mismatched-case invite created
  before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
  of `new PostHogService`, matching the DI pattern used by every other
  PostHog call site added in this PR.

* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion

- EnsureRegistrationEnabled, GoogleController, and GitHubController now
  require the invite param to resolve to a real Invite (Invite::fromId())
  instead of just checking presence. Previously any random string/UUID
  satisfied the self-hosted "invite required" gate and produced a fully
  functional account with its own workspace, defeating the restriction
  entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
  frontend to show/hide the login button — the actual OAuth routes
  (GoogleController/GitHubController::redirect(), and the settings
  connect-provider endpoint) had no backend check, so a disabled provider
  could still be used end-to-end by hitting the URL directly. Both are now
  gated with abort_unless(..., 404). The settings Authentication page also
  stops rendering a "Connect" button for a disabled, not-yet-connected
  provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
  on a past_due -> active recovery (a trial's first charge attempt failing
  and then succeeding on retry), not just the immediate trialing -> active
  transition. Guarded by trial_end being set so a long-time paying
  customer's unrelated payment-method recovery is never miscounted as a
  trial conversion.

* refactor: merge the two connectProvider abort_unless checks into one

* refactor: centralize social auth providers in a SocialAuthProvider enum

google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.

App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().

* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()

The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").

* refactor: remove the fixed 5s post-checkout redirect delay

REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.

* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union

* fix: Login.vue never displayed session-flashed email errors

GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.

* test: add a browser test for the Login.vue flashed-error display fix

Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.

* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks

signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.

* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry

convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.

Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.

Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.

* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging

WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.

Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.

* refactor: centralize OAuth invite-registration validation in PreservesInvite

GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 11:47:47 -03:00
Paulo Castellano
a1a9172448
fix: subscribe to AI generation channel before dispatching the job (#269)
* fix: subscribe to AI generation channel before dispatching the job

AiGenerateDialog posted the generate request and only subscribed to the
broadcast channel once the response came back. Reverb's plain Channel
(vendor/laravel/reverb/.../Channels/Channel.php) delivers broadcasts by
iterating the in-memory connection list at send time only — no history,
no replay. If the queued job started streaming text_delta/stream_end
events before the private-channel subscribe handshake finished, those
events were gone for good and the dialog hung on 'streaming' forever.

Generate the generation_id client-side, await channel subscription
confirmation (Echo's channel.subscribed(), backed by
pusher:subscription_succeeded) before sending the generate request, and
have the backend use the client-supplied id instead of minting its own.

Related to #218.

* fix: handle subscribe failure, dialog-close race, and i18n hardcoded strings

Code review on the previous commit surfaced real gaps:

- useAiStream only handled the subscribe-success path (.subscribed()).
  A definitive pusher:subscription_error (expired session, CSRF
  mismatch) fell through to the 5s timeout and was treated as success,
  reproducing the exact #218 hang via a different trigger. subscribe()
  now returns a boolean: true on confirm-or-ambiguous-timeout (proceed
  optimistically), false only on an explicit error (don't dispatch work
  nothing will ever hear).
- AiGenerateDialog now bails without dispatching if the dialog is
  closed while awaiting subscription confirmation (up to 5s), and
  unsubscribes on a post-subscribe dispatch failure so stale listeners
  can't flip status to 'completed' after an error was already shown.
- Extracted aiGenerationChannel() so the frontend has one place to
  update if the channel format changes, and cross-referenced the two
  remaining backend copies (PostAiGenerateController, StreamPostContent).
- Replaced the two hardcoded English fallback error strings with i18n
  keys (posts.ai.generate.errors.*) across all 16 locales — this app
  only ships translated copy.
- Simplified subscribe(): dropped a redundant "already settled" guard
  and the clearTimeout bookkeeping — Promise.resolve() already no-ops
  after the first call, so there was nothing to guard.

* fix: subscribe before dispatch in AI post creation and image regeneration flows

Extracts subscribePrivateChannel as a shared helper and applies the same
subscribe-before-dispatch fix from the post edit flow (issue #218) to the
other two flows that stream over private channels.

Post creation wizard moves the StreamPostCreation dispatch out of
AiPostWizard.vue and into Loading.vue, so the channel is subscribed before
the job that broadcasts on it is dispatched — previously a full page
navigation happened between dispatch and subscribe with no timeout
fallback, so a lost event hung the page forever.

* refactor: trim explanatory comments added in the subscribe-before-dispatch fix

Rationale lives in the commit history, not scattered inline comments.

* refactor: trim remaining explanatory comments from the subscribe-before-dispatch fix

Same cleanup as the previous commit, applied to the files from the
original post-edit-flow fix.

* fix: dedup post-creation dispatch, surface field-level AI errors, harden edge cases

Uses ShouldBeUnique on StreamPostCreation (scoped per-user) instead of an
ad-hoc cache guard, matching the pattern already used by
PublishToSocialPlatform and VerifyUpcomingPostConnections.

Field-level validation errors (prompt/instruction) now render inline via
InputError, matching how every other form in the app surfaces them, instead
of a generic status banner. Also fixes a 422 response missing the `errors`
key that Inertia's client silently swallows, adds error handling around the
wizard's navigation to the loading page, and extracts the duplicated
error-message parsing into a shared helper.
2026-08-10 16:06:37 -03:00
Paulo Castellano
676afb15ba
fix: chunked upload session collision + workspace name i18n (#263)
* fix: give each chunked upload attempt a unique server-side identifier

The upload session identifier was derived only from user+filename+size
(ChunkedAssetReceiver::receive), with no per-attempt nonce. Two genuinely
concurrent attempts of the same file (e.g. closing and reopening the media
picker mid-upload, then re-uploading the same file) collided on the same
Redis cache key / temp file, producing RuntimeException("Chunked cloud
upload session expired or missing.") on the multipart/cloud path and
silent byte corruption on the local-assemble path.

The frontend now mints a UUID per upload attempt (X-Upload-Id header) that
gets folded into the identifier. Falls back to the old formula when the
header is absent, so any already-loaded frontend bundle keeps working.

Also guards the media picker's dropzone against re-triggering an upload
while one is in flight, and aborts the in-flight fetch when the dialog
unmounts mid-upload.

Fixes Nightwatch issue #23.

* fix: explicitly type upload_id when passing to receive()

Matches the existing explicit (int) casts on the sibling validated()
calls in the same method — validated() returns mixed, so this keeps
the nullable-string contract explicit instead of relying on an
implicit runtime type.

* style: inline the upload_id null-safe cast

Drop the intermediate variable so all receive() arguments read as a
single expression each, matching the sibling validated() casts.

* fix: require X-Upload-Id instead of falling back to the legacy identifier

Nullable upload_id only preserved the old (collision-prone) formula for
clients that omit the header — it didn't actually protect them. Making it
required closes that gap outright: a request without the header now fails
loud (422) instead of silently falling back to the vulnerable identifier.

ChunkedAssetReceiver::receive() now takes a required $attemptId. Updated
every existing test hitting app.assets.store-chunked (ChunkedCloudUploadTest,
ChunkedAssetReceiverTest, ChunkedUploadFilenameEncodingTest, AssetControllerTest)
to send a real upload id, and added a regression test asserting the endpoint
rejects a request with no X-Upload-Id header.

* fix: localize hardcoded workspace name validation messages

StoreWorkspaceRequest had its custom messages() hardcoded in pt-BR
regardless of the user's locale; UpdateWorkspaceRequest had the same
bug hardcoded in English. Both now go through __('validation.required'
/ 'validation.max.string') with the already-localized
workspaces.create.name attribute label (present in all 16 lang/
directories), matching the pattern already used by
StoreWorkspaceInviteRequest.

Unrelated to the chunked upload fix, but caught while reviewing this
file's messages() convention.

* simplify: drop messages() override on workspace name validation

Laravel already localizes the generic required/max messages from
lang/{locale}/validation.php automatically — no need to hand-roll
messages() for standard rules with no custom copy.

* fix: localize StoreChunkedAssetRequest validation messages

Drop the hardcoded English messages for required/ends_with rules —
Laravel's own localized validation.php messages already cover them
adequately (ends_with's generic message is actually more useful, since
it lists the accepted extensions). total_size.max still needs a custom
message (the rule is in raw bytes, unreadable without MB conversion),
so it now goes through __('assets.upload.file_too_large') with the key
added to all 16 lang/ locales.

Also fixed test flakiness discovered while touching this file:
ChunkedCloudUploadTest used random_bytes() for the first mp4 chunk,
which occasionally collides with an unrelated magic number (MZ/PE,
SIMH tape, ...) and makes finfo misdetect the mime type. Replaced with
real mp4 header bytes padded with nulls, so detection is deterministic.

* fix: address final code review findings

- ChunkedAssetReceiver: use double-quoted interpolation instead of
  concatenation for the identifier hash, per project convention.
- AssetControllerTest: two chunked-upload rejection tests didn't send
  X-Upload-Id, so their 422 assertions could pass for the wrong reason
  (upload_id.required) instead of the field they claim to cover. Added
  the header and asserted the specific validation error field.
- GalleryBrowser: centralize the upload-in-progress guard as a single
  check at the top of uploadFiles() instead of three separate checks
  at each entry point (click/select/drop) — matches the single-source-
  of-truth pattern already used in PhotoUpload.vue.
- GalleryBrowser: show a toast when an in-flight upload is aborted
  (dialog closed mid-upload) instead of silently discarding it with no
  feedback. New assets.upload.cancelled key added to all 16 lang/
  locales.
2026-08-09 14:06:47 -03:00
Paulo Castellano
a147c7414b
feat: proactive connection check for at-risk posts + SocialAccount name centralization (#256)
* chore: gitignore .superpowers/ scratch workspace

Holds per-plan subagent-driven-development artifacts (ledger, briefs,
review packages) — scratch state, not part of the shipped codebase.

* feat: add connection_warning_sent_at to post_platforms

* feat: add PostAtRisk notification type and translations

* fix: add user_id to NotificationPreferenceFactory definition for ->create() support

* feat: add PostAtRisk mailable and email template

* feat: add VerifyUpcomingPostConnections job

* fix: guard VerifyUpcomingPostConnections against transient errors and cross-workspace leaks

- Add a generic \Exception catch around ConnectionVerifier::verify() so a
  transient error (e.g. ConnectionException) on one account can't abort
  processing of every other at-risk account in the workspace run.
- Eager-load socialAccount.workspace so markAsTokenExpired's observer chain
  never lazy-loads it — this only ever manifested once 2+ distinct accounts
  were hydrated in a single run (Eloquent only sets preventsLazyLoading on
  batch hydration of >1 row), which is exactly the multi-account scenario
  this job exists to handle.
- Add covering tests: enabled=false posts are excluded, one workspace's
  at-risk posts never leak into another workspace's notification, and an
  unexpected exception on one account doesn't stop the rest of the run.

* feat: add social:check-upcoming-connections command and schedule it

* fix: add composite index for the 15-minute upcoming-post connection query

post_platforms(status, connection_warning_sent_at) supports the filter both
VerifyUpcomingPostConnections and social:check-upcoming-connections run every
15 minutes; without it, every run does a full table scan that only grows as
posts accumulate.

* fix: localize the PostAtRisk email's per-account line and label times as UTC

The postsLabel line was the only hardcoded-English content in an otherwise
fully-translated email, and it showed scheduled_at times with no timezone
indicator even though the app stores everything in UTC. Add
mail.post_at_risk.posts_label (pluralized, one entry per locale, mirroring
each locale's existing post_at_risk.subject plural-boundary syntax) and use
trans_choice() to build the line, with a literal " UTC" suffix left
untranslated in every locale like a unit abbreviation.

Also document why content() reassigns the public $atRiskGroups property
instead of using a local variable (Mailable::buildViewData() overwrites
with() data with same-named public properties).

* fix: time-box the warning dedup and guard against orphaned/ownerless rows

- Re-arm connection_warning_sent_at after a day instead of permanently
  suppressing it, so a post rescheduled back into the risk window after a
  stale warning is re-evaluated instead of silently skipped forever.
- Exclude post_platforms with a null social_account_id from the at-risk
  query. With tries=1, dereferencing a null socialAccount relation would
  abort the whole workspace run, including already-detected broken accounts.
- Resolve and check the workspace owner before stamping
  connection_warning_sent_at, so an ownerless workspace's posts are left
  un-warned (available to be picked up once it gets an owner) instead of
  being marked "warned" with no notification ever sent.

Applied the same dedup time-boxing and null-account guard to the
social:check-upcoming-connections dispatch query for consistency.

* fix: PostAtRisk email is always English — drop the locale translation layer

config('app.locale')/App::setLocale() is only ever set by the SetLocale
web middleware, which reads a cookie off the incoming HTTP request. Every
Mailable in this branch is built inside a queued job (SendNotification),
which runs outside the HTTP request lifecycle entirely — no middleware,
no cookie, nothing sets the locale there. So content() always resolved
'app.locale' to the static APP_LOCALE default ('en') regardless of the
recipient's actual preference: the 16-locale mail.post_at_risk.* keys
were dead weight from the start, matching an existing (pre-existing,
out of scope here) gap in the sibling WorkspaceConnectionsDisconnected/
AccountDisconnected mailables.

Replaces the trans_choice()/__() calls with plain English strings built
directly in PostAtRisk, and removes the now-unused mail.post_at_risk.*
block from all 16 locale files. Also strengthens the mailable test to
assert the full "N post(s) scheduled: ... UTC" string, not just a
fragment of it.

* refactor: consolidate the two post_platforms migrations from this branch into one

connection_warning_sent_at and its supporting index were added in two
separate migrations (the column in the original task, the index during
final review). Both are still unmerged/unshipped on this branch, so
folding the index into the same migration that adds the column is safe
and keeps the schema change to post_platforms as one unit instead of two.

Verified with a full rollback + re-migrate cycle that the consolidated
up()/down() is self-consistent.

* refactor: add PostPlatform::scopeEnabled(), replace ->where('enabled', true) everywhere

The raw where('enabled', true) clause was duplicated across 17 call sites
in 12 files (13 including the 2 this branch added), all expressing the
same rule PublishPost enforces at publish time: only enabled platforms
are eligible. Added a scopeEnabled() to PostPlatform and swapped every
query-builder call site to ->enabled().

Three call sites are intentionally left untouched: they filter an
already-loaded relation Collection (->postPlatforms->where(...), no
parens), which is Collection::where(), not a query scope — a query scope
can't apply to an in-memory collection.

No inverse (enabled = false) query pattern exists anywhere in the
codebase — 'enabled' => false only ever appears as a write when a post
is disabled/synced, never as a read filter — so no scopeDisabled() was
added; nothing would call it.

* test: cover re-armed post_platform where the account was reconnected

The re-arm dedup fix (connection_warning_sent_at older than a day is
treated as null) only had coverage for "still broken, warns again" and
"too recent, stays skipped". Missing: the row gets re-evaluated (verify()
is called, not skipped) but comes back healthy because the user
reconnected in the meantime — nothing should change (no new warning, no
notification, marker stays at its old value).

* fix: dispatch-level uniqueness, index the enabled filter, close markAsTokenExpired race

From a deep review pass on the whole branch:

- VerifyUpcomingPostConnections now implements ShouldBeUnique (keyed on
  workspaceId, 300s window). withoutOverlapping() on the schedule only
  serializes the fast-dispatching command; a queue backlog could still let
  two jobs for the same workspace run concurrently, both mailing the owner
  for the same at-risk posts.
- The composite index now covers enabled too (status, enabled,
  connection_warning_sent_at) — every query that uses it filters on all
  three, so the index previously required a heap fetch per row just to
  check enabled.
- markAsTokenExpired() silently no-ops if it loses the account's status
  lock to a concurrent process (a publish attempt, the daily check). The
  job used to push the account into the at-risk notification regardless
  of whether the update actually landed. It now re-checks the account's
  status after the call and only warns if the transition is confirmed —
  a lost race just defers the account to the next run instead of sending
  a misleading "reconnect" email for an account whose status didn't change.

Also includes an unrelated stray Pint fix (inline \Throwable -> imported)
in SendNotification.php that had been sitting uncommitted.

* refactor: centralize account handle/display name, expose to frontend, close review findings

Adds SocialAccount::handle()/accountDisplayName() plus appended
display_label/handle_label JSON fields, replacing duplicated
username/display_name fallback logic scattered across platform
previews, NetworkConnectGrid, PreviewTab, Calendar, and the post
editor pages.

Also closes the remaining findings from the final review on this
branch: escapes the workspace name in PostAtRisk's intro (and drops
the now-unnecessary raw-HTML rendering), fixes the tautological
"dispatches once per workspace" test, adds plural/subject test
coverage for PostAtRisk, raises VerifyUpcomingPostConnections'
uniqueFor to cover the full schedule cadence, and updates a stale
docblock.

* test: cover draft-post exclusion, account status after PlatformUnavailableException

Adds the two coverage gaps left open by the last review: a post still
in Draft status inside the 1-hour window must not trigger a check or
warning, and a PlatformUnavailableException must leave the account
status untouched. Also drops the dedicated PostAtRisk XSS test — the
intro is now plain Blade-escaped text, so the coverage is redundant
with the framework's own escaping.

* fix: close final review findings — i18n notification, empty-string fallback, missed refactor sites

- Localize the in-app "post at risk" notification title in all 16
  locales via trans_choice (the email stays English, unchanged)
- Use ?: instead of ?? in handle()/accountDisplayName()/handleLabel()
  so an empty-string username/display_name still falls back, matching
  the old Vue || behavior
- Migrate the 3 frontend sites the earlier sweep missed (Index.vue,
  SocialAccountsGrid.vue, ScheduleTab.vue) to display_label/handle_label
- Fix avatar-initial fallback in the platform preview components to use
  display_label instead of raw display_name
- Correct handle_label's TS type to string | null across 10 files to
  match the accessor's actual return type
- Add test coverage for the command-level "already warned" dedup path
  and the in-app Notification row created alongside PostAtRisk's email

* fix: notification storm, duplicate-email race, and queue payload bloat in upcoming-post checks

Three correctness issues found by review, fixed after discussion:

- An already-broken account could get a fresh PostAtRisk email every
  15 minutes for as long as it stayed broken, if new posts kept
  entering the 1-hour risk window. Gated with a per-account 60-minute
  renotify cooldown.
- Two concurrent jobs (RefreshExpiringTokens and this one) could each
  discover the same dead token and send their own email for it
  (AccountDisconnected + PostAtRisk) within the same tick. Gated with
  a 5-minute grace period, applied only when another process already
  transitioned the account before we got to it — not when we're the
  one making the transition.
- PostAtRisk carried full SocialAccount/PostPlatform/Post model
  graphs on the queue payload, since SerializesModels can't reduce
  models nested inside a plain array/Collection to lightweight
  identifiers. It now carries only post_platform IDs and rehydrates
  at send time, with envelope()/content() sharing one memoized query
  so their counts can't disagree.

Also replaces the account-health cache with a persisted
SocialAccount.last_verified_at column, and narrows the actual
platform API calls to only fire once a post's nearest scheduled_at
is within 30 minutes — enough lead time to reconnect, without
spending API budget checking a full hour out.

* fix: replace dead unsubscribe link with notification preferences, finish display_label sweep

The shared mail footer's unsubscribe link was permanently dead code
(unsubscribe_url was never passed by any Mailable). Replaced it with
a fixed "Manage notifications" link to the real settings page,
via route('app.notifications.preferences').

Also closes out the remaining sites still computing the
username/display_name fallback locally instead of reading the
backend-computed display_label: 8 more Vue components (platform
previews, per-platform post-editor settings, the AI post wizard, the
automation Generate node config, and the analytics account selector)
plus two PHP call sites (PostPlatform::getDisplayNameAttribute(),
already fixed on main before this branch, and the template image
generator's rendered footer text).

* fix: only show "Manage notifications" on preference-driven emails

The link doesn't make sense on transactional emails that always send
regardless of notification preferences (password reset, email
verification) or that go to recipients who may not even have an
account yet (workspace invite) — and the settings page it points to
requires login, which is actively broken for the first two.

Split the shared footer into two Maizzle components: footer.html
(plain) for the 3 transactional templates, footer-authenticated.html
(adds the link) for the 6 that go through SendNotification and
respect the recipient's notification preferences.

* fix: lock PostAtRisk's subject to the dispatch-time count, expose handle_label from analytics

PostAtRisk's subject/previewText were recomputed from a fresh DB
query at send time, while the in-app notification's title (built in
VerifyUpcomingPostConnections::notifyOwner()) used the count observed
at dispatch time. If a post_platform row disappeared in between, the
two could disagree. The count is now passed into the mailable
explicitly and reused for both — the body's account/post details
still rehydrate fresh from the DB, preserving the anti-staleness fix
from earlier in this branch.

Also adds handle_label to AnalyticsController's account payload,
matching every other endpoint that serializes a SocialAccount.

* fix: don't abort the whole workspace run if an account is deleted mid-verify

An exception thrown inside a catch block isn't routed to a sibling
catch, so $account->refresh() throwing ModelNotFoundException (the
user disconnected/deleted the account in the brief window between
this job loading it and handling the TokenExpiredException) escaped
handle() entirely. With tries = 1, that killed the run for every
other account in the same workspace, not just the deleted one.

Also fixes an inconsistent placeholder in PlatformPreview.vue
(handle_label: null instead of '', matching display_label).

* fix: guard against deleted accounts, guarantee a non-empty account name

Closes the last 4 findings from the sixth review round:
- VerifyUpcomingPostConnections now skips a group whose account
  resolved to null (deleted between the main query and its eager-loaded
  relation), instead of an unguarded property access aborting the
  whole workspace's run
- the same job's nested exception handler now covers any \Exception
  from markAsTokenExpired() (lock/DB failures), not just
  ModelNotFoundException
- PostAtRisk drops a rehydrated group whose account no longer exists
  instead of crashing the render (verified: fails without the fix,
  passes with it)
- AnalyticsController's handle_label field is now actually consumed by
  AnalyticsAccountSelector.vue instead of being unused payload

Also closes a real gap: every connector requests enough OAuth scope to
populate at least one of username/display_name (confirmed for TikTok,
whose account.py comment implied otherwise but whose connect() scopes
always include user.info.profile), so accountDisplayName()/handle()/
displayLabel/handleLabel now return a guaranteed non-empty string
(falling back to the platform label only as a last resort) instead of
being nullable. This removes the now-pointless @if guards around
accountDisplayName() in the account-disconnected and post-at-risk
email templates, and lets ~30 frontend files drop the `| null` from
display_label/handle_label and the ?? undefined fallbacks that only
existed to satisfy that type.

* fix: drop the now-pointless ?? '' fallback on display_label in TemplateImageGenerator

display_label is a guaranteed non-empty string (see 950558b4).

* fix: correct social_account's TS type to nullable in Index.vue and Calendar.vue

Both declared social_account as required while their own templates
used optional chaining (pp.social_account?.display_label) — the type
was lying. social_account_id is nullable and the account can be
deleted (FK is nullOnDelete), so the field genuinely can be null.

Swept every other social_account/socialAccount field in resources/js
for the same mismatch; all others already declared it correctly.

* Centralize avatar-initial extraction via getInitials()

Replace hand-rolled .charAt(0)/.charAt(0).toUpperCase() avatar-initial
logic across social account previews, the accounts grid, the analytics
account selector, and the mention picker with the existing
useInitials() composable already used by Avatar.vue.

* Drop pointless display_label fallbacks now that it's always populated

display_label is guaranteed non-empty (falls back to the platform
label server-side), so || 'Channel' / || 'TryPost' / ?? platform were
unreachable.

* Fix cold-review findings: dead handle_label guard, slug leak, wrong post count

- AnalyticsAccountSelector: the "@handle" line's guard/value must read the
  raw username (nullable — Facebook Pages and Telegram channels legitimately
  have none), not handle_label, which always resolves to something and made
  the guard permanently true. Drop the now-orphaned handle_label field from
  the analytics payload/type since nothing else in analytics used it.
- PlatformPreview: the no-account-selected fallback now uses
  getPlatformLabel() instead of the raw platform slug, matching the
  backend's own last-resort label fallback.
- VerifyUpcomingPostConnections: count distinct posts (post_id), not
  post_platform rows, so one post spanning multiple broken accounts doesn't
  inflate the at-risk count in the email subject and notification title.

* Fix cold-review round 2: silent Telegram/Discord false negative, flaky email ordering, dead display_name

- VerifyUpcomingPostConnections: ConnectionVerifier::verify() reports a
  dead Telegram/Discord connection by returning false rather than
  throwing. The job discarded that return value, so a bot removed from
  a channel/guild was stamped last_verified_at and silently trusted
  healthy for the next 40 minutes — no warning, post just fails at
  publish time. Route a false return through the same
  TokenExpiredException handling used by every other platform.
- PostAtRisk: atRiskGroups() had no ORDER BY, so the per-account
  "N posts scheduled: H:i, H:i UTC" line rendered in arbitrary
  (physical row) order. Sort by scheduled_at before formatting.
- Drop the orphaned display_name field from the analytics payload/type
  (superseded by display_label; nothing in resources/js/components/
  analytics or pages/analytics read it).

* Add social icons and copyright to email footers

Icons match the trypost-site footer (outline @tabler/icons style,
converted to PNG since email clients — notably Outlook desktop — don't
render inline SVG). Reordered footer content: tagline, manage-notifications
link, icons as the closing element, copyright line last.

* Standardize connection-verify error classification across all 13 platforms

Every platform now follows one contract: verify() returns true on a
healthy connection, throws TokenExpiredException only on a confirmed
dead connection, and PlatformUnavailableException on anything else
(rate limit, 5xx, unrecognized). Previously most platforms silently
returned false on anything but a 401, so callers (all of which only
react via try/catch) could never distinguish "definitely dead" from
"transient" — and Telegram/Discord never threw at all.

Each platform's "is this confirmed dead" check now lives next to its
existing publish-time error classifier (App\Exceptions\Social\*PublishException)
instead of being re-typed inline in ConnectionVerifier, closing real,
already-drifted gaps between the two paths:

- TikTok and Mastodon both had a bare "status === 401/403" check shared
  between publish and verify, but TikTok's scope_not_authorized and
  Mastodon's write-scope 403 use the same status for a non-fatal scope
  gap, not a dead token — verify's lower-privilege endpoint keeps its
  own stricter check on top instead.
- Telegram/Discord authenticate with one bot token shared across every
  connected account; a 401 means that shared token is misconfigured
  (an operator problem), never that one specific account is broken —
  excluded from both platforms' confirmed-dead checks accordingly.
- Facebook/InstagramFacebook/Mastodon/Telegram/Discord have no
  per-account refresh flow at all, so a confirmed rejection now skips
  the pointless refresh-and-retry (Platform::hasTokenRefreshFlow()).

Also fixes two bugs found while hardening VerifyUpcomingPostConnections:
a post hard-deleted mid-run could crash the whole job for every other
account in the batch (now filtered per group), and two overlapping runs
of the same job could send duplicate PostAtRisk warnings (now a
conditional claim on connection_warning_sent_at).

* Skip paused accounts in upcoming-post connection checks, close claim race

A paused (is_active=false) social account already fails at publish time
before any platform API call, so it shouldn't trigger a proactive
connection check or "reconnect" warning. Guard added at dispatch time
(CheckUpcomingPostConnections) and re-checked fresh mid-run inside
VerifyUpcomingPostConnections's per-account loop, since the job can take
real wall-clock time working through a workspace and an account can be
paused or deleted after the query-time guard already ran.

Also wraps the connection_warning_sent_at claim in a SELECT ... FOR UPDATE
transaction (ordered by id, 3 retries) to close a race between two
overlapping runs of the same job double-claiming and double-emailing about
the same post_platform.

* Clarify "commit" wording in claim-transaction comment

Reads ambiguously as a git commit on a PR diff; it means the DB
transaction commit.
2026-08-09 11:10:39 -03:00
Paulo Castellano
173a1e4c61
Fix Facebook Page connect pagination (#212) (#253)
* Fix Facebook and Instagram-via-Facebook Page connect pagination.

Follow Graph API paging.next on /me/accounts so authorized non-first Pages are found and multi-Page accounts get the picker instead of silently connecting the first result.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Paginate Meta accounts until paging.next is exhausted.

Drop the artificial 50-page cap and stop only when there is no next URL, or the same request URL repeats (broken pagination loop).

Co-authored-by: Cursor <cursoragent@cursor.com>

* Redact tokens in Graph pagination logs and harden test coverage.

Cover happy-path and failure cases for Meta /me/accounts pagination, including mid-loop failures, invalid paging.next, and Instagram pages without a linked IG account.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fail closed on incomplete Meta accounts pagination.

If a later /me/accounts page fails after earlier pages succeeded, throw instead of returning a truncated list that could auto-connect the wrong Page. Also revert the IG detail timeout that could wipe the whole connect list.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify Graph pagination helpers and page fetchers.

Bake the first request query into the URL, drop requestKey, and let IncompleteGraphPaginationException bubble from the controllers without catch/rethrow noise.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move incomplete pagination exception under Social\Meta.

Colocate it with GraphPaginator so the Meta scope is clear from the namespace instead of a generic Social exception name.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Rename pagination exception to IncompleteMetaGraphPaginationException.

Keep it under Exceptions/Social with Meta in the class name instead of moving it into Services.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Make GraphPaginator results explicit before mapping pages.

Assign the paginated accounts to a variable first so the Facebook and Instagram-via-Facebook fetchers read more clearly.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Build Meta Graph pagination URLs with Laravel Uri.

Replace manual http_build_query concatenation with Uri::of()->withQuery().

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use Laravel HTTP and Uri helpers in Meta Graph pagination.

Prefer response collect/json key access, filled(), and Uri path parsing over manual array and parse_url handling.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify graphVersion using Uri path and str().

Drop basename and native string casts; Uri::path() already yields the Graph API version segment.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop unnecessary str() around graph API config.

Uri: :of() already accepts the string returned by config().
Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify GraphPaginator with Laravel helpers.

Consolidate failure handling via abort(), and use collect, when, throw_if, and Uri::value() for a shorter pagination loop.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refactor social OAuth page/channel selection handling. Update selectPage and selectChannel methods in Facebook, Instagram, and YouTube controllers to return popup callbacks instead of redirecting on session expiration or workspace not found. Enhance HandleInertiaRequests middleware to prevent deferring onboarding progress on social OAuth popup routes. Add tests to verify behavior for expired sessions and onboarding progress.

* Unify Instagram connect behind one card with a method picker.

Hide the Instagram-via-Facebook grid card and offer Instagram Login vs Facebook Pages from a single network entry, matching LinkedIn.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move social popup onboarding assertions into connection tests.

Cover the deferred-prop popup regression on Facebook, Instagram, and YouTube select routes instead of a synthetic onboarding share check.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Stop suppressing onboarding defer on all social routes.

Override onboardingProgress only in popupCallback so picker pages stay deferred and the close page does not re-hit select after session clear.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Always open the Instagram method dialog on connect.

Drop connectMethods and the single-method OAuth shortcut; the picker always offers both Login and Facebook Pages.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Filter Instagram dialog options by enabled platforms.

Keep always opening the method picker, but only list OAuth entry points that are turned on.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Extract Instagram connect methods into a dedicated helper.

Keep connectableOptions focused on shaping grid options while the enabled OAuth list lives in instagramConnectMethods().

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden Meta Graph pagination and localize Instagram connect copy.

Fail closed on Graph request errors and pathological paging, keep Instagram connect going when profile detail lookups time out, and translate the Instagram method dialog strings.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 12:01:46 -03:00
Paulo Castellano
a1fa897106
Activation checklist + MCP OAuth authorize UX (#239) (#250)
* Wire onboarding activation into Account, observers, and shared Inertia data

Add onboarding casts/hasFinishedOnboarding, AccessToken ObservedBy,
Platform::connectableOptions, Post/SocialAccount onboarding broadcast hooks,
and lazy onboardingResidual share + SharedData types.

* Register onboarding routes and post-checkout activation redirects.

Wire billing processing and the sidebar checklist so owners land on
activation after subscribe, with locale sidebar/uk onboarding strings.

* Align MCP grant usability with onboarding activation checks

Unbound MCP tokens fall back to the user's current workspace and require
createPost so viewer/unscoped grants neither unlock the checklist nor
broadcast onboarding status.

* Require bound MCP workspace for onboarding activation.

Drop current-workspace fallback from usable MCP grants so checklist
detection and broadcasts match Passport token scoping; viewers still
cannot unlock the MCP step.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden onboarding review findings and tighten locale strings.

Fix Welcome/Persona/TrackPost suites broken by the activation route reuse
and PostObserver analytics side effects, restore Echo poll fallbacks,
reject unbound MCP grants in tests, and drop unused onboarding.mcp keys.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Remove unused sidebar and MCP authorization locale keys.

Drop dead sidebar menu/theme strings (including the overwritten
workspace label and api_keys nav entry) and unused MCP authorize
app_title/approving copy across all locales.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix SetLocale crashing on Passport Symfony OAuth responses.

OAuth errors return a raw Symfony Response without withCookie(); attach
the default locale cookie via headers so authorize no longer 500s.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Prompt OAuth guests to log in before rejecting unknown clients.

MCP Inspector often reuses a stale client_id; validateAuthorizationRequest
was returning invalid_client JSON before the login redirect. Guests now
hit /login first, then client validation runs after authentication.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Render Inertia OAuth authorize errors for browser logins.

After login, Inertia follows the intended authorize URL; raw invalid_client
JSON broke that visit. HTML/Inertia requests now get mcp/AuthorizeError
while API JSON clients still receive the OAuth error payload.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Detect Inertia OAuth error pages via Request::inertia().

Use the framework helper so post-login authorize failures keep returning
an Inertia page instead of raw OAuth JSON.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify OAuth authorize error page detection to expectsJson.

Drop the X-Inertia header sniff; browser and Inertia visits already do
not expectsJson, while API clients still receive the OAuth JSON payload.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Share MCP authorize layout and drop the error close button.

Keep authorize and authorize-error on the same centered card shell instead of the auth split layout.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify onboarding activation for reviewability and safety.

Use an exists-based MCP check, keep GETs read-only, move sync into
syncAndNotify, clear MCP skips on connect, restrict complete to owners,
and share Echo/poll via one composable.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move MCP OAuth authorize UX out of the onboarding PR.

Keep the activation checklist focused; OAuth guest/error-page work now
lives on fix/mcp-oauth-authorize-ux.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix corrupted French MCP locale after OAuth key cleanup.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Restore MCP OAuth authorize UX onto the onboarding branch.

Keep authorize error page, guest login-before-client validation, and
SetLocale Symfony cookie fix in #250.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix OAuth prompt=none redirects and harden onboarding tests.

Keep login_required/consent_required as redirects instead of Inertia,
add regression coverage for owner-only activation, require invite email
confirmation, and align MCP connected apps with the sessions list UI.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify onboarding guards and dedupe viewed analytics.

Introduce isOnboardingOpen / belongsToAccount helpers, collapse
duplicated sync/dispatch paths, and capture onboarding.viewed once
per account.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify onboarding event, observers, and status helpers.

Tighten Account onboarding predicates, drop nullable broadcast/dispatch
APIs, and collapse repeated observer/controller guards.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Treat in-app users as always having an account.

Add resolveAccount(), tighten belongsToAccount to string ids, and fold
guest residual handling into ResolveOnboardingStatus.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Rename onboarding residual share test to progress.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify onboarding status and rename residual to progress.

Use accountOrFail, extract MCP onboarding scope, auto-leave the ready
screen, and send non-onboarding checkout back to accounts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Extract HasAccount and prefer data_get in onboarding flows.

Move account helpers off User, drop nullable sidebarProgress, and
read OAuth/onboarding payloads with data_get.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify onboarding checks and extract HasOnboarding.

Use Eloquent + policies for MCP/backfill paths, and move account
onboarding helpers into a dedicated trait.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add trait tests and tidy onboarding imports.

Cover HasAccount and HasOnboarding under Models/Traits, prefer filled() for checkout session ids, and import Throwable instead of FQCN.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify checkout session_id and OAuth error props.

Read session_id via request->string(), and take OAuth error details from the League exception instead of decoding the response body.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify PostObserver onboarding notify path.

Share one otherPosts check for first-create and last-delete instead of separate callbacks.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use post author as onboarding sync actor.

Drop Auth::user() preference in PostObserver; checklist sync attributes to $post->user.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify SocialAccountObserver and OAuth authorize flow.

Share create/delete onboarding notify, drop Auth actor fallback to owner, and inline Passport Inertia error handling.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use lazy Inertia props for onboarding partial reloads.

Drop partial-header branching; wrap page props in closures and always redirect completed/dismissed accounts to the calendar.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Defer sidebar onboarding progress and stamp completion as owner-only.

Skip the MCP checklist work on full Inertia visits via deferred shared props,
early-exit token scans, and keep account completion stamps owner-gated.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify deferred onboarding progress share via canShowProgress.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add User firstName for shared auth and simplify onboarding page.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move User firstName coverage into UserTest.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use first_name directly without empty-name fallbacks.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Resolve onboarding sample prompt on the frontend via i18n.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Stamp onboarding completion via the account owner after teammate unlocks.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Count only the account owner MCP grant toward onboarding activation.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix OAuth consent auth-token mismatch for mid-activation owners.

Skip deferred onboardingProgress on Passport authorize so Inertia does not
rotate the session authToken, cover happy and stale-token paths in tests,
and polish MCP setup copy plus sidebar/onboarding layout.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Keep users on onboarding after activation completes.

Stamp completion and re-render the finished checklist instead of
redirecting to the calendar so owners can review the done state.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Clarify Passport consent-view opt-out and guard app-route deferral.

Rename the authorize-only route check and assert onboardingProgress still
defers on calendar, onboarding, and MCP settings.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden onboarding completion and MCP consent workspace binding.

Reject OAuth approve without a workspace, retry auto-complete until
stamped, send dismissed complete straight to calendar, and cover the
device consent defer opt-out.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Enable activation checklist for self-hosted installs.

Remove the self-hosted onboarding redirects, keep the SaaS-only dismiss backfill, and cover subscription-less owners plus skip/complete destinations.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add GitHub, Hacker News, and directories referral sources.

Expand the welcome referral step with open-source and directory discovery channels.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refine welcome referral sources and labels.

Split Instagram/Threads, add Founder, and shorten Google, GitHub, AI, and blog option labels.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Sort accounts platforms alphabetically and drop connect hover plus.

Reuse connectableOptions for the accounts index and remove the unused plus badge on disconnected cards.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Centralize PostHog once-capture so disabled installs don't burn dedupe keys.

Move isEnabled + Cache::add into PostHogService::captureOnce and route onboarding viewed/step events through it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify onboarding backfill to complete every existing open account.

Drop self-hosted and subscription filters; down clears completed_at again.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop PostHog captureOnce and use plain capture for onboarding.

Remove cache-based event dedupe; callers rely on PostHogService::capture gating.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 20:34:43 -03:00
Paulo Castellano
2ca5948309
Scope MCP OAuth tokens to user + workspace (#222) (#245)
* Scope MCP OAuth tokens to user + workspace

Bind authorization-code grants to the authorizing workspace (via auth codes),
inherit workspace on refresh, resolve MCP/API requests from the token instead
of current_workspace_id, backfill existing grants, and revoke workspace tokens
when a member is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add multi-workspace MCP OAuth coverage

Cover coexistence of the same client across workspaces, settings
list/disconnect scoped to the current workspace, and API key
controllers excluding workspace-bound MCP grants.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use constrained foreignUuid for oauth_auth_codes.workspace_id

Match the project's UUID foreign-key convention instead of a separate
foreign() call.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Localize the MCP OAuth authorize consent screen

Wire authorize.blade.php to mcp.* translation keys (including the
workspace scope copy) and cover pt-BR rendering.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix invalid Mockery import in bind workspace test

CI treats the non-compound `use Mockery` as an ErrorException and
aborts the whole parallel suite.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Inline MCP OAuth workspace backfill into the migration

Move the one-shot backfill out of a dedicated Action and wrap it in an
explicit transaction so a failure rolls back partial binds/revokes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Nest MCP authorize i18n keys and test backfill rollback

Group consent-screen copy under mcp.authorize.*, and assert the
workspace backfill migration rolls back binds when it fails before
commit.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Hardcode TryPost in the MCP authorize page title

Drop the config('app.name') interpolation from the consent screen title.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add workspace picker to MCP OAuth consent screen

Let users choose which workspace to bind at authorize time instead of
always using current_workspace_id; silent re-consent still falls back.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Tighten MCP authorize workspace select spacing

Match NativeSelect styling and give the label, control, and helper text room to breathe.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Convert MCP OAuth consent screen to Inertia Vue

Reuse AuthCardLayout, Button, and NativeSelect so the authorize page
matches the app UI. Keep native form posts so Passport's external
redirect still works for MCP client popups.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Polish MCP authorize layout with logo and workspace combobox

Drop the shield and AuthCardLayout double-logo, put TryPost branding
at the top, and reuse the app Combobox pattern for workspace search.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Align MCP OAuth workspace backfill with mcpOAuth scope

Reuse AccessToken::mcpOAuth() so the migration only touches mcp:use
grants on non-PAT clients, matching the rest of the codebase.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Tighten MCP OAuth workspace backfill heuristics

Only touch connected MCP sessions, bind a sole membership or a valid
current workspace, and revoke ambiguous multi-workspace grants instead
of guessing the oldest workspace.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop Passport connection override from auth code migration

Always use the app default database connection from .env.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Bind MCP OAuth workspace in AccessTokenRepository

Replace the AccessTokenCreated listener with the same Passport repository
override pattern used for auth codes, so workspace_id is set at persist.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify AccessTokenRepository workspace binding

Drop redundant string casts and the oldest-workspace fallback; keep a
small ownedWorkspace/payloadId helper surface instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Extract Passport MCP authorization view from AppServiceProvider

Keep configurePassport thin by moving the Inertia consent props into an
invokable App\Passport\AuthorizationView class.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify AuthorizationView and cover it with direct tests

Use collection higher-order mapping for workspaces/scopes and add focused
tests for current-workspace selection and empty-user props.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Rename BindWorkspaceToAccessTokenTest after listener removal

The suite now covers AuthCodeRepository and AccessTokenRepository
workspace binding, not an AccessTokenCreated listener.

* Fail closed when auth code has no bindable workspace

Authorization-code grants no longer fall back to the user's current
workspace, so a token cannot be minted for a different tenant than consent.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Retrigger CI after GitHub Actions infrastructure failures

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: retrigger CI

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: harden MCP OAuth workspace binding on refresh and backfill

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: always show MCP OAuth consent to pick a workspace

Disable Passport silent re-consent and require an explicit workspace_id
from the consent form, with Passport wiring moved to its own provider.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: sort MCP connected clients by last used

Show most recently used OAuth connections first on the workspace MCP settings page.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 21:59:34 -03:00
Paulo Castellano
27287aa130
fix: Pinterest video processing timeout — longer poll + retry (#246)
* fix: give Pinterest video processing more time and retry on timeout

A valid ~54s video pin failed after ~90s of polling while Pinterest was
still processing. Extend the poll window to ~5 minutes and treat timeout
as platform unavailable so PublishToSocialPlatform reschedules instead of
failing the post on the first attempt.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: use Laravel Sleep for Pinterest media processing polls

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: inline Pinterest video processing poll constants

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: map Pinterest media upload statuses to an enum

Use the official MediaUploadStatus values (registered, processing,
succeeded, failed) instead of comparing raw strings in the publisher.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: trim Pinterest media processing docblock

* fix: cap platform-unavailable retries and recover stuck retrying posts

Stop infinite reschedules after 6 attempts with a user-safe failure
message, keep technical detail in error_context, recover Retrying
platforms in social:recover-stuck-posts, and drop unused isTerminal().

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: remove unused failedCount in RecoverStuckPosts

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: skip final Pinterest poll sleep and localize recover timeout

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: raise publish job timeout headroom and ignore already-failed platforms

Give social publish jobs 15 minutes so Pinterest media polling fits under
the worker limit, bump Horizon/redis retry_after above that timeout, and
skip handle/failed when the platform is already Failed so delayed jobs
cannot revive posts recovered by social:recover-stuck-posts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: restore social-publishing and ai-assistant horizon supervisors

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: harden Pinterest 401 handling, unique publish jobs, and recover JSON

Treat media-status 401 as TokenExpired, make PublishToSocialPlatform
unique per platform+attempt so retries still queue, and persist recover
error_context via Eloquent casts instead of manual json_encode.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: mass-update stuck post platforms without per-row each

Eloquent query updates already bind JSON arrays correctly here, so one
UPDATE is enough — no manual json_encode and no N model writes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: simplify Pinterest media processing poll loop

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: simplify publish job retry and terminal status checks

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: do not finalize posts while platforms are still retrying

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: cover Pinterest timeout, unique jobs, and recover edge cases

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: retry Pinterest media poll on connection errors and tighten tests

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: remove ineffective TypeError import that breaks CI

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 20:49:37 -03:00
Paulo Castellano
b4f61be6ef
Welcome: pre-subscription funnel and member subscription-required screen (#243)
* Rename pre-subscription onboarding funnel to Welcome.

Move the ICP steps to /welcome, drop the social-connect checkout gate, hold unpaid members on a subscription-required screen, and keep legacy /onboarding URLs working until the post-subscription checklist lands.

Closes #237

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop legacy /onboarding ICP URL aliases.

Unfinished users re-enter Welcome via EnsureAccountReady on next login; /onboarding stays free for the post-subscription checklist.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify Welcome PostHog event names.

Use welcome.persona/goals/referral and drop the unused checkout case — begin checkout stays on the frontend as checkout.started / begin_checkout.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Slim welcome goal options to match the #204 set.

Drop team_collaboration, automate_api, and track_performance so the goals step stays at nine choices.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Split Welcome AI goals into TryPost AI and MCP assistants.

Rewrite ai_content for in-app generation and add use_mcp so Claude/ChatGPT/Cursor intent is captured separately across locales.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden Welcome goals gate and drop dead checkout UI.

Treat removed goal values as incomplete so mid-funnel users re-select, remove the unused canCheckout branch, and fix the pt-BR welcome progress label.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add password visibility toggle to the login form.

Match the register eye control so users can reveal their password while signing in.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Point the sidebar community link to Discord.

Replace the X stay-updated entry with Join Discord and the trypost.it/discord invite.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Rename the sidebar Discord link to Discord community.

Softer label that matches the other support nav items.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix broken Turkish Discord community translation.

An unescaped apostrophe left a parse error in lang/tr/sidebar.php.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 11:34:50 -03:00
Paulo Castellano
4d8353d758
MCP: workspace settings, viewer read access, and token access (#241)
* Add workspace MCP settings and token access controls.

Ship MCP settings UI, OAuth revoke/list helpers, Passport deploy wiring,
and workspace.token:mcp gating so assistants can connect without pulling
in welcome/onboarding from the parent epic.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Type MCP client config shapes instead of string checks.

Encode http/config-root on each advanced client and tighten primary
client ids so snippet generation does not branch on magic strings.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Polish MCP settings follow-ups from review.

Translate Ukrainian MCP copy, deep-link ChatGPT into connector
creation, drop an unused asset and revoke arg, and assert PATs are
rejected on the MCP endpoint.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden MCP connected clients, revoke scope, and OAuth consent.

List recoverable sessions with live refresh tokens, revoke only PATs,
throttle registration alone, and block viewers from authorizing MCP.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify MCP OAuth route throttling to a single middleware group.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Allow workspace viewers read-only MCP access with web policy writes.

Mirror the web app: MCP connects on view + OAuth mcp:use, write tools
enforce createPost/update/delete/manageAccounts/manageTeam, and demotion
to Viewer keeps grants. Cover role denials, consent, and disconnect.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden MCP tool authz with shared workspace helpers.

Route ApiKey tools through AuthorizesMcpTool, fail closed on null user
or policy argument, and resolve the current workspace before mutating.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop redundant string casts on validated request data.

Enum::from and validated() fields are already strings, so the casts
add noise without changing behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Show only the current user's MCP connections in settings.

Match API keys privacy: list and disconnect your own OAuth clients,
not teammates' across the account.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Cover LoadWorkspaceFromToken gaps and harden AuthorizesMcpTool tests.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop redundant is_string guard before UpdatePostTool find.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refactor AppSidebar to always show MCP link and simplify route middleware definition in ai.php. The MCP link is now consistently displayed regardless of the current workspace state, and the route middleware syntax has been streamlined.

* Refresh MCP connected clients with Inertia usePoll.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Bump laravel/mcp to 0.9.1 and add the TryPost server icon.

Requires laravel/boost 2.5 for the Icon attribute; expose images/trypost/icon.png on TryPostServer.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop no-op ReflectionClass import in TryPostServerTest.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 09:54:51 -03:00
Paulo Castellano
f62b4bb4a5
Unify sidebar workspace and account menus (#240)
* Unify sidebar workspace and account menus.

Merge workspace switching, profile, billing, and language into one header dropdown, move notifications beside it, pin support links to the footer, and add Workspace Settings to the nav — without MCP or onboarding residual.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Remove Workspace Settings from the sidebar nav.

Settings already lives in the unified account menu; keep the workspace group free for items like MCP later.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Cover sidebar menu role gates in browser tests.

Assert account/workspace settings visibility for owner, admin, member, and self-hosted so the unified menu stays aligned with WorkspacePolicy.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Rename sidebar wait helper to avoid Pest browser collision.

waitForTestId was already declared in MobileEditorTest, which fataled the e2e suite when listing Browser tests.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add sidebar menu browser coverage for workspace viewers.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 21:33:16 -03:00
Paulo Castellano
1af705f3fd
Localize calendar date pickers to the active UI locale (#234)
* Localize calendar date pickers to the active UI locale.

Pass the Inertia locale into Reka calendars, translate a11y labels, and use dayjs LL/LLL for DatePicker display text.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Localize remaining dayjs date displays across the UI.

Route list/calendar/preview timestamps through localized LL/LLL helpers so formats follow the active UI locale instead of English or Portuguese-locked patterns.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use scheduled-or-now timestamps in platform previews.

Drive preview labels from the post schedule when set, localize Discord without dayjs calendar(), and expose a single formatPreviewPostedAt helper.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix preview schedule wiring and Discord/Facebook timestamp labels.

Restore hasPickedTime from any saved scheduled_at, keep time on non-today Discord labels, and use a localized just-now fallback for unschedled Facebook previews.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix API key expiry day shift and tighten calendar range titles.

Format date-only expiry in UTC calendar days, and use compact dayjs titles for calendar day/week headers.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Replace frontend date source greps with Inertia API key assertions.

Drop the Vue/TS file scanner and assert expiry calendar days through ApiKeyController props instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Localize calendar week titles with day-first dayjs formats.

Avoid English month-day order in week headers and chart axis labels so locales like pt-BR keep natural day-first dates.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Split preview timestamp formatting into named platform helpers.

Replace the style-switch formatPreviewPostedAt with clear per-platform helpers so call sites read as formatDiscordPreview / formatXPreview / etc.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 21:02:34 -03:00
Paulo Castellano
2248d01edc
Add optional Pinterest pin title and destination link (#232)
* Add optional Pinterest pin title, description, and link.

Expose title/description/link across web, API, and MCP; seed description from caption into meta on save, and publish description only from meta.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Expand Pinterest title/description/link test coverage.

Cover web draft persistence and validation bounds, API/MCP update merge and seed, and publisher payload fields on video and carousel pins.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify Pinterest: description is post content again.

Keep optional title and link in meta/settings only. Remove the separate description textarea, seed logic, and meta.description path so Pinterest follows the shared caption pattern.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refactor Pinterest meta handling and validation.

- Update CreatePost and UpdatePost actions to filter out null values from meta fields.
- Introduce a new method in PinterestPublisher to resolve board IDs, ensuring required fields are validated.
- Enhance PinterestSettings component to manage title and link inputs, including validation for HTTP URLs.
- Update PostPlatformMetaRules to enforce URL validation for Pinterest links.
- Add tests for clearing Pinterest title and link, and for rejecting invalid links during scheduling.

This refactor improves the handling of Pinterest metadata and enhances user experience by ensuring proper validation and error handling.

* Add validation messages and attributes for Pinterest meta fields

- Introduced custom validation messages and friendly attribute names for Pinterest link and title fields in PostPlatformMetaRules.
- Updated StorePostRequest, UpdatePostRequest, and related tools to utilize these new messages and attributes.
- Enhanced tests to assert correct error messages for invalid Pinterest links and title length constraints.

This update improves user feedback during post creation and editing, ensuring clarity in validation errors.

* Remove click.prevent directive from Pinterest link in PinterestPreview component.

This change simplifies the link behavior, allowing default click actions to occur, which may enhance user interaction with the Pinterest link.

* Update validation error messages for Pinterest meta fields in tests

- Refined the assertions in PostApiPlatformMetaTest to include localized validation messages for Pinterest title and link fields.
- Ensured that error messages reflect the updated validation rules, enhancing clarity for users during post creation and editing.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 18:15:50 -03:00
Paulo Castellano
53a5a8bf22
Allow account owners to delete workspaces (#208)
* Allow owners and admins to delete workspaces from settings.

Expose a danger zone with name confirmation, sync Stripe quantity on SaaS, and skip billing constraints in self-hosted mode.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop redundant canDelete prop from workspace settings.

The settings page is already gated by update (owner/admin), which matches delete.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Extract workspace delete danger zone into DeleteWorkspace component.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Clarify workspace delete billing copy across locales.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Match workspace delete card to the delete-account settings pattern.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden workspace and account deletion around shared members.

Enforce owner-only workspace creation, rehome stranded members to a personal account, warn about member access loss, and clarify the only-workspace SaaS exit paths.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden workspace delete: owner-only billing impact and safer member rehome.

Restrict delete to account owners, rehome stranded members transactionally with account-scoped fallbacks, and clean up the danger-zone UI/copy.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix workspace delete review findings.

Prune pending invites and media on delete, lock the account for the
last-workspace guard, fall back to account-owned workspaces for owners,
redirect self-hosted last deletes to create, cancel Stripe after local
cleanup, align personal-account trials, and gate Index create for owners.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Harden invite accept and account delete edge cases.

Stop invite accept from demoting existing roles, expire dead invites on
show, preserve flash by avoiding calendar bounces, move media file I/O
outside locked delete transactions, and finish account deletion even if
Stripe cancel fails.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Fix remaining invite redirect and media cleanup edge cases.

Distinguish already-accepted invites from gone workspaces, rehome
members removed from their last shared workspace, capture media paths
inside the delete lock, extract orphaned-file cleanup, and use Wayfinder
for the expired-invite home link.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Fix invite current-workspace and account-delete edge cases.

Switch invitees onto an invite-account workspace when accepting, prefer
same-account fallbacks when removing members, abort account deletion if
Stripe cancel fails, and clear avatar media on profile delete.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Fix Stripe-failure media leak and invite cross-account redirect.

Flush workspace media files before billing cancel can abort account
delete, and rehome stranded non-owners before picking an invite redirect
fallback so current workspace never points across accounts.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Never set cross-account current workspace on member rehome.

Keep RemoveMember and account-delete member fallbacks same-account
only, clarify the billing-failure flash that workspaces were already
removed, and assert storage deletion in media cleanup tests.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Sync Stripe workspace quantity when account delete billing fails.

After local workspaces are wiped, a stuck cancelNow must still drop
seat quantity so the subscription cannot keep billing the old count.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Prune account invites when owner delete wipes workspaces.

Pending and accepted invites are removed with the workspaces so a
Stripe cancel failure cannot leave unique email/account rows that block
re-invites to a gutted account.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Extract DeleteWorkspaceMedia to purge workspace media rows.

Call sites capture returned paths inside the lock and still flush
orphaned storage files after commit via DeleteOrphanedMediaFiles.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Redirect to calendar after deleting a workspace with a fallback.

When DeleteWorkspace already sets another current workspace, sending
the owner to the workspace picker is unnecessary — take them back into
the app instead.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Use Wayfinder for invite redirect and logo home links.

Replace hardcoded /invites/{id} and / hrefs in AcceptInvite with
show.url() and home() route helpers.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Use Wayfinder home() for AcceptInvite logo link.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Extract AcceptInvite title and description into computeds.

Keeps the expired/active copy logic out of the template and matches
the existing trans() pattern used elsewhere.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Fix lazy-loading crash when deleting a workspace.

isAccountOwner() no longer touches the account relation unless it is
already loaded, and delete/rehome queries eager-load account when they
need ownership checks under Model::shouldBeStrict().

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Avoid isAccountOwner during workspace delete fallback.

Compare against the already-loaded account owner_id so current-workspace
reassignment cannot touch the account relation under shouldBeStrict().

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* Add tests for DeleteWorkspace functionality

Introduce comprehensive tests for the DeleteWorkspace action, covering scenarios such as deleting stranded members, handling multiple workspaces, restoring members with personal workspaces, and managing invites. Ensure that workspace media files are deleted and verify behavior when the last workspace is blocked by SaaS settings. This enhances the reliability of workspace deletion processes and ensures proper account management during deletions.

* Refactor member removal process to delete or restore stranded members

Updated the RemoveMember action to utilize the new DeleteOrRestoreStrandedMember class, which handles the deletion of stranded members or restoration to personal accounts. This change improves the management of user accounts when members are removed from workspaces, ensuring that non-owner members are properly handled based on their account status. Additionally, tests have been updated to reflect these changes, ensuring that the functionality works as intended.

* Enhance member removal and media management during account deletion

Updated the RemoveMember action to collect media paths for orphaned files when removing members. Integrated the DeleteOrphanedMediaFiles action to ensure that any media associated with deleted users is properly purged. Additionally, refactored the DeleteOrRestoreStrandedMember class to return media paths for cleanup, improving overall resource management during user account deletions. This change ensures that all orphaned media files are handled efficiently, maintaining system integrity.

* Enhance user account deletion process with force delete option

Updated the DeleteOrRestoreStrandedMember class to include a forceDelete parameter, allowing for immediate deletion of members and their associated personal accounts and workspaces. This change ensures that when an account is forcefully deleted, all remnants of the user's data are purged, improving data integrity and resource management. Additionally, updated related methods and tests to accommodate this new functionality, ensuring comprehensive coverage and correct behavior during account deletions.

* Extract shared delete/invite actions out of fat controllers.

Centralize workspace/account/user teardown and invite accept/decline so ProfileController and AcceptInviteController stay thin HTTP wrappers.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden delete/invite invariants and replace invite string outcomes.

Block cross-account workspace listing/switching, cancel Stripe on owned accounts before purge, lock RemoveMember, fold owner fallback into ReassignCurrentWorkspace, and type invite results with an enum.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Polish delete/invite teardown APIs and cancel Stripe on empty accounts.

Extract DeleteEmptyOwnedAccounts, rename settle-after-invite, and expose
clearer stranded-member entry points so cancel never races the invite lock.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Finish stranded teardown craft: settle outside locks, clearer names.

Defer empty-account Stripe cancel until after the account lock, rename
stranded handling to SettleStrandedMember, and extract AccountsRequiringCancel.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden multi-account Stripe cancel order and typed stranded settlements.

Cancel member personals before the shared account, introduce CancelAccounts
and StrandedSettlement::flush so partial Stripe failures leave billing intact.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Reuse strandedMemberOnSharedAccount across delete/invite feature tests.

Expand the Pest helper for shared workspaces and owner injection so
stranded-member fixtures stop being hand-rolled in every suite.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Lock the account row during owner account teardown.

Serialize DeleteAccount with DeleteWorkspace/RemoveMember so concurrent
stranded restores cannot move members off the account before force-delete.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop personal-account restore when leaving a shared account.

Invitees abandon their previous personal account on accept, and stranded
members are always deleted — matching the real product flow.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Close the account model and consolidate teardown actions.

Block invites to emails that already belong to a registered user — accounts
are closed (one user, one account), so members never own a personal account.
This removes the whole leftover/restore surface.

Consolidate: fold AccountsRequiringCancel/CancelAccounts into
CancelAccountSubscription, drop DeleteEmptyOwnedAccounts/DeleteOwnedAccount/
PurgeOwnedAccounts, and fold DeleteAccount into DeleteUser. 23 -> 15 new
action files.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Remove orphaned members.errors.already_member translation key.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Block invitees from creating a workspace on the invite shell.

A pending invitee could open workspaces/create (outside EnsureHasWorkspace)
and add a workspace (then billing) on their empty signup shell before accept.
Accept only tears down an empty shell, so this left an abandoned, billable
account. Deny create/store while an invite is pending — the invitee joins via
the invite instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Tighten stranded-member fixtures to the closed-account model.

Drop the member's empty signup shell in strandedMemberOnSharedAccount and the
billing-abort profile test so the setup matches what accept actually leaves
(member owns nothing). Remove the never-overridden attachOwner param.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Bind invite registration to the invited email.

The register form shows the invited email as read-only when an invite id is
present, and store() rejects a different email for a valid invite. Also fixes
a latent bug: EnsureRegistrationEnabled only read the invite id from the query
string, so the self-hosted invite registration POST always 404'd.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move register validation into RegisterRequest.

Inline $request->validate() and the invite-email check move into
App\Http\Requests\App\Auth\RegisterRequest (withValidator). Invite detection
no longer sniffs a /invites/ redirect string — it resolves the invite id
directly; the invite registration test now uses a real invite.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:00:38 -04:00
Paulo Castellano
4cbdfa37d7 Hide video-only formats in the automation Generate node.
AI generate only produces images, so Video Pin / Reel / TikTok Video are filtered out in previewOnly and rejected server-side with a clear error.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-24 23:29:58 -03:00
Paulo Castellano
b9194b9c7d Surface Pinterest board truncation in the web editors.
Share {boards, truncated} via ListPinterestBoards into Inertia and warn in the board picker when pagination stopped early, matching API/MCP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-24 23:02:40 -03:00
Paulo Castellano
564f157e44 Fix MCP upload rate limits and Instagram Reel duration caps.
Key signed uploads by workspace so ChatGPT's shared egress IPs don't throttle tenants together, raise the MCP upload cap to 300MB, and expose accurate Reel max durations via API/MCP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-24 21:21:39 -03:00
Paulo Castellano
8964dda8f2 fix: raise YouTube Shorts max duration to 3 minutes
YouTube Shorts now allow videos up to 3 minutes. The dashboard media rules still capped uploads at 60s (API/MCP already had no duration gate), so align the frontend validation, content-type copy, and unit test.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-23 12:06:15 -03:00
Paulo Castellano
a78f5a96ae feat(onboarding): add "where you found us" referral-source step
Adds a single-select referral-source step between the goals and connect
steps of onboarding. The choice is stored on users.referral_source and
mirrored to PostHog, mirroring the existing persona and goals steps.

- ReferralSource enum (12 sources) + nullable users.referral_source column
- referralSource()/storeReferralSource() controller actions with the same
  self-hosted, subscribed, persona and goals guards as the sibling steps
- connect() now requires a referral source before rendering
- Single-select ReferralSource.vue page mirroring the goals step
- Localized across all 15 locales
2026-07-18 16:07:11 -03:00
Paulo Castellano
2c2ab69e68 Merge main + finalize AI brand-colors toggle
Resolves the AiPostWizard conflict and completes the feature:
- i18n parity: brand_colors_label + brand_colors_description in all 15 locales
  (was en/es/pt-BR only, which broke LocalizationParityTest).
- Reworked the two-button toggle into a Switch with an explanatory description
  (matches the settings Switch/card pattern).
- Only shown for templates that honor the flag: added appliesBrandVisuals() to
  the AiContentTemplate contract (ImageCard=true, tweet cards=false), exposed as
  applies_brand_visuals in the create-page DTO, and gated the toggle on it — so
  it no longer appears (as a no-op) for tweet-card styles.
- Tests: TemplateContractTest covers appliesBrandVisuals for all templates.
2026-07-18 15:12:26 -03:00
Paulo Castellano
5118640a9c feat(automations): mobile-safe builder with desktop notice
The node builder is gated to lg+ (its fixed side panels no longer overflow a phone); below lg it shows a 'works best on a larger screen' notice. Automation tabs scroll instead of cutting off.
2026-07-17 18:38:20 -03:00
Paulo Castellano
b7b3809790 feat(posts): make the post editor usable on mobile
- Top switcher (Compose / Channels / Preview / Comments) reveals the panel that was hidden below lg
- Sticky bottom action bar puts schedule/publish/delete within thumb reach
- Composer media actions and comment toolbar are visible on touch (no hover needed); media grid is 3-up
- Clamp media picker and emoji picker widths to the viewport
2026-07-17 18:38:20 -03:00
Paulo Castellano
797750a1c8 Show the alt text on the thumbnail and drop the file-size badge 2026-07-11 12:49:56 -03:00
Paulo Castellano
8d7948cb2e Add per-image alt text editor to the post composer 2026-07-11 09:45:52 -03:00
Paulo Castellano
36ccc570e0 Rewrite the image cropper as a movable/resizable selection box
Replace the move-image-behind-a-fixed-frame model with a selection box over the fully visible (contain-fit) image: drag to move, corner handles to resize, locked to 1:1 for the square avatar/logo output. The default selection is inset so the crop outline is always visible, handles sit inside the frame so they are never clipped, and wheel/pinch zoom is swallowed. Reset drag state on open/close, guard pointer capture and multi-touch, and fail-safe the canvas encode. Update the crop copy in all 15 locales to match the selection model.
2026-07-04 09:56:31 -03:00
Paulo Castellano
2549a82e9b Address review: cropper mime/zoom/error fixes, harden browser test
- Output a canvas-encodable mime (jpeg/png/webp, else png) and keep the File's
  name/extension in sync, so non-encodable input (gif/svg/heic) no longer ships
  PNG bytes mislabeled as the original type.
- Clamp zoom to a maximum (8x cover) so scrolling in can't collapse the crop to
  a sub-pixel region.
- Handle undecodable/zero-dimension images (@error + naturalWidth guard) with a
  crop_error message instead of a permanently-disabled Save.
- Replace the str_contains(static::class) Vite heuristic with a dedicated
  BrowserTestCase ($fakesVite = false).
- The browser test now decodes the dispatched blob and asserts a 512x512 image,
  and uses route(..., absolute: false) instead of a hardcoded path.
- Remove tests/Browser/ProbeTest.php (committed debug scratch).
2026-07-03 22:07:23 -03:00
Paulo Castellano
c6369a6ddb Crop the avatar/logo before upload with a dependency-free cropper
Selecting an avatar or workspace logo now opens a crop dialog (drag + zoom)
before uploading, so the image is framed the way it renders. The crop is
performed client-side and the resized 512x512 result is what gets uploaded.

This reworks the idea from #131 without its cropper dependency: vue-advanced-cropper
was last released ~2 years ago and we did not want an unmaintained package for
something this load-bearing. What we need is narrow (fixed 1:1, a circle/square
mask, fixed-size output), so a small canvas-based cropper covers it:

- imageCrop.ts: pure transform math (cover-fit, clamp, zoom, viewport->source).
- ImageCropperDialog.vue: CSS-transform preview, pointer drag, wheel/button zoom,
  a ResizeObserver to measure the modal (no requestAnimationFrame timing hacks),
  and a canvas toBlob only on save.
- PhotoUpload.vue: opens the cropper on file select; the mask shape follows the
  display shape (round avatar / square logo) instead of always being round.
- crop_* strings added to all 15 locales.

Also installs Pest browser testing (pest-plugin-browser + Playwright) and adds a
browser test for the crop flow. TestCase only calls withoutVite() for non-browser
tests, since browser tests need the real Vite assets to boot the SPA. The Pest
browser server does not parse multipart uploads, so the test asserts the crop
dispatches the correct upload request; endpoint persistence stays covered by
ProfileUpdateTest.
2026-07-03 21:46:19 -03:00
Paulo Castellano
c7be1af124 Detect all 15 content languages on autofill, harden RTL/i18n, and cover the gaps with tests
- Brand-analyzer prompt now lists every supported language instead of only
  en/pt-BR/es, so onboarding autofill can detect the 12 added languages. The
  backtick-formatted list is built in BrandAnalyzer::instructions(), keeping the
  Blade clean and the enum free of prompt presentation.
- Translate the delete-confirmation keyword for el/ja/zh/ar (the four locales
  that still shipped the English "delete").
- Make the language and font comboboxes RTL-correct (logical ms-* instead of
  physical ml-*), and let the language combobox be searched by English name via
  a visually-hidden label (ContentLanguage::options() now exposes englishName).
- Correct the ContentLanguage class docblock: the enum is also the source of
  truth for the UI locales' text direction.

Tests: SetLocale middleware dir/RTL, isRtl and the full 15-language
englishName/label match arms, LLM language detection beyond en/es/pt-BR, and
store-path persistence of a non-default content language plus rejection of an
unsupported one.
2026-07-03 18:52:45 -03:00
Paulo Castellano
519175f9fd Translate the sidebar Beta badge and place it at the row end for RTL
Move the nav badge from the physical right-2 to the logical end-2 so it
sits at the end of the row in both directions (right in LTR, left in RTL).

Replace the hardcoded 'Beta' string with a global common.beta translation
key across all 15 locales.
2026-07-03 18:22:19 -03:00
Paulo Castellano
e17b86ac93 Make the content-language field a searchable combobox and reload on UI-language switch
Replace the plain content-language <Select> in the brand form with a
searchable LanguagePicker combobox (Popover + Command), matching the
FontPicker. i18n the combobox placeholder/search/empty strings across all
15 locales.

Switch the UI language via a full page reload instead of client-side dir
syncing, so the server-rendered <html dir> flips LTR<->RTL correctly
without a manual refresh.
2026-07-03 18:17:38 -03:00
Paulo Castellano
6797706921 Translate the interface into 12 languages
Add full lang/ translations for fr, de, it, nl, pl, el, ja, ko, zh, ru,
tr, and ar — all 23 base files each, with identical key trees to lang/en,
preserved :placeholders and plural forms, and native product terminology.
2026-07-03 15:38:40 -03:00