The Brand.vue autofill was hitting the endpoint with a raw fetch()
call including manual CSRF header wiring, content-type boilerplate,
and error parsing. Inertia v3 ships useHttp() for standalone HTTP
requests that handles all of that natively — matching the convention
already used elsewhere in the app (YouTubeAnalytics, XAnalytics,
InstagramAnalytics).
Typed the payload and response shape so the composable gives us
type-safe access to the fields we care about. Error handling now
reads from the Inertia exception's response.data.message.
When config('trypost.ai.text_provider') points to a provider whose
API key is populated (services.gemini.api_key or
services.openai.api_key), the autofill action pipes the homepage
markdown through a BrandAnalyzer agent with structured output to
produce higher-quality values for:
- brand_description — 2-3 sentences summarizing the company based on
the actual page content, not the raw meta description (which is
often generic SEO boilerplate)
- brand_tone — classified into one of our seven enum values from the
writing style on the page
- content_language — detected from the actual content (more reliable
than <html lang> which is often wrong)
- brand_voice_notes — concrete writing guidelines inferred from the
site's style, written in the detected language
When the LLM provider is NOT configured (open-source self-hosted
deploys without API keys), the action keeps the existing
deterministic meta-tag-only flow — no crash, no noise, no LLM cost.
When the LLM fails mid-request, we log a warning and fall back to
the meta-tag values so the user still gets something useful.
Stack additions:
- league/html-to-markdown ^5.1 converts the main body to clean
markdown for the LLM input (truncated to 4000 chars).
- BrandAnalyzer agent (Agent + HasStructuredOutput) with schema
enums matching our allowed tones and languages.
- resources/views/prompts/brand_analyzer.blade.php holds the
instructions, including explicit enum lists and examples of good
voice_notes.
Frontend: Brand.vue now also fills brand_tone and brand_voice_notes
from the response when present.
Tests (+3): LLM-configured happy path, no-credentials fallback
(asserts BrandAnalyzer is never prompted via preventStrayPrompts),
and LLM-exception fallback (meta tags win, brand_tone stays null).
Reka UI's SelectValue extracts the displayed text from the slot of
the currently-selected SelectItem. When that slot is a reactive
{{ $t('onboarding.brand.tone_professional') }} expression, the
library reads the DOM content before Vue applies the translation,
leaving the raw key visible in the trigger even after the list has
rendered correctly.
Bypass the lookup by rendering the translated label directly inside
<SelectValue> via a computed that maps the current v-model value to
its localized string. The SelectItem slots keep their translations
for the dropdown menu itself, but the closed-state trigger no longer
depends on DOM introspection.
Applied to both the onboarding Brand form and Settings → Workspace.
trans() is the laravel-vue-i18n helper that must be imported into
<script setup> for use in TS logic (like toast messages). Inside
<template>, the plugin registers a global $t() that should be used
instead — imports aren't needed and it matches Vue I18n conventions.
Converted all :placeholder / :title / :description / :action bindings
in Brand.vue and Workspace.vue to $t(). Also added explicit
:placeholder to the Brand and Workspace Selects so if the initial
v-model value hasn't resolved to a matching SelectItem yet, the user
sees the field label instead of the raw translation key.
Dropped the now-unused trans import from Workspace.vue.
The onboarding Brand page was reusing settings.brand.* keys, which
coupled two unrelated pages: a rename in Settings would silently break
onboarding, and the two pages might want to diverge copy later (e.g.
more welcoming language during first-run vs terse settings labels).
Duplicated the relevant keys (field labels, placeholders, tone
options, content language copy) into onboarding.brand.* across
en/pt-BR/es. The Settings workspace page keeps using
settings.brand.* — they're the source of truth for that page now.
No behavior change; just separation of ownership.
The brand section was only defined in lang/en/settings.php, so users
with locale pt-BR or es saw raw keys (settings.brand.website,
settings.brand.tone_professional, etc.) instead of translations on
the onboarding Brand step and in Settings → Workspace → Brand.
laravel-vue-i18n doesn't fall back to 'en' the way Laravel's backend
translator does for JSON keys — each locale must define everything it
references.
Added the full brand block to both pt-BR/settings.php and
es/settings.php, matching the English keys 1:1.
Users on the Brand step can type their website URL and click
'Preencher' (Portuguese) / 'Autofill' (English). The backend fetches
their homepage, parses standard meta tags, and returns:
- name ← og:site_name | title (suffix stripped at ' | ', ' - ')
- description ← meta[name=description] | og:description
- language ← <html lang> mapped to en / pt-BR / es
- logo ← apple-touch-icon | largest link[rel*=icon] | og:image
The logo is downloaded, validated (mime whitelist, 2MB max), and
attached to the workspace's 'logo' media collection so the avatar
updates immediately.
Zero LLM calls, zero external APIs. Uses symfony/dom-crawler +
symfony/css-selector (newly required) for meta extraction. Everything
else (Http client, workspace media, Intervention) was already in the
project.
Security:
- SSRF guardrail: resolves the host, rejects private / loopback /
link-local ranges, enforces http(s) scheme on both the initial
page fetch and the logo download.
- Rate limited at 10 req/min per user via the throttle middleware
alias on the route.
- Logo content-type must be one of the allowed image mimes; wrong
types are silently dropped so users never see broken images.
UX:
- 'Autofill' button next to the website input, disabled until there
is a URL; shows a spinner while running.
- If a logo was captured, a small preview appears below the input
so users can see what was pulled before saving.
- Success and error paths both surface as vue-sonner toasts, with
translations in en / pt-BR / es.
- Failures leave the form untouched — nothing is destructively
overwritten if parsing gave us nothing.
Tests (16 new): action-level coverage for happy path, title-suffix
fallback, language code normalization across 6 locales, scheme
rejection, private-range SSRF rejection, implicit https prefixing,
empty sites, upstream errors, and wrong-mime logo rejection. Plus
two controller-level tests for the autofill endpoint.
After users pick their persona (role), they now land on a new Brand
step that collects the same fields available in Settings → Workspace
→ Brand: website, description, tone, voice notes, and content
language. When they continue, every AI-generated post for this
workspace already has sensible defaults — before the user's first
post is ever drafted.
Flow:
Role (persona) → Brand (new) → Connections → Subscription → Completed.
A 'Skip for now' button on the brand step advances to Connections
without touching the workspace (defaults stay at their seed values).
Backend:
- Setup enum gets a new Brand case slotted between Role and
Connections with matching stepNumber updates.
- OnboardingController::brand() renders the form pre-filled from the
current workspace. storeBrand() validates via a new
StoreBrandRequest form request and writes the fields onto the
workspace, then advances setup. skipBrand() just advances.
- storeRole() redirects to brand instead of account. enforceStep()
knows how to redirect users whose setup is Brand.
- Three new routes: GET /onboarding/brand, POST /onboarding/brand,
POST /onboarding/brand/skip.
Frontend:
- New Brand.vue page mirrors the Settings brand form but inside the
onboarding AuthLayout. Tone + language sit side by side, both
selects take full width. Translations added to en, pt-BR, and es.
- Wayfinder regenerated so the page can import storeBrand / skipBrand.
Tests:
- Renamed 'redirects to step2' → 'redirects to brand step' and
assert new setup.
- Added six new tests covering brand step auth, redirects, render,
successful store, validation of tone and content_language, and
skip.
- Updated UserSetupTest for the new enum case + reshuffled step
numbers.
The Laravel locale is declared as 'pt-BR' (uppercase BR) in
config/languages.php, but the translations lived in lang/pt-br/
(lowercase). The laravel-vue-i18n Vite plugin names its output bundle
after the folder — php_pt-br.json — so when the frontend resolved
lang/php_pt-BR.json (from page.props.locale), the lookup failed
silently and strings fell back to the raw keys which render as
English-looking text.
Renaming the folder to lang/pt-BR/ aligns bundle name, file system
path, and Laravel locale code, so translations load correctly again
for users with locale=pt-BR.
The shadcn SelectTrigger ships without w-full, so both dropdowns were
shrinking to their label width while every other input in the form
stretches full-width. Added w-full to both triggers to match the
surrounding inputs.
Users can now pick the language AI uses for captions, hashtags,
descriptions, AND on-image / on-screen text — independent of the
app UI locale. A user with pt-BR UI who writes for an English
audience gets English content, and vice versa.
- New content_language column on workspaces (added to the existing
create_workspaces_table migration since we're pre-production),
defaulting to 'en'. Fillable on the model.
- Dropdown in Settings → Workspace → Brand, side-by-side with Tone.
Options: English, Português (Brasil), Español. Short helper copy
explains what the setting controls.
- Validation: sometimes|string|in:en,pt-BR,es — optional on update
so existing callers that don't post the field keep the current
value (DB default handles fresh workspaces).
- System prompt now uses $content_language (sourced from the
workspace) instead of app()->getLocale(). The rule was also
strengthened: the AI must always write in this language regardless
of what language the user types instructions in, and must instruct
image/video tools to render on-media text in this language too.
- Image and video Blade prompts received a new line forcing any text
rendered inside the generated media to use $content_language.
- GenerateImage tool and VideoGenerationService pass the workspace's
content_language into their respective prompt templates.
Previously the caption would be in Portuguese (since it followed the
user's input language) but the image could render with English text
because there was no explicit constraint. Now the whole pipeline is
aligned to one per-workspace language.
Critical fixes:
- Quota enforcement regressed when the regex flow was replaced with
tools. The LLM was trusted to respect [Session state] quota hints,
which is vulnerable to prompt injection / hallucination. Each tool
now checks Pennant feature limits at the top of handle() and returns
a short quota-exhausted string instead of calling the provider.
Audio shares the video quota (there is no AiAudioLimit by design).
- N+1 on aiMessages: combined the two separate ->get() scans that
produced imagesInThread and videosInThread into a single query.
- postPlatforms lazy load: controller now loadMissing('postPlatforms')
before constructing SocialMediaAssistant, which accesses the relation
in activePlatformRules().
Project conventions:
- \RuntimeException and \Throwable are now imported at the top of the
controller instead of inlined per CLAUDE.md.
- Tool handle() methods use data_get($request, 'prompt') instead of
direct array access, matching the data_get convention for service
classes.
- enrichContent() pluralizes attachment types via Str::plural so
'2 images' reads naturally instead of '2 image'.
Tests:
- Added Storage::fake('public') in tool tests so runs don't pollute
the local disk with fake-generated files.
- Restored quota enforcement coverage (deleted when the flow changed)
as three new tests — one per tool — that fill the monthly bucket
and assert the tool refuses and nothing is generated.
- Removed inline \App\ references in tests in favor of imports.
SocialMediaAssistant::activePlatformRules() reads post_platforms on the
attached Post, maps them to Platform enum values, and resolves rule
classes via Registry::forMany(). The rendered instructions include only
the summaries of platforms actually selected on this post — so when a
user is posting to X only, the agent doesn't waste tokens thinking
about Instagram Reels.
The PLATFORM KNOWLEDGE block in system.blade.php is replaced with
@include('prompts.assistant.platforms') which iterates the passed rules
and renders each summary. When the post has no platforms, the section
renders nothing (a @if guards it).
Each platform has a rule class exposing specs() (char limits, aspect
ratios, media limits, format-specific constraints) and summary() (a
short concise description the agent can render into instructions).
Registered in AppServiceProvider::configurePlatformRules() mapping
Platform enum values to rule classes. Both InstagramFacebook and
LinkedInPage share rules with their non-business siblings.
Contract + Registry follow the lookup-map pattern. Registry is a
static registry seeded at boot — rules are cheap enough to new up
per request.
Tests cover all 12 platforms via Pest dataset and verify the forMany
fan-out, clear/register behavior, and representative summaries.
Controller now delegates to SocialMediaAssistant::prompt() and reads
generated attachments from AttachmentCollector (request-scoped). The
three preg_match branches for [GENERATE_IMAGE/VIDEO/AUDIO] commands
are gone — the LLM invokes tools directly with typed parameters.
Deleted:
- app/Services/Ai/GeminiTextGenerationService.php
- app/Services/Ai/TextGenerationService.php (OpenAI alternative)
- app/Services/Ai/ImageGenerationService.php
- app/Services/Ai/AudioGenerationService.php
- app/Services/Ai/Contracts/TextGenerationInterface.php
Kept: VideoGenerationService (wrapped by GenerateVideo tool since
Veo is not in the SDK's provider matrix) and IntentDetector.
Tests now fake the agent via SocialMediaAssistant::fake() with either
canned text or a callable that simulates tool side-effects by pushing
directly into AttachmentCollector.
The agent now implements HasTools and returns three tool instances
(GenerateImage, GenerateVideo, GenerateAudio) each wired with the
workspace + post + userId context.
Replaced the MEDIA GENERATION RULES block in the system prompt. Tools
replace the old [GENERATE_IMAGE:vertical] regex convention — the LLM
now invokes tools directly with typed parameters (prompt, orientation),
which eliminates the fragile text parsing in the controller.
Each tool implements Laravel\Ai\Contracts\Tool with description(),
handle(Request), and schema(JsonSchema). They share a common pattern:
- Constructor receives Workspace, optional Post, userId, and an optional
AttachmentCollector (resolves from container if not injected).
- handle() does the work (Image::of(), Audio::of(), or calls our custom
VideoGenerationService for Veo), persists media + usage log, pushes
the full attachment shape into the collector, and returns a short
text summary to the LLM.
- schema() exposes typed parameters with enum constraints and doc
strings so the LLM selects valid inputs.
Also fix the Ai::extend closure signature — MultipleInstanceManager
passes (app, config) not just (config) to custom creators.
The agent implements Laravel AI SDK's Agent + Conversational contracts:
- instructions() renders the existing Blade system prompt with workspace
brand context (name, description, website, tone, voice notes, locale)
- messages() reads directly from the AiMessage model scoped to the post,
so our existing conversation persistence stays the single source of
truth — no duplicate SDK-managed storage.
- Assistant messages with attachments are enriched inline with a summary
like [This assistant message attached: 2 image] so the model tracks
progress through carousel-style multi-image generations.
- provider() maps the trypost.ai.text_provider config to Lab::Gemini or
Lab::OpenAI, preserving the existing provider-switching behavior.
The stock provider only exposes 1:1, 2:3, 3:2 via defaultImageOptions()
match statement — any other ratio gets silently dropped to null.
ExtendedGeminiProvider adds 9:16, 16:9, 4:3, 3:4, 4:5, 5:4, 21:9 so
Image::of()->size('9:16') now works for Reels/Stories/TikTok/Shorts
and size('16:9') for X/LinkedIn/YouTube landscape content.
Gemini's native API supports all these ratios; the SDK restriction was
purely in the provider's match statement.
AiUsageLogTest and UsageController still passed string 'image'/'video'
arguments to monthlyCount() after the enum migration. Update them to
pass UsageType::Image and UsageType::Video.
- Block all billing/usage/subscribe routes in self-hosted mode (redirect to calendar)
- Hide billing_email field in account settings when self-hosted
- Migrate deprecated Facebook Page Insights metrics to new Media Views API (v25.0)
- Fix X analytics token refresh to use Basic Auth (matching XPublisher/ConnectionVerifier)
- Prevent duplicate social accounts by using updateOrCreate across all OAuth controllers
- Sidebar reorganized: Workspace group (connections, hashtags, labels,
API keys, settings) and Account group (settings, usage, billing)
- Account group only visible to owner and hidden in self-hosted mode
- Onboarding simplified: role -> account (connect socials) -> completed
-> redirect to /subscribe. Removed Subscription setup step.
- Subscribe page redesigned with 4 plan cards, monthly/yearly toggle,
trial info, and per-plan features list
- Billing page redesigned following Sendkit layout (sections with
sidebar labels)
- Processing page uses usePoll with immediate watch for subscription
activation
- Cancel URL redirects directly to /subscribe
- Account settings page with name and billing_email (syncs with Stripe)
- Usage page with ring meters for all plan limits
- Settings layout tabs only for user pages (profile, password,
notifications). Workspace/API keys/billing are standalone pages.
- GoogleAuthButton extracted as reusable component
- WorkspaceRole TypeScript enum for type-safe role checks in frontend
- Trial period changed to 7 days
- Fixed onboarding loop when user confirms email
- All 1101 tests passing
- Create Account model as Cashier Billable entity (stripe, plan, subscription)
- Account owns workspaces and has an owner_id (User)
- User belongs to one Account via account_id
- Workspace belongs to Account via account_id, no longer has billing fields
- Remove Brand model entirely (workspaces serve as grouping)
- Rename brand_limit to workspace_limit in plans
- Workspace roles simplified: admin/member/viewer (owner via Account)
- Invites now belong to Account with workspaces JSON array
- Pennant features scope changed from Workspace to Account
- EnsureSubscribed middleware checks Account subscription
- All controllers updated: BillingController, OnboardingController,
WorkspaceInviteController, SocialController, StripeEventListener
- Frontend: extract GoogleAuthButton component, create WorkspaceRole
enum for type-safe role checks, fix all views for new architecture
- All 1101 tests passing
- New card-based layout showing connected accounts with avatar, platform
badge, brand label, and connection date
- "Add Social" button opens dialog with platform grid for connecting
- Removed unique constraint on workspace_id+platform to allow multiple
accounts per platform
- Removed "already connected" checks from all 13 OAuth controllers
- Updated tests to verify multi-account connection works