Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Add in-app tours: Publish views, Insights filters and the MCP card (#503)
Paulo Castellanof9de16fabc8d
diff --git a/.agents/skills/in-app-copy/SKILL.md b/.agents/skills/in-app-copy/SKILL.mdindex 45ed98ff4..51ace777d 100644--- a/.agents/skills/in-app-copy/SKILL.md+++ b/.agents/skills/in-app-copy/SKILL.md@@ -1,6 +1,6 @@---name: in-app-copy-description: "Use this skill to write, rewrite or review any text the end user reads inside the TryPost app: lang keys in lang/*/*.php, labels, buttons, tabs, menu items, tooltips, popovers that ask for an action, empty states, dialogs and confirmations, errors, validation messages, toasts, settings descriptions and onboarding steps. Trigger on requests like 'improve this text', 'rewrite this popover', 'this copy is bad', 'review the product copy', 'translate this key', or any new UI string. Covers the three-step pattern for action prompts, tone, per-component rules, the 16-locale workflow and a review checklist. Not for marketing pages, emails' visual layout or AI prompts (see copywriting, the Maizzle rules and the AI agents rules)."+description: "Use this skill to write, rewrite or review any text the end user reads inside the TryPost app: lang keys in lang/*/*.php, labels, buttons, tabs, menu items, tooltips, popovers that ask for an action, empty states, dialogs and confirmations, errors, validation messages, toasts, tour steps, settings descriptions and onboarding steps. Trigger on requests like 'improve this text', 'rewrite this popover', 'this copy is bad', 'review the product copy', 'translate this key', or any new UI string. Covers the three-step pattern for action prompts, tone, per-component rules, the 16-locale workflow and a review checklist. Not for marketing pages, emails' visual layout or AI prompts (see copywriting, the Maizzle rules and the AI agents rules)."metadata:author: trypost---@@ -107,6 +107,27 @@ Never a bare "Nothing here".- The line under a settings page title stays on one line in every locale.- Helper text under a field explains the effect of the setting, not its name.+### Tours++A tour step (`TourStep`, `lang/*/tours.php`) sits right next to the control it points at, so the user already sees the control's own words. The step says what the control does for them, not what it contains (owner decision November 2026).++- **Title: the action the control gives, verb + object**, in the words on the control: "Filter by period", "Filter by channel", "Switch views". Not a question, not "New feature".+- **Description: one short sentence on what the user gets out of it.** Never list the options the control already shows (the presets, the view names): the user is looking at them.+- **No mechanism, no settings, no "next time".** What the app remembers or how the filter is built does not belong in a tour.+- **Short enough to read at a glance:** the card is 320px wide; aim for one line of title and one or two lines of description in the longest locale.++Reference: the Insights filters tour (`tours.insights.filters`).++Before (rejected, lists what the control shows):++> **Pick the period**+> Look at the last 7 or 30 days, this month so far, or pick your own dates.++After (approved):++> **Filter by period**+> Filter your data by recent days or by specific dates.+## Localization (16 locales)Every string ships in `lang/{ar,de,el,en,es,fr,it,ja,ko,nl,pl,pt-BR,ru,tr,uk,zh}`. `LocalizationParityTest` fails when a key is missing in one.diff --git a/.claude/skills/in-app-copy/SKILL.md b/.claude/skills/in-app-copy/SKILL.mdindex 45ed98ff4..51ace777d 100644--- a/.claude/skills/in-app-copy/SKILL.md+++ b/.claude/skills/in-app-copy/SKILL.md@@ -1,6 +1,6 @@---name: in-app-copy-description: "Use this skill to write, rewrite or review any text the end user reads inside the TryPost app: lang keys in lang/*/*.php, labels, buttons, tabs, menu items, tooltips, popovers that ask for an action, empty states, dialogs and confirmations, errors, validation messages, toasts, settings descriptions and onboarding steps. Trigger on requests like 'improve this text', 'rewrite this popover', 'this copy is bad', 'review the product copy', 'translate this key', or any new UI string. Covers the three-step pattern for action prompts, tone, per-component rules, the 16-locale workflow and a review checklist. Not for marketing pages, emails' visual layout or AI prompts (see copywriting, the Maizzle rules and the AI agents rules)."+description: "Use this skill to write, rewrite or review any text the end user reads inside the TryPost app: lang keys in lang/*/*.php, labels, buttons, tabs, menu items, tooltips, popovers that ask for an action, empty states, dialogs and confirmations, errors, validation messages, toasts, tour steps, settings descriptions and onboarding steps. Trigger on requests like 'improve this text', 'rewrite this popover', 'this copy is bad', 'review the product copy', 'translate this key', or any new UI string. Covers the three-step pattern for action prompts, tone, per-component rules, the 16-locale workflow and a review checklist. Not for marketing pages, emails' visual layout or AI prompts (see copywriting, the Maizzle rules and the AI agents rules)."metadata:author: trypost---@@ -107,6 +107,27 @@ Never a bare "Nothing here".- The line under a settings page title stays on one line in every locale.- Helper text under a field explains the effect of the setting, not its name.+### Tours++A tour step (`TourStep`, `lang/*/tours.php`) sits right next to the control it points at, so the user already sees the control's own words. The step says what the control does for them, not what it contains (owner decision November 2026).++- **Title: the action the control gives, verb + object**, in the words on the control: "Filter by period", "Filter by channel", "Switch views". Not a question, not "New feature".+- **Description: one short sentence on what the user gets out of it.** Never list the options the control already shows (the presets, the view names): the user is looking at them.+- **No mechanism, no settings, no "next time".** What the app remembers or how the filter is built does not belong in a tour.+- **Short enough to read at a glance:** the card is 320px wide; aim for one line of title and one or two lines of description in the longest locale.++Reference: the Insights filters tour (`tours.insights.filters`).++Before (rejected, lists what the control shows):++> **Pick the period**+> Look at the last 7 or 30 days, this month so far, or pick your own dates.++After (approved):++> **Filter by period**+> Filter your data by recent days or by specific dates.+## Localization (16 locales)Every string ships in `lang/{ar,de,el,en,es,fr,it,ja,ko,nl,pl,pt-BR,ru,tr,uk,zh}`. `LocalizationParityTest` fails when a key is missing in one.diff --git a/.cursor/skills/in-app-copy/SKILL.md b/.cursor/skills/in-app-copy/SKILL.mdindex 45ed98ff4..51ace777d 100644--- a/.cursor/skills/in-app-copy/SKILL.md+++ b/.cursor/skills/in-app-copy/SKILL.md@@ -1,6 +1,6 @@---name: in-app-copy-description: "Use this skill to write, rewrite or review any text the end user reads inside the TryPost app: lang keys in lang/*/*.php, labels, buttons, tabs, menu items, tooltips, popovers that ask for an action, empty states, dialogs and confirmations, errors, validation messages, toasts, settings descriptions and onboarding steps. Trigger on requests like 'improve this text', 'rewrite this popover', 'this copy is bad', 'review the product copy', 'translate this key', or any new UI string. Covers the three-step pattern for action prompts, tone, per-component rules, the 16-locale workflow and a review checklist. Not for marketing pages, emails' visual layout or AI prompts (see copywriting, the Maizzle rules and the AI agents rules)."+description: "Use this skill to write, rewrite or review any text the end user reads inside the TryPost app: lang keys in lang/*/*.php, labels, buttons, tabs, menu items, tooltips, popovers that ask for an action, empty states, dialogs and confirmations, errors, validation messages, toasts, tour steps, settings descriptions and onboarding steps. Trigger on requests like 'improve this text', 'rewrite this popover', 'this copy is bad', 'review the product copy', 'translate this key', or any new UI string. Covers the three-step pattern for action prompts, tone, per-component rules, the 16-locale workflow and a review checklist. Not for marketing pages, emails' visual layout or AI prompts (see copywriting, the Maizzle rules and the AI agents rules)."metadata:author: trypost---@@ -107,6 +107,27 @@ Never a bare "Nothing here".- The line under a settings page title stays on one line in every locale.- Helper text under a field explains the effect of the setting, not its name.+### Tours++A tour step (`TourStep`, `lang/*/tours.php`) sits right next to the control it points at, so the user already sees the control's own words. The step says what the control does for them, not what it contains (owner decision November 2026).++- **Title: the action the control gives, verb + object**, in the words on the control: "Filter by period", "Filter by channel", "Switch views". Not a question, not "New feature".+- **Description: one short sentence on what the user gets out of it.** Never list the options the control already shows (the presets, the view names): the user is looking at them.+- **No mechanism, no settings, no "next time".** What the app remembers or how the filter is built does not belong in a tour.+- **Short enough to read at a glance:** the card is 320px wide; aim for one line of title and one or two lines of description in the longest locale.++Reference: the Insights filters tour (`tours.insights.filters`).++Before (rejected, lists what the control shows):++> **Pick the period**+> Look at the last 7 or 30 days, this month so far, or pick your own dates.++After (approved):++> **Filter by period**+> Filter your data by recent days or by specific dates.+## Localization (16 locales)Every string ships in `lang/{ar,de,el,en,es,fr,it,ja,ko,nl,pl,pt-BR,ru,tr,uk,zh}`. `LocalizationParityTest` fails when a key is missing in one.diff --git a/.env.example b/.env.exampleindex 688717f08..c5408b2d6 100644--- a/.env.example+++ b/.env.example@@ -27,6 +27,8 @@ X_DEFUSE_LINKS=false# Show the "What's New" sidebar card and modal (entries under# resources/changelog/, synced with `php artisan changelog:sync`).CHANGELOG_ENABLED=true+# Open the in-app tours (TourStep) the first time a user sees a page.+TOURS_ENABLED=trueMETA_PAGE_WALK_SECONDS=20# Domain verification tokens served at /.well-known/{name} (config trypost.well_known).diff --git a/AGENTS.md b/AGENTS.mdindex 583b8cfff..aab9dcb12 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -276,14 +276,26 @@ Everything the app keeps in the browser for a user lives in one key per user, `t- Add a new item to the typed `UserStorage` (every workspace) or `WorkspaceStorage` (one workspace) interface in `types/browser-storage.ts` (named `area.thing`, like lang keys; `BrowserStorage` there is the whole stored value) and use it through `useUserStorage(key, default)` or `useWorkspaceStorage(key, default)` (`composables/useBrowserStorage.ts`): a writable ref read once per tab and shared by every component that uses the item, saved on set, following the user's other tabs, and following the page's current user and workspace (a component that stays mounted while the workspace switches, like the layout's command palette, moves to the new one). Code outside a component's setup (a cleanup on logout) or that validates its item itself (the composer draft) uses `readUserItem` / `writeUserItem` / `readWorkspaceItem` / `writeWorkspaceItem` from the lib; writing `undefined` removes an item. A read returns `unknown`: the browser may hold anything, so its reader checks the shape (the composables fall back to the default, the draft goes through `isSnapshot`).- The store does the safe read and write: a missing, unreadable or other-version key (`BROWSER_STORAGE_VERSION`) reads as empty, a block that is not an object reads as empty, a browser without storage works on the defaults, and every write reads the key again first so two tabs never write back a stale copy.- The one exception is `trypost.media-source-popup`: not storage but a message the Canva / Google picker popup writes and removes at once, heard through the `storage` event on that key.-- Browser tests read and seed it through `browserStorageItem($page, $user, $item, $workspaceId = null)` and `setBrowserStorageItem(...)` in `tests/Pest.php`, never the raw key. The earlier keys (#461) are moved in once by `lib/legacyBrowserStorage.ts` (owner decision November 2026): before the first read of the storage on a page with a current workspace (`useBrowserStorage.ts` and the composer draft call it, so the values a page shows right after sign-in are already moved), it copies the signed-in user's earlier values into their storage (a value already there wins) and removes those keys. Each earlier key is named exactly in a typed table (the user's own, the networks that had columns, the user's workspaces' drafts), never matched by prefix, so no other key is touched; another user's earlier keys stay until they sign in on this browser. Remove that file a release or two after it ships; never read an earlier key anywhere else.+- Browser tests read and seed it through `browserStorageItem($page, $user, $item, $workspaceId = null)` and `setBrowserStorageItem(...)` in `tests/Pest.php`, never the raw key: `browserStorage()` reads the whole value, `localStorageKeys()` lists the keys, `setRawBrowserStorage()` writes a value the app must read past (not JSON, another version), `announceBrowserStorageFromAnotherTab()` plays a change made in another tab, and `refuseBrowserStorage()` turns storage off. The earlier keys (#461) are moved in once by `lib/legacyBrowserStorage.ts` (owner decision November 2026): before the first read of the storage on a page with a current workspace (`useBrowserStorage.ts` and the composer draft call it, so the values a page shows right after sign-in are already moved), it copies the signed-in user's earlier values into their storage (a value already there wins) and removes those keys. Each earlier key is named exactly in a typed table (the user's own, the networks that had columns, the user's workspaces' drafts), never matched by prefix, so no other key is touched; another user's earlier keys stay until they sign in on this browser. Remove that file a release or two after it ships; never read an earlier key anywhere else.++## In-app tours++A tour walks the user through a page the first time they see it, one step per control (owner decision November 2026). Use it to point at something new or easy to miss; never to explain a page that explains itself.++- **One definition, three mirrors.** `TOURS` in `resources/js/lib/tours.ts` lists every tour and its steps in order; `App\Enums\Tour\Tour` mirrors the names, and each step's copy is `tours.<tour>.steps.<step>.title` and `.description` in `lang/<locale>/tours.php`, in all 16 locales. `tests/Unit/ToursTest.php` fails when the three drift. Tour names read like lang keys (`publish.views`); their components live in `components/tours` and are named after the tour (`McpPromptTour.vue`).+- **A step wraps its control**: `<TourStep tour="publish.views" step="views">` around it, wherever it is rendered; the step type only accepts that tour's steps. The page goes dark around the control and the step opens next to it, above the backdrop. The backdrop and the card are one for every tour (`TourOverlay`, mounted in `AppSidebarLayout`; a `TourStep` only publishes its step and control), and the card is anchored to the backdrop's cut-out, so moving to the next step slides both to the next control together. One step says "Got it"; several show "2 of 3", Skip tour, Back and Next / Done, and the arrow keys move between the steps without ever ending the tour (on the last step the forward arrow does nothing; only Done closes it). Using the highlighted control moves the tour on (it completes a one-step tour), and the control still works. A step whose control is not on the page is left out, and a `disabled` step (a page where its copy does not fit, like the Instagram grid's switch) never opens. An optional `tag` (translated text) with `tag-color` is drawn like a label; `align` places the card along the control (`end` by default, `start` for a control on the left). `insights.filters` (period, channels, labels) is the reference multi-step tour.+- **When it opens:** on its first step on the page, once per user in a browser, one tour at a time (the next one waiting on the page opens when it closes), never on a phone (below `sm`; narrowing the window to a phone's width hides the open tour without a record, and widening it again opens it at the same step), and never over something already open: it waits while the composer, any dialog, alert dialog or sheet of `components/ui`, or the "How did you find us?" survey is on screen, and opens once the page is free. The dialogs report to the tours through `composables/tours/useTourWaitsForDialogs.ts` (`trackDialogForTours()` in each dialog's content); it lives with the tours although `components/ui` calls it, since only the tours read it (owner decision November 2026). A tour put away without ending (a visit that remounts the page, like picking a period on Insights; a dialog opened over it, like the command palette; a window narrowed to a phone's width) opens again at the step it was on, kept per user and tour while the app stays open. Closing it (Got it, Done, Skip tour or Escape), here or in another tab, ends it; a click elsewhere on the page does nothing (owner decision November 2026); leaving the page midway does not, so it opens again. Everyone sees it once, new and existing users alike. The state lives in `composables/tours/useTour.ts`.+- **Where it is kept:** the browser storage item `tours` (see "Browser storage"; the one item not named `area.thing`, owner decision November 2026: it holds every tour, keyed by tour name), one entry per tour, `{ "status": "completed" | "skipped", "step": <reached, from 1> }`, read and written through `useTourProgress()`. Never a database column.+- **Tracking:** `POST app.tours.store` sends `tour.completed` or `tour.skipped` with `tour`, `step`, `steps` and `workspace_id` (`TourController`, queued on `posthog`).+- **The MCP card is the `mcp.prompt` tour**: it records its "Not now" in `tours`, keeps its own tracking, and waits while a `TourStep` tour is open (`useTourOnScreen()`).+- **`TOURS_ENABLED`** (on by default) turns `TourStep` tours off. Browser tests run with them off (`tests/Pest.php`) so a tour never covers the page they drive; a tour's own test turns them on (`config(['trypost.tours.enabled' => true])`). Tour browser tests live in `tests/Browser/Tours`.## Inviting a user to connect an AI (MCP)-There is no MCP step in Welcome (owner decision November 2026): it was friction before the user ever saw the app, and phones could rarely finish it. Processing always opens the schedule. Instead, `components/mcp/McpPromptCard.vue` (mounted in `AppSidebarLayout`) invites the user from inside the app:+There is no MCP step in Welcome (owner decision November 2026): it was friction before the user ever saw the app, and phones could rarely finish it. Processing always opens the schedule. Instead, `components/tours/McpPromptTour.vue` (mounted in `AppSidebarLayout`) invites the user from inside the app:- **Shown** while the shared `mcpPrompt` prop is set (`HandleInertiaRequests::mcpPrompt()`, with the MCP URL the steps show: a current workspace whose account has app access, or self-hosted, and no AI of the user connected to that workspace (`HasConnectedMcpClient`, the rule the MCP settings list follows); the connection is cached five minutes per user and workspace, while app access is read on every page, so the card and the referral survey show on the first page after an account gets app access), on `sm` and up, never on the MCP settings page, and never while the "How did you find us?" survey shows (the survey goes first).-- **Closing it** (the X, labeled "Not now") is kept in the browser storage (`mcp.promptDismissed`, see "Browser storage"): no database column. Another browser shows it once more. Connecting an AI hides it everywhere, because that comes from the server.+- **Closing it** (the X, labeled "Not now") is kept in the browser storage as the `mcp.prompt` entry of `tours` (`useTourProgress('mcp.prompt')`, see "Browser storage"): no database column. Another browser shows it once more. Connecting an AI hides it everywhere, because that comes from the server.- **Browser tests** see the card on almost every page (a test user has app access and no AI). A test whose page should not carry it calls `connectAiTo($user)` (`tests/Pest.php`), which connects an AI to the user's current workspace; never hide it through the browser storage.- **The card** shows the best-known apps as overlapping avatars (ChatGPT first, on top), and two buttons in the brand colors of Claude and ChatGPT; the close button is the way out. Each opens that app's connect steps (`McpConnectDialog`) on the page the user is on. While the card or its steps are on screen, the card asks `app.mcp.prompt.show` every two seconds, so an AI connected from anywhere (the card, the MCP settings, another tab) hides it; only `connected: true` hides it with confetti (as the MCP settings do) and forgets the cache, never `mcpPrompt` turning null, which losing access or switching workspace also does.- **Tracking:** each answer posts to `app.mcp.prompt.store`, which dispatches `mcp.prompt_clicked` (with the `client` picked: `claude`, `chatgpt` or `other`) or `mcp.prompt_dismissed` (`App\Enums\Mcp\PromptAnswer`). The connection itself is `mcp.connected` (`TrackMcpConnection`), whatever led to it.@@ -1274,6 +1286,7 @@ Browser tests live in `tests/Browser` and run on `pestphp/pest-plugin-browser` d- `waitForCount($page, '@composer-media-item', 2)`: that many elements match (`===`, or pass `'>='` / `'>'`).- `waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog')`: whichever happens first, so the assertion after it fails at once instead of waiting out the timeout.- `waitForPath($page, $path)`: the page is at that path.+ - Beside the waits: `rememberElement($page, '@id', 'name')` keeps an element so a later wait can check it is the same one (`element === window.__remembered.name`), `elementsMap($page, '@list [data-testid]', $expression)` reads a value from every matching element, `pointerDownOn($page, '@id')` presses outside an open modal layer, `clickWithoutPointer($page, '@id')` clicks an element such a layer keeps out of the pointer's reach, and `letPageRun($page, $milliseconds)` lets the page run to show that something stays as it is.- `waitForCondition($page, $js)`: only for what is not about an element (`location.search`, a `window.__` spy).- Each wait gives up after 30 seconds; a slower one (an import that polls the server) passes `seconds:` to `waitFor`, `waitForGone`, `waitForState` or `waitForCondition`.- Never write `document.querySelector(...)` inside a wait, and never define a per-file `waitFor*` helper. Pest's `Webpage` is `final readonly` and not macroable, which is why these are global functions. A helper with a domain name (`waitForComposerReady`) may wrap one condition, built on the shared helpers, never a polling loop of its own. If a wait needs something the helpers cannot express, add a helper to `tests/Pest.php` instead of inlining it.diff --git a/app/Enums/PostHog/TourEvent.php b/app/Enums/PostHog/TourEvent.phpnew file mode 100644index 000000000..8750c7d21--- /dev/null+++ b/app/Enums/PostHog/TourEvent.php@@ -0,0 +1,11 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum TourEvent: string+{+ case Completed = 'tour.completed';+ case Skipped = 'tour.skipped';+}diff --git a/app/Enums/Tour/Outcome.php b/app/Enums/Tour/Outcome.phpnew file mode 100644index 000000000..68718b4f1--- /dev/null+++ b/app/Enums/Tour/Outcome.php@@ -0,0 +1,24 @@+<?php++declare(strict_types=1);++namespace App\Enums\Tour;++use App\Enums\PostHog\TourEvent;++/**+ * How a tour ended: the user reached its last step, or closed it before.+ */+enum Outcome: string+{+ case Completed = 'completed';+ case Skipped = 'skipped';++ public function event(): TourEvent+ {+ return match ($this) {+ self::Completed => TourEvent::Completed,+ self::Skipped => TourEvent::Skipped,+ };+ }+}diff --git a/app/Enums/Tour/Tour.php b/app/Enums/Tour/Tour.phpnew file mode 100644index 000000000..36cb9a976--- /dev/null+++ b/app/Enums/Tour/Tour.php@@ -0,0 +1,16 @@+<?php++declare(strict_types=1);++namespace App\Enums\Tour;++/**+ * The in-app tours, named by their keys in `lang/<locale>/tours.php`; mirrors+ * `TOURS` in `resources/js/lib/tours.ts`.+ */+enum Tour: string+{+ case PublishViews = 'publish.views';+ case InsightsFilters = 'insights.filters';+ case McpPrompt = 'mcp.prompt';+}diff --git a/app/Http/Controllers/App/TourController.php b/app/Http/Controllers/App/TourController.phpnew file mode 100644index 000000000..77d0121f2--- /dev/null+++ b/app/Http/Controllers/App/TourController.php@@ -0,0 +1,43 @@+<?php++declare(strict_types=1);++namespace App\Http\Controllers\App;++use App\Enums\Tour\Outcome;+use App\Http\Requests\App\Tour\StoreTourRequest;+use App\Jobs\PostHog\CaptureAccountEvent;+use App\Services\PostHogService;+use Illuminate\Http\Response;++class TourController extends Controller+{+ /**+ * Records how a tour ended and at which step. The browser keeps which+ * tours the user went through; this only tracks it.+ */+ public function store(StoreTourRequest $request): Response+ {+ $user = $request->user();+ $workspace = $user->currentWorkspace;+ $outcome = $request->enum('outcome', Outcome::class);+ $properties = [+ 'tour' => $request->validated('tour'),+ 'step' => (int) $request->validated('step'),+ 'steps' => (int) $request->validated('steps'),+ 'workspace_id' => $workspace->id,+ ];++ rescue(function () use ($user, $workspace, $outcome, $properties): void {+ CaptureAccountEvent::dispatchIf(+ PostHogService::isEnabled(),+ (string) $user->id,+ (string) $workspace->account_id,+ $outcome->event(),+ $properties,+ );+ });++ return response()->noContent();+ }+}diff --git a/app/Http/Middleware/App/HandleInertiaRequests.php b/app/Http/Middleware/App/HandleInertiaRequests.phpindex 2874b8533..10df1e5fd 100644--- a/app/Http/Middleware/App/HandleInertiaRequests.php+++ b/app/Http/Middleware/App/HandleInertiaRequests.php@@ -112,6 +112,7 @@ class HandleInertiaRequests extends Middleware'aiEnabled' => fn (): bool => filled(config('ai.providers.'.config('ai.default').'.key')),'googleAuthEnabled' => fn (): bool => SocialAuthProvider::Google->isEnabled(),'githubAuthEnabled' => fn (): bool => SocialAuthProvider::GitHub->isEnabled(),+ 'toursEnabled' => fn (): bool => (bool) config('trypost.tours.enabled'),...(filled($user) ? ['mediaSources' => fn (): array => ['menu' => MediaSource::menu()],'mediaUploadLimits' => fn (): array => [diff --git a/app/Http/Requests/App/Tour/StoreTourRequest.php b/app/Http/Requests/App/Tour/StoreTourRequest.phpnew file mode 100644index 000000000..cfcc1862c--- /dev/null+++ b/app/Http/Requests/App/Tour/StoreTourRequest.php@@ -0,0 +1,31 @@+<?php++declare(strict_types=1);++namespace App\Http\Requests\App\Tour;++use App\Enums\Tour\Outcome;+use App\Enums\Tour\Tour;+use Illuminate\Foundation\Http\FormRequest;+use Illuminate\Validation\Rule;++class StoreTourRequest extends FormRequest+{+ public function authorize(): bool+ {+ return true;+ }++ /**+ * @return array<string, mixed>+ */+ public function rules(): array+ {+ return [+ 'tour' => ['required', Rule::enum(Tour::class)],+ 'outcome' => ['required', Rule::enum(Outcome::class)],+ 'steps' => ['required', 'integer', 'min:1'],+ 'step' => ['required', 'integer', 'min:1', 'lte:steps'],+ ];+ }+}diff --git a/config/trypost.php b/config/trypost.phpindex c75ef05ce..e308da1ff 100644--- a/config/trypost.php+++ b/config/trypost.php@@ -40,6 +40,21 @@ return ['path' => resource_path('changelog'),],+ /*+ |--------------------------------------------------------------------------+ | In-app tours+ |--------------------------------------------------------------------------+ |+ | The tours that walk a user through a page the first time they see it+ | (`TourStep`). On by default; browser tests turn them off so a tour+ | never covers the page they drive.+ |+ */++ 'tours' => [+ 'enabled' => (bool) env('TOURS_ENABLED', true),+ ],+/*|--------------------------------------------------------------------------| Legal pagesdiff --git a/lang/ar/mcp.php b/lang/ar/mcp.phpindex a0fe2988f..e76ebaa84 100644--- a/lang/ar/mcp.php+++ b/lang/ar/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'بانتظار اتصال الذكاء الاصطناعي…',],- 'prompt' => [- 'title' => 'لم يتم ربط أي ذكاء اصطناعي بعد',- 'body' => 'اربط Claude أو ChatGPT لإنشاء منشوراتك وجدولتها وتحليلها بمجرد طلب ذلك.',- 'not_now' => 'ليس الآن',- ],-];diff --git a/lang/ar/tours.php b/lang/ar/tours.phpnew file mode 100644index 000000000..443cf8b27--- /dev/null+++ b/lang/ar/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'جديد',+ ],+ 'actions' => [+ 'got_it' => 'فهمت',+ 'back' => 'رجوع',+ 'next' => 'التالي',+ 'done' => 'تم',+ 'skip' => 'تخطي الجولة',+ ],+ 'progress' => ':current من :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'غيّر طريقة العرض',+ 'description' => 'خطط لمنشوراتك بالشكل الذي يناسبك أكثر.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'صفِّ حسب الفترة',+ 'description' => 'صفِّ بياناتك حسب الأيام الأخيرة أو تواريخ محددة.',+ ],+ 'channels' => [+ 'title' => 'صفِّ حسب القناة',+ 'description' => 'اعرض أرقام قناة واحدة أو قارن بين عدة قنوات.',+ ],+ 'labels' => [+ 'title' => 'صفِّ حسب التسمية',+ 'description' => 'تابع حملة أو سلسلة من خلال تسمياتها.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'لم يتم ربط أي ذكاء اصطناعي بعد',+ 'description' => 'اربط Claude أو ChatGPT لإنشاء منشوراتك وجدولتها وتحليلها بمجرد طلب ذلك.',+ 'not_now' => 'ليس الآن',+ ],+ ],+ ],+ ],+];diff --git a/lang/de/mcp.php b/lang/de/mcp.phpindex cec49e662..58c5effb7 100644--- a/lang/de/mcp.php+++ b/lang/de/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Warte auf die Verbindung deiner KI…',],- 'prompt' => [- 'title' => 'Du hast noch keine KI verbunden',- 'body' => 'Verbinde Claude oder ChatGPT, um Posts einfach per Nachricht zu erstellen, zu planen und zu analysieren.',- 'not_now' => 'Nicht jetzt',- ],-];diff --git a/lang/de/tours.php b/lang/de/tours.phpnew file mode 100644index 000000000..f034763cc--- /dev/null+++ b/lang/de/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Neu',+ ],+ 'actions' => [+ 'got_it' => 'Verstanden',+ 'back' => 'Zurück',+ 'next' => 'Weiter',+ 'done' => 'Fertig',+ 'skip' => 'Überspringen',+ ],+ 'progress' => ':current von :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Ansicht wechseln',+ 'description' => 'Plane deine Beiträge in dem Format, das für dich am besten passt.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Nach Zeitraum filtern',+ 'description' => 'Filtere deine Zahlen nach den letzten Tagen oder einem eigenen Zeitraum.',+ ],+ 'channels' => [+ 'title' => 'Nach Kanal filtern',+ 'description' => 'Sieh dir die Zahlen eines Kanals an oder vergleiche mehrere.',+ ],+ 'labels' => [+ 'title' => 'Nach Label filtern',+ 'description' => 'Verfolge eine Kampagne oder Serie über ihre Labels.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Du hast noch keine KI verbunden',+ 'description' => 'Verbinde Claude oder ChatGPT, um Posts einfach per Nachricht zu erstellen, zu planen und zu analysieren.',+ 'not_now' => 'Nicht jetzt',+ ],+ ],+ ],+ ],+];diff --git a/lang/el/mcp.php b/lang/el/mcp.phpindex aa18b01d9..caef48a52 100644--- a/lang/el/mcp.php+++ b/lang/el/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Αναμονή για σύνδεση του AI σας…',],- 'prompt' => [- 'title' => 'Δεν έχετε συνδέσει ακόμα AI',- 'body' => 'Συνδέστε το Claude ή το ChatGPT για να φτιάχνετε, να προγραμματίζετε και να αναλύετε posts απλώς ζητώντας το.',- 'not_now' => 'Όχι τώρα',- ],-];diff --git a/lang/el/tours.php b/lang/el/tours.phpnew file mode 100644index 000000000..416b56b76--- /dev/null+++ b/lang/el/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Νέο',+ ],+ 'actions' => [+ 'got_it' => 'Εντάξει',+ 'back' => 'Πίσω',+ 'next' => 'Επόμενο',+ 'done' => 'Τέλος',+ 'skip' => 'Παράλειψη',+ ],+ 'progress' => ':current από :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Άλλαξε προβολή',+ 'description' => 'Σχεδίασε τις αναρτήσεις σου στη μορφή που σου ταιριάζει καλύτερα.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Φίλτραρε ανά περίοδο',+ 'description' => 'Φίλτραρε τα δεδομένα σου ανά πρόσφατες ή συγκεκριμένες ημερομηνίες.',+ ],+ 'channels' => [+ 'title' => 'Φίλτραρε ανά κανάλι',+ 'description' => 'Δες τα νούμερα ενός καναλιού ή σύγκρινε πολλά.',+ ],+ 'labels' => [+ 'title' => 'Φίλτραρε ανά ετικέτα',+ 'description' => 'Παρακολούθησε μια καμπάνια ή μια σειρά μέσα από τις ετικέτες της.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Δεν έχετε συνδέσει ακόμα AI',+ 'description' => 'Συνδέστε το Claude ή το ChatGPT για να φτιάχνετε, να προγραμματίζετε και να αναλύετε posts απλώς ζητώντας το.',+ 'not_now' => 'Όχι τώρα',+ ],+ ],+ ],+ ],+];diff --git a/lang/en/mcp.php b/lang/en/mcp.phpindex 19d34eb29..fd7e3265c 100644--- a/lang/en/mcp.php+++ b/lang/en/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Waiting for your AI to connect…',],- 'prompt' => [- 'title' => 'You haven\'t connected an AI yet',- 'body' => 'Connect Claude or ChatGPT to create, schedule and analyze your posts just by asking.',- 'not_now' => 'Not now',- ],-];diff --git a/lang/en/tours.php b/lang/en/tours.phpnew file mode 100644index 000000000..fdcc48942--- /dev/null+++ b/lang/en/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'New',+ ],+ 'actions' => [+ 'got_it' => 'Got it',+ 'back' => 'Back',+ 'next' => 'Next',+ 'done' => 'Done',+ 'skip' => 'Skip tour',+ ],+ 'progress' => ':current of :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Switch views',+ 'description' => 'Plan your posts in the layout that works best for you.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Filter by period',+ 'description' => 'Filter your data by recent days or by specific dates.',+ ],+ 'channels' => [+ 'title' => 'Filter by channel',+ 'description' => 'See one channel\'s numbers or compare several.',+ ],+ 'labels' => [+ 'title' => 'Filter by label',+ 'description' => 'Follow a campaign or a series through its labels.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'You haven\'t connected an AI yet',+ 'description' => 'Connect Claude or ChatGPT to create, schedule and analyze your posts just by asking.',+ 'not_now' => 'Not now',+ ],+ ],+ ],+ ],+];diff --git a/lang/es/mcp.php b/lang/es/mcp.phpindex 64ef3d115..7952d7b6b 100644--- a/lang/es/mcp.php+++ b/lang/es/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Esperando a que tu IA se conecte…',],- 'prompt' => [- 'title' => 'Aún no has conectado ninguna IA',- 'body' => 'Conecta Claude o ChatGPT para crear, programar y analizar tus posts con solo pedirlo.',- 'not_now' => 'Ahora no',- ],-];diff --git a/lang/es/tours.php b/lang/es/tours.phpnew file mode 100644index 000000000..f7b8dc48a--- /dev/null+++ b/lang/es/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Nuevo',+ ],+ 'actions' => [+ 'got_it' => 'Entendido',+ 'back' => 'Atrás',+ 'next' => 'Siguiente',+ 'done' => 'Listo',+ 'skip' => 'Saltar tour',+ ],+ 'progress' => ':current de :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Cambia la vista',+ 'description' => 'Planifica tus publicaciones en el formato que mejor te funcione.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Filtra por periodo',+ 'description' => 'Filtra tus datos por los últimos días o por fechas concretas.',+ ],+ 'channels' => [+ 'title' => 'Filtra por canal',+ 'description' => 'Mira los números de un canal o compara varios.',+ ],+ 'labels' => [+ 'title' => 'Filtra por etiqueta',+ 'description' => 'Sigue una campaña o una serie por sus etiquetas.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Aún no has conectado ninguna IA',+ 'description' => 'Conecta Claude o ChatGPT para crear, programar y analizar tus posts con solo pedirlo.',+ 'not_now' => 'Ahora no',+ ],+ ],+ ],+ ],+];diff --git a/lang/fr/mcp.php b/lang/fr/mcp.phpindex 83e227778..3ab1de036 100644--- a/lang/fr/mcp.php+++ b/lang/fr/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'En attente de la connexion de votre IA…',],- 'prompt' => [- 'title' => 'Vous n\'avez pas encore connecté d\'IA',- 'body' => 'Connectez Claude ou ChatGPT pour créer, planifier et analyser vos posts simplement en le demandant.',- 'not_now' => 'Plus tard',- ],-];diff --git a/lang/fr/tours.php b/lang/fr/tours.phpnew file mode 100644index 000000000..b89ccbb4c--- /dev/null+++ b/lang/fr/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Nouveau',+ ],+ 'actions' => [+ 'got_it' => 'Compris',+ 'back' => 'Retour',+ 'next' => 'Suivant',+ 'done' => 'Terminé',+ 'skip' => 'Passer',+ ],+ 'progress' => ':current sur :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Changez de vue',+ 'description' => 'Planifiez vos publications dans le format qui vous convient le mieux.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Filtrez par période',+ 'description' => 'Filtrez vos données sur les derniers jours ou sur des dates précises.',+ ],+ 'channels' => [+ 'title' => 'Filtrez par canal',+ 'description' => 'Affichez les chiffres d\'un canal ou comparez-en plusieurs.',+ ],+ 'labels' => [+ 'title' => 'Filtrez par étiquette',+ 'description' => 'Suivez une campagne ou une série grâce à ses étiquettes.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Vous n\'avez pas encore connecté d\'IA',+ 'description' => 'Connectez Claude ou ChatGPT pour créer, planifier et analyser vos posts simplement en le demandant.',+ 'not_now' => 'Plus tard',+ ],+ ],+ ],+ ],+];diff --git a/lang/it/mcp.php b/lang/it/mcp.phpindex c7d090a4b..c800a5882 100644--- a/lang/it/mcp.php+++ b/lang/it/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'In attesa che la tua IA si colleghi…',],- 'prompt' => [- 'title' => 'Non hai ancora collegato un\'IA',- 'body' => 'Collega Claude o ChatGPT per creare, programmare e analizzare i post semplicemente chiedendolo.',- 'not_now' => 'Non ora',- ],-];diff --git a/lang/it/tours.php b/lang/it/tours.phpnew file mode 100644index 000000000..498cba665--- /dev/null+++ b/lang/it/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Novità',+ ],+ 'actions' => [+ 'got_it' => 'Ho capito',+ 'back' => 'Indietro',+ 'next' => 'Avanti',+ 'done' => 'Fatto',+ 'skip' => 'Salta il tour',+ ],+ 'progress' => ':current di :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Cambia vista',+ 'description' => 'Pianifica i tuoi post nel formato che funziona meglio per te.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Filtra per periodo',+ 'description' => 'Filtra i tuoi dati per gli ultimi giorni o per date specifiche.',+ ],+ 'channels' => [+ 'title' => 'Filtra per canale',+ 'description' => 'Guarda i numeri di un canale o confrontane diversi.',+ ],+ 'labels' => [+ 'title' => 'Filtra per etichetta',+ 'description' => 'Segui una campagna o una serie tramite le sue etichette.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Non hai ancora collegato un\'IA',+ 'description' => 'Collega Claude o ChatGPT per creare, programmare e analizzare i post semplicemente chiedendolo.',+ 'not_now' => 'Non ora',+ ],+ ],+ ],+ ],+];diff --git a/lang/ja/mcp.php b/lang/ja/mcp.phpindex e9a19da69..5f9aa0294 100644--- a/lang/ja/mcp.php+++ b/lang/ja/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'AIの接続を待っています…',],- 'prompt' => [- 'title' => 'まだAIを接続していません',- 'body' => 'ClaudeやChatGPTを接続すると、頼むだけで投稿の作成・予約・分析ができます。',- 'not_now' => '今はしない',- ],-];diff --git a/lang/ja/tours.php b/lang/ja/tours.phpnew file mode 100644index 000000000..589e1ec67--- /dev/null+++ b/lang/ja/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => '新機能',+ ],+ 'actions' => [+ 'got_it' => 'OK',+ 'back' => '戻る',+ 'next' => '次へ',+ 'done' => '完了',+ 'skip' => 'ツアーをスキップ',+ ],+ 'progress' => ':current / :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => '表示を切り替える',+ 'description' => '自分に合った表示で投稿を計画できます。',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => '期間で絞り込む',+ 'description' => '直近の日数や特定の日付でデータを絞り込めます。',+ ],+ 'channels' => [+ 'title' => 'チャンネルで絞り込む',+ 'description' => '1つのチャンネルの数値を見たり、複数を比較したりできます。',+ ],+ 'labels' => [+ 'title' => 'ラベルで絞り込む',+ 'description' => 'ラベルでキャンペーンやシリーズの成果を追えます。',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'まだAIを接続していません',+ 'description' => 'ClaudeやChatGPTを接続すると、頼むだけで投稿の作成・予約・分析ができます。',+ 'not_now' => '今はしない',+ ],+ ],+ ],+ ],+];diff --git a/lang/ko/mcp.php b/lang/ko/mcp.phpindex 91435d1ae..26390a2f3 100644--- a/lang/ko/mcp.php+++ b/lang/ko/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'AI 연결을 기다리는 중…',],- 'prompt' => [- 'title' => '아직 연결한 AI가 없습니다',- 'body' => 'Claude나 ChatGPT를 연결하면 요청만으로 게시물을 만들고, 예약하고, 분석할 수 있습니다.',- 'not_now' => '나중에',- ],-];diff --git a/lang/ko/tours.php b/lang/ko/tours.phpnew file mode 100644index 000000000..00c010864--- /dev/null+++ b/lang/ko/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => '신규',+ ],+ 'actions' => [+ 'got_it' => '확인',+ 'back' => '뒤로',+ 'next' => '다음',+ 'done' => '완료',+ 'skip' => '투어 건너뛰기',+ ],+ 'progress' => ':current / :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => '보기 전환',+ 'description' => '가장 편한 방식으로 게시물을 계획하세요.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => '기간으로 필터링하세요',+ 'description' => '최근 며칠 또는 특정 날짜로 데이터를 필터링하세요.',+ ],+ 'channels' => [+ 'title' => '채널로 필터링하세요',+ 'description' => '한 채널의 수치를 보거나 여러 채널을 비교하세요.',+ ],+ 'labels' => [+ 'title' => '라벨로 필터링하세요',+ 'description' => '라벨로 캠페인이나 시리즈의 성과를 확인하세요.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => '아직 연결한 AI가 없습니다',+ 'description' => 'Claude나 ChatGPT를 연결하면 요청만으로 게시물을 만들고, 예약하고, 분석할 수 있습니다.',+ 'not_now' => '나중에',+ ],+ ],+ ],+ ],+];diff --git a/lang/nl/mcp.php b/lang/nl/mcp.phpindex b12fba505..b590ae265 100644--- a/lang/nl/mcp.php+++ b/lang/nl/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Wachten tot je AI verbindt…',],- 'prompt' => [- 'title' => 'Je hebt nog geen AI gekoppeld',- 'body' => 'Koppel Claude of ChatGPT om posts te maken, te plannen en te analyseren door het gewoon te vragen.',- 'not_now' => 'Niet nu',- ],-];diff --git a/lang/nl/tours.php b/lang/nl/tours.phpnew file mode 100644index 000000000..c5096118b--- /dev/null+++ b/lang/nl/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Nieuw',+ ],+ 'actions' => [+ 'got_it' => 'Begrepen',+ 'back' => 'Terug',+ 'next' => 'Volgende',+ 'done' => 'Klaar',+ 'skip' => 'Overslaan',+ ],+ 'progress' => ':current van :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Wissel van weergave',+ 'description' => 'Plan je posts in de weergave die voor jou het best werkt.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Filter op periode',+ 'description' => 'Filter je gegevens op de afgelopen dagen of op specifieke datums.',+ ],+ 'channels' => [+ 'title' => 'Filter op kanaal',+ 'description' => 'Bekijk de cijfers van één kanaal of vergelijk er meerdere.',+ ],+ 'labels' => [+ 'title' => 'Filter op label',+ 'description' => 'Volg een campagne of reeks via de labels.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Je hebt nog geen AI gekoppeld',+ 'description' => 'Koppel Claude of ChatGPT om posts te maken, te plannen en te analyseren door het gewoon te vragen.',+ 'not_now' => 'Niet nu',+ ],+ ],+ ],+ ],+];diff --git a/lang/pl/mcp.php b/lang/pl/mcp.phpindex 84152e9c7..3b04454cf 100644--- a/lang/pl/mcp.php+++ b/lang/pl/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Czekamy na połączenie Twojej AI…',],- 'prompt' => [- 'title' => 'Nie masz jeszcze połączonej AI',- 'body' => 'Połącz Claude lub ChatGPT, aby tworzyć, planować i analizować posty, po prostu o to prosząc.',- 'not_now' => 'Nie teraz',- ],-];diff --git a/lang/pl/tours.php b/lang/pl/tours.phpnew file mode 100644index 000000000..0c9d904cc--- /dev/null+++ b/lang/pl/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Nowość',+ ],+ 'actions' => [+ 'got_it' => 'Rozumiem',+ 'back' => 'Wstecz',+ 'next' => 'Dalej',+ 'done' => 'Gotowe',+ 'skip' => 'Pomiń',+ ],+ 'progress' => ':current z :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Zmień widok',+ 'description' => 'Planuj posty w układzie, który najlepiej ci odpowiada.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Filtruj według okresu',+ 'description' => 'Filtruj dane według ostatnich dni lub konkretnych dat.',+ ],+ 'channels' => [+ 'title' => 'Filtruj według kanału',+ 'description' => 'Zobacz liczby jednego kanału lub porównaj kilka.',+ ],+ 'labels' => [+ 'title' => 'Filtruj według etykiety',+ 'description' => 'Śledź kampanię lub serię po jej etykietach.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Nie masz jeszcze połączonej AI',+ 'description' => 'Połącz Claude lub ChatGPT, aby tworzyć, planować i analizować posty, po prostu o to prosząc.',+ 'not_now' => 'Nie teraz',+ ],+ ],+ ],+ ],+];diff --git a/lang/pt-BR/mcp.php b/lang/pt-BR/mcp.phpindex a333033ef..b4a2d6a39 100644--- a/lang/pt-BR/mcp.php+++ b/lang/pt-BR/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Aguardando sua IA conectar…',],- 'prompt' => [- 'title' => 'Você ainda não conectou uma IA',- 'body' => 'Conecte o Claude ou o ChatGPT para criar, agendar e analisar seus posts só pedindo.',- 'not_now' => 'Agora não',- ],-];diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.phpindex e45c5f7bb..f13854e06 100644--- a/lang/pt-BR/posts.php+++ b/lang/pt-BR/posts.php@@ -431,7 +431,7 @@ return ['topic' => 'Tópico','topic_placeholder' => 'Digite o tópico','topic_invalid' => 'O tópico deve ter de 1 a 50 caracteres, sem . ou &.',- 'ghost_post_attachments' => 'Posts fantasma não aceitam anexos',+ 'ghost_post_attachments' => 'Posts temporários não aceitam anexos',],'x' => ['poll' => [@@ -857,7 +857,7 @@ return ['description' => 'Post de texto com mídia opcional',],'threads_ghost_post' => [- 'label' => 'Post fantasma',+ 'label' => 'Post temporário','description' => 'Post só de texto, arquivado após 24 horas',],'pinterest_pin' => [diff --git a/lang/pt-BR/tours.php b/lang/pt-BR/tours.phpnew file mode 100644index 000000000..3f48a7eb1--- /dev/null+++ b/lang/pt-BR/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Novo',+ ],+ 'actions' => [+ 'got_it' => 'Entendi',+ 'back' => 'Voltar',+ 'next' => 'Próximo',+ 'done' => 'Concluir',+ 'skip' => 'Pular tour',+ ],+ 'progress' => ':current de :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Mude a visualização',+ 'description' => 'Planeje seus posts no formato que funciona melhor para você.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Filtre por período',+ 'description' => 'Filtre seus dados pelos últimos dias ou por datas específicas.',+ ],+ 'channels' => [+ 'title' => 'Filtre por canal',+ 'description' => 'Veja os números de um canal ou compare vários.',+ ],+ 'labels' => [+ 'title' => 'Filtre por etiqueta',+ 'description' => 'Acompanhe uma campanha ou série pelas etiquetas.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Você ainda não conectou uma IA',+ 'description' => 'Conecte o Claude ou o ChatGPT para criar, agendar e analisar seus posts só pedindo.',+ 'not_now' => 'Agora não',+ ],+ ],+ ],+ ],+];diff --git a/lang/ru/mcp.php b/lang/ru/mcp.phpindex 326189929..abb040181 100644--- a/lang/ru/mcp.php+++ b/lang/ru/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Ждём подключения вашего ИИ…',],- 'prompt' => [- 'title' => 'ИИ ещё не подключён',- 'body' => 'Подключите Claude или ChatGPT, чтобы создавать, планировать и анализировать посты простой просьбой.',- 'not_now' => 'Не сейчас',- ],-];diff --git a/lang/ru/tours.php b/lang/ru/tours.phpnew file mode 100644index 000000000..960178b61--- /dev/null+++ b/lang/ru/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Новое',+ ],+ 'actions' => [+ 'got_it' => 'Понятно',+ 'back' => 'Назад',+ 'next' => 'Далее',+ 'done' => 'Готово',+ 'skip' => 'Пропустить',+ ],+ 'progress' => ':current из :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Смените вид',+ 'description' => 'Планируйте посты в том виде, который удобнее вам.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Фильтруйте по периоду',+ 'description' => 'Смотрите данные за последние дни или за нужные даты.',+ ],+ 'channels' => [+ 'title' => 'Фильтруйте по каналу',+ 'description' => 'Смотрите цифры одного канала или сравнивайте несколько.',+ ],+ 'labels' => [+ 'title' => 'Фильтруйте по метке',+ 'description' => 'Следите за кампанией или серией по её меткам.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'ИИ ещё не подключён',+ 'description' => 'Подключите Claude или ChatGPT, чтобы создавать, планировать и анализировать посты простой просьбой.',+ 'not_now' => 'Не сейчас',+ ],+ ],+ ],+ ],+];diff --git a/lang/tr/mcp.php b/lang/tr/mcp.phpindex 2952d5310..772fd27d1 100644--- a/lang/tr/mcp.php+++ b/lang/tr/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Yapay zekânın bağlanması bekleniyor…',],- 'prompt' => [- 'title' => 'Henüz bir yapay zekâ bağlamadın',- 'body' => 'Gönderilerini sadece isteyerek oluşturmak, planlamak ve analiz etmek için Claude veya ChatGPT\'yi bağla.',- 'not_now' => 'Şimdi değil',- ],-];diff --git a/lang/tr/tours.php b/lang/tr/tours.phpnew file mode 100644index 000000000..32099a4e8--- /dev/null+++ b/lang/tr/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Yeni',+ ],+ 'actions' => [+ 'got_it' => 'Anladım',+ 'back' => 'Geri',+ 'next' => 'İleri',+ 'done' => 'Bitti',+ 'skip' => 'Turu atla',+ ],+ 'progress' => ':current / :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Görünümü değiştir',+ 'description' => 'Gönderilerini sana en uygun düzende planla.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Döneme göre filtrele',+ 'description' => 'Verilerini son günlere veya belirli tarihlere göre filtrele.',+ ],+ 'channels' => [+ 'title' => 'Kanala göre filtrele',+ 'description' => 'Bir kanalın rakamlarını gör veya birkaçını karşılaştır.',+ ],+ 'labels' => [+ 'title' => 'Etikete göre filtrele',+ 'description' => 'Bir kampanyayı veya seriyi etiketleriyle takip et.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'Henüz bir yapay zekâ bağlamadın',+ 'description' => 'Gönderilerini sadece isteyerek oluşturmak, planlamak ve analiz etmek için Claude veya ChatGPT\'yi bağla.',+ 'not_now' => 'Şimdi değil',+ ],+ ],+ ],+ ],+];diff --git a/lang/uk/mcp.php b/lang/uk/mcp.phpindex 587273cbd..fb90e0e59 100644--- a/lang/uk/mcp.php+++ b/lang/uk/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => 'Чекаємо на підключення вашого ШІ…',],- 'prompt' => [- 'title' => 'ШІ ще не підключено',- 'body' => 'Підключіть Claude або ChatGPT, щоб створювати, планувати й аналізувати дописи, просто попросивши.',- 'not_now' => 'Не зараз',- ],-];diff --git a/lang/uk/tours.php b/lang/uk/tours.phpnew file mode 100644index 000000000..b2de2146d--- /dev/null+++ b/lang/uk/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => 'Нове',+ ],+ 'actions' => [+ 'got_it' => 'Зрозуміло',+ 'back' => 'Назад',+ 'next' => 'Далі',+ 'done' => 'Готово',+ 'skip' => 'Пропустити',+ ],+ 'progress' => ':current з :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => 'Змініть вигляд',+ 'description' => 'Плануйте дописи в тому вигляді, який зручніший вам.',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => 'Фільтруйте за періодом',+ 'description' => 'Переглядайте дані за останні дні або за потрібні дати.',+ ],+ 'channels' => [+ 'title' => 'Фільтруйте за каналом',+ 'description' => 'Переглядайте цифри одного каналу або порівнюйте кілька.',+ ],+ 'labels' => [+ 'title' => 'Фільтруйте за міткою',+ 'description' => 'Відстежуйте кампанію чи серію за її мітками.',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => 'ШІ ще не підключено',+ 'description' => 'Підключіть Claude або ChatGPT, щоб створювати, планувати й аналізувати дописи, просто попросивши.',+ 'not_now' => 'Не зараз',+ ],+ ],+ ],+ ],+];diff --git a/lang/zh/mcp.php b/lang/zh/mcp.phpindex 1fb67f652..03512ad74 100644--- a/lang/zh/mcp.php+++ b/lang/zh/mcp.php@@ -76,10 +76,4 @@ return [],'waiting' => '正在等待你的 AI 连接…',],- 'prompt' => [- 'title' => '你还没有连接 AI',- 'body' => '连接 Claude 或 ChatGPT,只需开口就能创建、排期和分析帖子。',- 'not_now' => '以后再说',- ],-];diff --git a/lang/zh/tours.php b/lang/zh/tours.phpnew file mode 100644index 000000000..210445b48--- /dev/null+++ b/lang/zh/tours.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++return [+ 'tags' => [+ 'new' => '新功能',+ ],+ 'actions' => [+ 'got_it' => '知道了',+ 'back' => '上一步',+ 'next' => '下一步',+ 'done' => '完成',+ 'skip' => '跳过导览',+ ],+ 'progress' => ':current / :total',+ 'publish' => [+ 'views' => [+ 'steps' => [+ 'views' => [+ 'title' => '切换视图',+ 'description' => '用最适合你的方式规划帖子。',+ ],+ ],+ ],+ ],+ 'insights' => [+ 'filters' => [+ 'steps' => [+ 'range' => [+ 'title' => '按时间段筛选',+ 'description' => '按最近几天或指定日期筛选你的数据。',+ ],+ 'channels' => [+ 'title' => '按频道筛选',+ 'description' => '查看一个频道的数据,或比较多个频道。',+ ],+ 'labels' => [+ 'title' => '按标签筛选',+ 'description' => '通过标签跟踪一次活动或一个系列。',+ ],+ ],+ ],+ ],+ 'mcp' => [+ 'prompt' => [+ 'steps' => [+ 'card' => [+ 'title' => '你还没有连接 AI',+ 'description' => '连接 Claude 或 ChatGPT,只需开口就能创建、排期和分析帖子。',+ 'not_now' => '以后再说',+ ],+ ],+ ],+ ],+];diff --git a/resources/js/components/mcp/McpConnectDialog.vue b/resources/js/components/mcp/McpConnectDialog.vueindex f7f9f81fb..99fdb384a 100644--- a/resources/js/components/mcp/McpConnectDialog.vue+++ b/resources/js/components/mcp/McpConnectDialog.vue@@ -13,7 +13,7 @@ import {DialogTitle,} from '@/components/ui/dialog';import { Spinner } from '@/components/ui/spinner';-import type { McpClient, McpClientId } from '@/lib/mcpClients';+import type { McpClient, McpClientId } from '@/types/mcp';const props = defineProps<{client: McpClient;diff --git a/resources/js/components/posts/ScheduleViewSwitch.vue b/resources/js/components/posts/ScheduleViewSwitch.vueindex 156d0012e..57e91107d 100644--- a/resources/js/components/posts/ScheduleViewSwitch.vue+++ b/resources/js/components/posts/ScheduleViewSwitch.vue@@ -10,6 +10,7 @@ import {} from '@tabler/icons-vue';import { type Component, computed } from 'vue';+import TourStep from '@/components/tours/TourStep.vue';import { Button } from '@/components/ui/button';import {DropdownMenu,@@ -67,6 +68,9 @@ const gridNote = (): string | null => {return 'channels.grid.info';};+/** The channel's Instagram grid is one more view here; the views tour speaks of list, calendar and board only, so it stays closed. */+const hasGrid = computed(() => filled(props.gridHref));+/** The views of the page; the Instagram grid comes first on a channel that has one. */const views = computed((): ScheduleView[] => {const publishViews: ScheduleView[] = [@@ -169,38 +173,45 @@ const viewLinkClass = (key: string): string => {</DropdownMenuItem></DropdownMenuContent></DropdownMenu>- <TooltipProvider v-else :delay-duration="0">- <nav- class="inline-flex h-8 items-center gap-1 rounded-lg border border-border-strong bg-card p-[3px]"- :aria-label="$t('posts.view_switcher')"- >- <Tooltip- v-for="view in views"- :key="view.key"- :disabled="!view.note"+ <TourStep+ v-else+ tour="publish.views"+ step="views"+ :disabled="hasGrid"+ >+ <TooltipProvider :delay-duration="0">+ <nav+ class="inline-flex h-8 items-center gap-1 rounded-lg border border-border-strong bg-card p-[3px]"+ :aria-label="$t('posts.view_switcher')">- <TooltipTrigger as-child>- <Link- :href="view.href"- :aria-current="ariaCurrent(view.key)"- :data-testid="`schedule-view-${view.key}`"- @click="pickView(view.key)"- class="inline-flex h-6 items-center justify-center gap-1 rounded-md border border-transparent px-2 text-sm font-medium transition-control"- :class="viewLinkClass(view.key)"- >- <component :is="view.icon" class="size-4" />- <span class="hidden sm:inline">{{- $t(view.label)- }}</span>- </Link>- </TooltipTrigger>- <TooltipContent- v-if="view.note"- :data-testid="`schedule-view-${view.key}-note`"+ <Tooltip+ v-for="view in views"+ :key="view.key"+ :disabled="!view.note">- {{ $t(view.note) }}- </TooltipContent>- </Tooltip>- </nav>- </TooltipProvider>+ <TooltipTrigger as-child>+ <Link+ :href="view.href"+ :aria-current="ariaCurrent(view.key)"+ :data-testid="`schedule-view-${view.key}`"+ @click="pickView(view.key)"+ class="inline-flex h-6 items-center justify-center gap-1 rounded-md border border-transparent px-2 text-sm font-medium transition-control"+ :class="viewLinkClass(view.key)"+ >+ <component :is="view.icon" class="size-4" />+ <span class="hidden sm:inline">{{+ $t(view.label)+ }}</span>+ </Link>+ </TooltipTrigger>+ <TooltipContent+ v-if="view.note"+ :data-testid="`schedule-view-${view.key}-note`"+ >+ {{ $t(view.note) }}+ </TooltipContent>+ </Tooltip>+ </nav>+ </TooltipProvider>+ </TourStep></template>diff --git a/resources/js/components/mcp/McpPromptCard.vue b/resources/js/components/tours/McpPromptTour.vuesimilarity index 65%rename from resources/js/components/mcp/McpPromptCard.vuerename to resources/js/components/tours/McpPromptTour.vueindex b6cf21856..e7757ffb2 100644--- a/resources/js/components/mcp/McpPromptCard.vue+++ b/resources/js/components/tours/McpPromptTour.vue@@ -6,20 +6,16 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue';import McpConnectDialog from '@/components/mcp/McpConnectDialog.vue';import { Button } from '@/components/ui/button';+import { useTourOnScreen, useTourProgress } from '@/composables/tours/useTour';import { useBelowBreakpoint } from '@/composables/useBreakpoint';-import { useUserStorage } from '@/composables/useBrowserStorage';-import {- mcpAppLogos,- mcpClients,- type McpAppLogo,- type McpClient,- type McpClientId,-} from '@/lib/mcpClients';+import { filled } from '@/lib/helpers';+import { claudeMcpClient, mcpAppLogos, mcpClients } from '@/lib/mcpClients';import {show as showConnectionStatus,store as storePromptAnswer,} from '@/routes/app/mcp/prompt';import type { SharedData } from '@/types';+import type { McpAppLogo, McpClient, McpClientId } from '@/types/mcp';import { fireCelebration } from '@/utils/confetti';interface McpConnectionStatus {@@ -36,26 +32,79 @@ const avatars: McpAppLogo[] = AVATAR_APPS.flatMap((id) =>mcpAppLogos.filter((app) => app.id === id),);+/** Each avatar sits over the next one: the first is on top. */+const avatarStyle = (position: number): { zIndex: number } => ({+ zIndex: avatars.length - position,+});+const page = usePage<SharedData>();const isPhone = useBelowBreakpoint('sm');-const dismissed = useUserStorage('mcp.promptDismissed', false);+const { wentThrough: dismissed, record } = useTourProgress('mcp.prompt');+const tourOnScreen = useTourOnScreen();const connected = ref(false);const prompt = computed(() => page.props.mcpPrompt ?? null);/*** Invites the user to connect an AI until they connect one or say not now.- * Connecting is a desktop task, and the "How did you find us?" survey goes first.+ * Connecting is a desktop task, and the "How did you find us?" survey and an+ * open tour go first.*/-const visible = computed(- (): boolean =>- prompt.value !== null &&- !dismissed.value &&- !connected.value &&- !isPhone.value &&- (page.props.referralSources ?? []).length === 0 &&- page.component !== 'settings/workspace/Mcp',-);+const visible = computed((): boolean => {+ if (!filled(prompt.value)) {+ return false;+ }++ if (dismissed.value) {+ return false;+ }++ if (connected.value) {+ return false;+ }++ if (isPhone.value) {+ return false;+ }++ if (filled(page.props.referralSources)) {+ return false;+ }++ if (tourOnScreen.value) {+ return false;+ }++ return page.component !== 'settings/workspace/Mcp';+});++/** How long the card waits before it shows, in milliseconds. */+const SHOW_DELAY_MS = 400;++/**+ * Whether the card is on screen. It shows a moment after it may, and hides at+ * once: a tour opening on the same page load (the visit after answering the+ * referral survey remounts the layout) goes first, instead of the card+ * flashing in under it and its transition being cut off halfway.+ */+const shown = ref(false);+let showTimer: ReturnType<typeof setTimeout> | undefined;++const followVisible = (canShow: boolean): void => {+ clearTimeout(showTimer);++ if (!canShow) {+ shown.value = false;++ return;+ }++ showTimer = setTimeout(() => {+ shown.value = true;+ }, SHOW_DELAY_MS);+};++watch(visible, followVisible, { immediate: true });const connectHttp = useHttp<{ answer: 'connect'; client: McpClientId }>({answer: 'connect',@@ -65,12 +114,12 @@ const dismissHttp = useHttp<{ answer: 'dismiss' }>({ answer: 'dismiss' });const statusHttp = useHttp<Record<string, never>, McpConnectionStatus>({});const dismiss = (): void => {- dismissed.value = true;+ record('skipped', 1);dismissHttp.post(storePromptAnswer.url()).catch(() => {});};const dialogOpen = ref(false);-const activeClient = ref<McpClient>(mcpClients[0]);+const activeClient = ref<McpClient>(claudeMcpClient);const mcpUrl = ref('');const connect = (client: McpClient): void => {@@ -121,9 +170,19 @@ const followCard = (onScreen: boolean): void => {poll.pause();};-watch(() => visible.value || dialogOpen.value, followCard, { immediate: true });+/** The card or its steps are on screen. */+const isOnScreen = computed((): boolean => {+ if (shown.value) {+ return true;+ }++ return dialogOpen.value;+});++watch(isOnScreen, followCard, { immediate: true });onBeforeUnmount(() => {+ clearTimeout(showTimer);poll.pause();stopConfetti();});@@ -135,24 +194,31 @@ onBeforeUnmount(() => {enter-active-class="motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-2 motion-safe:duration-300"><aside- v-if="visible"+ v-if="shown"class="fixed end-4 bottom-4 z-40 w-[calc(100vw-2rem)] max-w-sm rounded-xl bg-popover p-4 text-popover-foreground shadow-lg dark:border dark:border-border"aria-labelledby="mcp-prompt-title"aria-describedby="mcp-prompt-body"data-testid="mcp-prompt"><div class="flex items-start justify-between gap-3">- <div class="flex -space-x-2" aria-hidden="true">+ <div+ class="flex -space-x-2"+ aria-hidden="true"+ data-testid="mcp-prompt-avatars"+ ><spanv-for="(app, position) in avatars":key="app.id"class="relative inline-flex size-9 items-center justify-center rounded-lg bg-muted ring-2 ring-popover"- :style="{ zIndex: avatars.length - position }"+ :style="avatarStyle(position)":data-testid="`mcp-prompt-avatar-${app.id}`"><component:is="app.logo"- :class="['size-5 text-foreground', app.logoClass]"+ :class="[+ 'size-5 text-foreground',+ app.logoClass,+ ]"/></span></div>@@ -161,7 +227,7 @@ onBeforeUnmount(() => {variant="ghost"size="icon"class="-me-1.5 -mt-1.5 size-7 text-muted-foreground"- :aria-label="$t('mcp.prompt.not_now')"+ :aria-label="$t('tours.mcp.prompt.steps.card.not_now')"data-testid="mcp-prompt-close"@click="dismiss">@@ -173,13 +239,13 @@ onBeforeUnmount(() => {id="mcp-prompt-title"class="mt-3 text-sm font-medium text-foreground">- {{ $t('mcp.prompt.title') }}+ {{ $t('tours.mcp.prompt.steps.card.title') }}</h2><pid="mcp-prompt-body"class="mt-1 text-sm text-muted-foreground">- {{ $t('mcp.prompt.body') }}+ {{ $t('tours.mcp.prompt.steps.card.description') }}</p><div class="mt-4 grid grid-cols-2 gap-2">@@ -191,7 +257,10 @@ onBeforeUnmount(() => {:data-testid="`mcp-prompt-connect-${client.id}`"@click="connect(client)">- <component :is="client.logo" class="size-4 fill-current" />+ <component+ :is="client.logo"+ class="size-4 fill-current"+ />{{ client.label }}</Button></div>diff --git a/resources/js/components/tours/TourOverlay.vue b/resources/js/components/tours/TourOverlay.vuenew file mode 100644index 000000000..df7116dab--- /dev/null+++ b/resources/js/components/tours/TourOverlay.vue@@ -0,0 +1,393 @@+<script setup lang="ts">+import { IconChevronsLeft, IconChevronsRight } from '@tabler/icons-vue';+import { computed, useId, useTemplateRef, watch } from 'vue';++import { Button } from '@/components/ui/button';+import {+ Popover,+ PopoverAnchor,+ PopoverContent,+} from '@/components/ui/popover';+import { useOpenTourStep } from '@/composables/tours/useTour';+import { filled } from '@/lib/helpers';+import { labelTextColor } from '@/lib/labelColor';++/**+ * The dark backdrop and the card of the open tour step, mounted once in the+ * app layout. The backdrop is cut out around the step's control, and the card+ * is anchored to that cut-out and follows it every frame, so moving to the+ * next step slides both to the next control together. Using the control+ * itself moves the tour on; a click elsewhere on the page does nothing, and+ * Escape skips it. In a longer+ * tour the arrow keys move between the steps, without ever ending it.+ */+const openStep = useOpenTourStep();+const backdrop = useTemplateRef<HTMLElement>('backdrop');++const titleId = useId();+const descriptionId = useId();++const isCardOpen = computed((): boolean => {+ if (!filled(openStep.value)) {+ return false;+ }++ return filled(backdrop.value);+});++/** The cut-out of the dark backdrop, over the open step's control. */+const spotlightStyle = computed(() => {+ if (!filled(openStep.value)) {+ return undefined;+ }++ const { frame } = openStep.value;++ return {+ top: `${frame.top}px`,+ left: `${frame.left}px`,+ width: `${frame.width}px`,+ height: `${frame.height}px`,+ };+});++/** The tag's color as the background, with the text color that reads on it, as `LabelBadge` does. */+const tagStyle = computed(() => {+ if (!filled(openStep.value)) {+ return undefined;+ }++ return {+ backgroundColor: openStep.value.tagColor,+ color: labelTextColor(openStep.value.tagColor),+ };+});++const copyKey = computed((): string => {+ if (!filled(openStep.value)) {+ return '';+ }++ return `tours.${openStep.value.tour}.steps.${openStep.value.step}`;+});+const titleKey = computed(() => `${copyKey.value}.title`);+const descriptionKey = computed(() => `${copyKey.value}.description`);++/** A test id without dots, which a CSS selector would read as classes. */+const testId = computed((): string => {+ if (!filled(openStep.value)) {+ return 'tour';+ }++ return `tour-${openStep.value.tour.replaceAll('.', '-')}-${openStep.value.step}`;+});++/** Where the user is in the tour, from 1, and how many steps it shows; 0 while none is open. */+const position = computed((): number => {+ if (!filled(openStep.value)) {+ return 0;+ }++ return openStep.value.position;+});++const total = computed((): number => {+ if (!filled(openStep.value)) {+ return 0;+ }++ return openStep.value.total;+});++/** A tour of one step only says "Got it"; a longer one shows where the user is, Skip, Back and Next. */+const hasSeveralSteps = computed(() => total.value > 1);+const isFirst = computed(() => position.value === 1);+const isLast = computed(() => position.value === total.value);++/** In a longer tour, where the user is ("2 of 3") sits next to the tag, above the title. */+const progressBesideTag = computed((): boolean => {+ if (!filled(openStep.value?.tag)) {+ return false;+ }++ return hasSeveralSteps.value;+});++/** Without a tag, it sits on the title's line instead, so the title stays at the top. */+const progressBesideTitle = computed((): boolean => {+ if (filled(openStep.value?.tag)) {+ return false;+ }++ return hasSeveralSteps.value;+});++/** Without Back (the first step), Next takes Back's place at the end of the row. */+const nextButtonClass = computed((): string | undefined => {+ if (isFirst.value) {+ return 'ms-auto';+ }++ return undefined;+});++const nextLabelKey = computed((): string => {+ if (isLast.value) {+ return 'tours.actions.done';+ }++ return 'tours.actions.next';+});++type Translate = (key: string, replacements: Record<string, string>) => string;++const progressLabel = (translate: Translate): string =>+ translate('tours.progress', {+ current: String(position.value),+ total: String(total.value),+ });++const next = (): void => {+ openStep.value?.next();+};++const back = (): void => {+ openStep.value?.back();+};++const skip = (): void => {+ openStep.value?.skip();+};++type PointerDownOutside = CustomEvent<{ originalEvent: PointerEvent }>;++/**+ * A press outside the card never closes the tour: only its buttons and+ * Escape do. A press on the control the step points at moves the tour on+ * once the click lands on the control; moving on at once would take the+ * control's pointer events away before the click.+ */+const followControl = (event: PointerDownOutside): void => {+ event.preventDefault();++ const clicked = event.detail.originalEvent.target;++ if (!(clicked instanceof Node)) {+ return;+ }++ if (!filled(openStep.value)) {+ return;+ }++ if (!openStep.value.control.contains(clicked)) {+ return;+ }++ pendingControl = openStep.value.control;+ pendingControl.addEventListener('click', next, { once: true });+};++/**+ * The control waiting for the click a press on it started. A press that ends+ * off the control never clicks, so its listener goes when the step changes+ * (another control), never when the same step only moves on screen.+ */+let pendingControl: HTMLElement | null = null;++/** The open step's control: the same while the step only moves on screen. */+const openControl = (): HTMLElement | null => {+ if (!filled(openStep.value)) {+ return null;+ }++ return openStep.value.control;+};++watch(openControl, () => {+ if (!filled(pendingControl)) {+ return;+ }++ pendingControl.removeEventListener('click', next);+ pendingControl = null;+});++/** Focus leaving the card does not close the tour either. */+const keepTourOpen = (event: Event): void => {+ event.preventDefault();+};++/** The arrow key that reads forward: right, or left in a right-to-left language. */+const forwardKey = (): string => {+ if (document.documentElement.dir === 'rtl') {+ return 'ArrowLeft';+ }++ return 'ArrowRight';+};++const backwardKey = (): string => {+ if (document.documentElement.dir === 'rtl') {+ return 'ArrowRight';+ }++ return 'ArrowLeft';+};++/**+ * In a longer tour, the arrow keys move between the steps like Next and+ * Back. They never end the tour: on the last step the forward arrow does+ * nothing, and only Done closes it.+ */+const followArrowKey = (event: KeyboardEvent): void => {+ if (!hasSeveralSteps.value) {+ return;+ }++ if (event.key === forwardKey()) {+ event.preventDefault();++ if (isLast.value) {+ return;+ }++ next();++ return;+ }++ if (event.key === backwardKey()) {+ event.preventDefault();+ back();+ }+};++const closeTour = (open: boolean): void => {+ if (open) {+ return;+ }++ skip();+};+</script>++<template>+ <div class="contents">+ <Teleport to="body">+ <Transition+ enter-active-class="transition-opacity duration-200 ease-out"+ enter-from-class="opacity-0"+ leave-active-class="transition-opacity duration-150 ease-in"+ leave-to-class="opacity-0"+ >+ <div+ v-if="filled(openStep)"+ ref="backdrop"+ class="pointer-events-none fixed z-50 rounded-xl shadow-[0_0_0_9999px_rgb(0_0_0/0.5)] transition-[top,left,width,height] duration-300 ease-in-out motion-reduce:transition-none dark:shadow-[0_0_0_9999px_rgb(0_0_0/0.6)]"+ :style="spotlightStyle"+ data-testid="tour-backdrop"+ />+ </Transition>+ </Teleport>+ <Popover :open="isCardOpen" modal @update:open="closeTour">+ <PopoverAnchor v-if="filled(backdrop)" :reference="backdrop" />+ <PopoverContent+ v-if="filled(openStep)"+ :align="openStep.align"+ :side-offset="12"+ update-position-strategy="always"+ class="z-[60] w-80"+ :aria-labelledby="titleId"+ :aria-describedby="descriptionId"+ :data-testid="`${testId}-content`"+ @pointer-down-outside="followControl"+ @focus-outside="keepTourOpen"+ @keydown="followArrowKey"+ >+ <div+ v-if="filled(openStep.tag)"+ class="mb-2 flex items-center gap-2"+ >+ <span+ class="inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-foreground"+ :style="tagStyle"+ :data-testid="`${testId}-tag`"+ >+ {{ openStep.tag }}+ </span>+ <span+ v-if="progressBesideTag"+ class="ms-auto text-xs text-muted-foreground"+ :data-testid="`${testId}-progress`"+ >+ {{ progressLabel($t) }}+ </span>+ </div>+ <div class="flex items-baseline gap-2">+ <p :id="titleId" class="text-base font-semibold">+ {{ $t(titleKey) }}+ </p>+ <span+ v-if="progressBesideTitle"+ class="ms-auto shrink-0 text-xs text-muted-foreground"+ :data-testid="`${testId}-progress`"+ >+ {{ progressLabel($t) }}+ </span>+ </div>+ <p+ :id="descriptionId"+ class="mt-1 text-sm text-muted-foreground"+ >+ {{ $t(descriptionKey) }}+ </p>+ <div+ v-if="hasSeveralSteps"+ class="mt-4 flex items-center gap-2"+ >+ <Button+ variant="ghost"+ size="sm"+ :data-testid="`${testId}-skip`"+ @click="skip"+ >+ {{ $t('tours.actions.skip') }}+ </Button>+ <Button+ v-if="!isFirst"+ variant="outline"+ size="sm"+ class="ms-auto"+ :data-testid="`${testId}-back`"+ @click="back"+ >+ <IconChevronsLeft class="size-4 rtl:-scale-x-100" />+ {{ $t('tours.actions.back') }}+ </Button>+ <Button+ size="sm"+ :class="nextButtonClass"+ :data-testid="`${testId}-next`"+ @click="next"+ >+ {{ $t(nextLabelKey) }}+ <IconChevronsRight+ v-if="!isLast"+ class="size-4 rtl:-scale-x-100"+ />+ </Button>+ </div>+ <div v-else class="mt-4 flex justify-end">+ <Button+ size="sm"+ :data-testid="`${testId}-next`"+ @click="next"+ >+ {{ $t('tours.actions.got_it') }}+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ </div>+</template>diff --git a/resources/js/components/tours/TourStep.vue b/resources/js/components/tours/TourStep.vuenew file mode 100644index 000000000..3ac396441--- /dev/null+++ b/resources/js/components/tours/TourStep.vue@@ -0,0 +1,92 @@+<script setup lang="ts" generic="Tour extends TourName">+import { useElementBounding } from '@vueuse/core';+import { computed, useTemplateRef, watchEffect } from 'vue';++import { showTourStep, useTourStep } from '@/composables/tours/useTour';+import { filled } from '@/lib/helpers';+import type { TourName, TourStepName } from '@/types/tour';++/**+ * One step of a tour (`TOURS` in `lib/tours.ts`), on the control in its slot.+ * While it is the tour's current step, the tour's overlay (`TourOverlay`)+ * darkens the page around the control and opens the step's title and+ * description (`tours.<tour>.steps.<step>.*`) next to it. A `tag` (already+ * translated, like `$t('tours.tags.new')`) shows above the title as a chip of+ * `tagColor`, the way a label shows (the brand purple unless set). `align`+ * places the card along the control (`end` by default, `start` for a control+ * on the left). A `disabled` step renders its control and never opens; it is+ * read once, when the step mounts.+ */+const props = withDefaults(+ defineProps<{+ tour: Tour;+ step: TourStepName<Tour>;+ tag?: string;+ tagColor?: string;+ disabled?: boolean;+ align?: 'start' | 'center' | 'end';+ }>(),+ { tag: undefined, tagColor: '#7c3aed', disabled: false, align: 'end' },+);++const { isActive, position, total, next, back, skip } = useTourStep(+ props.tour,+ props.step,+ !props.disabled,+);++const target = useTemplateRef<HTMLElement>('target');+const bounds = useElementBounding(target);++/** Room left around the control inside the dark backdrop, in pixels. */+const SPOTLIGHT_PADDING = 6;++/** While this step is open, the overlay shows it on its control. */+watchEffect(() => {+ if (!isActive.value) {+ return;+ }++ if (!filled(target.value)) {+ return;+ }++ showTourStep({+ tour: props.tour,+ step: props.step,+ position: position.value,+ total: total.value,+ tag: props.tag,+ tagColor: props.tagColor,+ align: props.align,+ control: target.value,+ frame: {+ top: bounds.top.value - SPOTLIGHT_PADDING,+ left: bounds.left.value - SPOTLIGHT_PADDING,+ width: bounds.width.value + SPOTLIGHT_PADDING * 2,+ height: bounds.height.value + SPOTLIGHT_PADDING * 2,+ },+ next,+ back,+ skip,+ });+});++/**+ * The open tour blocks the page around it; the control it points at stays+ * usable, so it still reacts to the click that moves the tour on.+ */+const targetClass = computed((): string | undefined => {+ if (isActive.value) {+ return 'pointer-events-auto';+ }++ return undefined;+});+</script>++<template>+ <div ref="target" class="inline-flex" :class="targetClass">+ <slot />+ </div>+</template>diff --git a/resources/js/components/ui/alert-dialog/AlertDialogContent.vue b/resources/js/components/ui/alert-dialog/AlertDialogContent.vueindex c08cd709b..a0a15fe0f 100644--- a/resources/js/components/ui/alert-dialog/AlertDialogContent.vue+++ b/resources/js/components/ui/alert-dialog/AlertDialogContent.vue@@ -8,6 +8,7 @@ import {AlertDialogPortal,useForwardPropsEmits,} from "reka-ui"+import { trackDialogForTours } from "@/composables/tours/useTourWaitsForDialogs"import { cn } from "@/lib/utils"defineOptions({@@ -20,6 +21,8 @@ const emits = defineEmits<AlertDialogContentEmits>()const delegatedProps = reactiveOmit(props, "class")const forwarded = useForwardPropsEmits(delegatedProps, emits)++trackDialogForTours()</script><template>diff --git a/resources/js/components/ui/dialog/DialogContent.vue b/resources/js/components/ui/dialog/DialogContent.vueindex 3b37850e2..88a88a5d2 100644--- a/resources/js/components/ui/dialog/DialogContent.vue+++ b/resources/js/components/ui/dialog/DialogContent.vue@@ -10,6 +10,7 @@ import {useForwardPropsEmits,} from "reka-ui"import { buttonVariants } from "@/components/ui/button"+import { trackDialogForTours } from "@/composables/tours/useTourWaitsForDialogs"import { cn } from "@/lib/utils"import DialogOverlay from "./DialogOverlay.vue"@@ -26,6 +27,8 @@ const emits = defineEmits<DialogContentEmits>()const delegatedProps = reactiveOmit(props, "class", "fullscreenOnMobile")const forwarded = useForwardPropsEmits(delegatedProps, emits)++trackDialogForTours()</script><template>diff --git a/resources/js/components/ui/sheet/SheetContent.vue b/resources/js/components/ui/sheet/SheetContent.vueindex 9f9326869..a36fa1019 100644--- a/resources/js/components/ui/sheet/SheetContent.vue+++ b/resources/js/components/ui/sheet/SheetContent.vue@@ -10,6 +10,7 @@ import {useForwardPropsEmits,} from "reka-ui"import { buttonVariants } from "@/components/ui/button"+import { trackDialogForTours } from "@/composables/tours/useTourWaitsForDialogs"import { cn } from "@/lib/utils"import SheetOverlay from "./SheetOverlay.vue"@@ -32,6 +33,8 @@ const emits = defineEmits<DialogContentEmits>()const delegatedProps = reactiveOmit(props, "class", "side", "showCloseButton")const forwarded = useForwardPropsEmits(delegatedProps, emits)++trackDialogForTours()</script><template>diff --git a/resources/js/composables/tours/useTour.ts b/resources/js/composables/tours/useTour.tsnew file mode 100644index 000000000..0fd4e44e3--- /dev/null+++ b/resources/js/composables/tours/useTour.ts@@ -0,0 +1,377 @@+import { useHttp, usePage } from '@inertiajs/vue3';+import {+ computed,+ type ComputedRef,+ nextTick,+ onBeforeUnmount,+ onMounted,+ reactive,+ shallowRef,+ watch,+} from 'vue';++import { isDialogBlockingTours } from '@/composables/tours/useTourWaitsForDialogs';+import { useBelowBreakpoint } from '@/composables/useBreakpoint';+import { useUserStorage } from '@/composables/useBrowserStorage';+import { isPostComposerOpen } from '@/composables/useGlobalPostComposer';+import { filled } from '@/lib/helpers';+import {+ firstStep,+ shownSteps,+ stepAfter,+ stepBefore,+ TOURS,+} from '@/lib/tours';+import { store as storeTour } from '@/routes/app/tours';+import type { SharedData } from '@/types';+import type {+ OpenTourStep,+ TourName,+ TourOutcome,+ TourStepName,+} from '@/types/tour';++/** The steps of each tour whose control is on the page. */+const onPage = reactive(new Map<TourName, string[]>());++/** The tour on screen and its step: one tour at a time, the first one on the page. */+const active = shallowRef<{ tour: TourName; step: string } | null>(null);++/**+ * The open step, published by its `TourStep`: one backdrop and one card for+ * the whole tour, so moving to the next step moves them to the next control+ * instead of closing one and opening another.+ */+const openStep = shallowRef<OpenTourStep | null>(null);++/**+ * The step each tour was on when it was put away without ending (a visit+ * that remounts the page, a dialog opened over it, a window narrowed to a+ * phone's width), keyed by user and tour (`<user id>:<tour>`): the tour picks+ * up there when that step is back on the page, for that user only.+ */+const resumeAt = new Map<string, string>();++/** The start of every step on the page, in mount order: tried again whenever no tour is open. */+const starters = new Set<() => void>();++/** Tries every step on the page, so the first tour that may open opens. */+const startWaitingTours = (): void => {+ starters.forEach((start) => start());+};++/** Closes the open tour and opens the next one waiting on the page, if any. */+const closeActive = (): void => {+ active.value = null;+ openStep.value = null;++ nextTick(startWaitingTours);+};++/** Whether this tour's step is the one open. */+const isOpenStep = (tour: TourName, step: string): boolean => {+ const current = active.value;++ if (!filled(current)) {+ return false;+ }++ if (current.tour !== tour) {+ return false;+ }++ return current.step === step;+};++/** Whether a tour is open on the page, so what would sit over it (the MCP card) waits. */+export const useTourOnScreen = (): ComputedRef<boolean> =>+ computed(() => filled(active.value));++/** The open step shows itself on its control. */+export const showTourStep = (step: OpenTourStep): void => {+ openStep.value = step;+};++/** The step the overlay shows, or none while no tour is open. */+export const useOpenTourStep = (): ComputedRef<OpenTourStep | null> =>+ computed(() => {+ if (!filled(active.value)) {+ return null;+ }++ return openStep.value;+ });++interface TourProgressState {+ wentThrough: ComputedRef<boolean>;+ record: (outcome: TourOutcome, step: number) => void;+}++/**+ * Whether the user went through a tour in this browser, and the way to record+ * how it ended (`tours` in the browser storage). A tour is recorded once.+ */+export const useTourProgress = (tour: TourName): TourProgressState => {+ const progress = useUserStorage('tours', {});++ const wentThrough = computed(() => filled(progress.value?.[tour]));++ const record = (outcome: TourOutcome, step: number): void => {+ if (wentThrough.value) {+ return;+ }++ progress.value = {+ ...progress.value,+ [tour]: { status: outcome, step },+ };+ };++ return { wentThrough, record };+};++interface TourStepState {+ isActive: ComputedRef<boolean>;+ position: ComputedRef<number>;+ total: ComputedRef<number>;+ next: () => void;+ back: () => void;+ skip: () => void;+}++/**+ * One step of a tour, on the control it points at. The tour opens on its+ * first step on the page, once per user in this browser: reaching the end or+ * closing it before is recorded (`useTourProgress`) and tracked.+ * Leaving the page midway closes it without a record, so it opens again, at+ * the step it was on while the app stays open; closing it in another tab+ * closes it here. Once it closes, the next tour waiting on the page opens. A+ * tour waits while the page is busy (the composer, a dialog, the referral+ * survey). Tours are a desktop thing: on a phone none opens, and narrowing+ * the window to a phone's width hides the open one until it widens again.+ * A step that is not `enabled` (a page where its copy does not fit) never+ * counts as on the page.+ */+export const useTourStep = <Tour extends TourName>(+ tour: Tour,+ step: TourStepName<Tour>,+ enabled = true,+): TourStepState => {+ const page = usePage<SharedData>();+ const isPhone = useBelowBreakpoint('sm');+ const { wentThrough, record } = useTourProgress(tour);+ const tracking = useHttp<{+ tour: TourName;+ outcome: TourOutcome;+ step: number;+ steps: number;+ }>({ tour, outcome: 'completed', step: 1, steps: 1 });++ const shown = computed(() =>+ shownSteps(TOURS[tour], onPage.get(tour) ?? []),+ );+ const position = computed(() => shown.value.indexOf(step) + 1);+ const total = computed(() => shown.value.length);++ const isActive = computed(() => isOpenStep(tour, step));++ /**+ * Something on the page goes first: the composer, any open dialog, or the+ * "How did you find us?" survey.+ */+ const isPageBusy = computed((): boolean => {+ if (isPostComposerOpen.value) {+ return true;+ }++ if (filled(page.props.referralSources)) {+ return true;+ }++ return isDialogBlockingTours.value;+ });++ const resumeKey = (): string => `${page.props.auth.user.id}:${tour}`;++ /** The step the tour opens on: where this user left it, while that step is on the page, else its first. */+ const openingStep = (): string | null => {+ const resumed = resumeAt.get(resumeKey());++ if (!filled(resumed)) {+ return firstStep(shown.value);+ }++ if (!shown.value.includes(resumed)) {+ return firstStep(shown.value);+ }++ return resumed;+ };++ /** Puts this tour away, when it is the open one, to pick it up at the same step later. */+ const putAway = (): void => {+ const current = active.value;++ if (!filled(current)) {+ return;+ }++ if (current.tour !== tour) {+ return;+ }++ resumeAt.set(resumeKey(), current.step);+ closeActive();+ };++ const start = (): void => {+ if (page.props.toursEnabled !== true) {+ return;+ }++ if (isPhone.value) {+ return;+ }++ if (filled(active.value)) {+ return;+ }++ if (wentThrough.value) {+ return;+ }++ const opening = openingStep();++ if (!filled(opening)) {+ return;+ }++ if (isPageBusy.value) {+ return;+ }++ resumeAt.delete(resumeKey());+ active.value = { tour, step: opening };+ };++ const finish = (outcome: TourOutcome, reached: number): void => {+ closeActive();++ if (wentThrough.value) {+ return;+ }++ record(outcome, reached);++ tracking.outcome = outcome;+ tracking.step = reached;+ tracking.steps = total.value;+ tracking.post(storeTour.url()).catch(() => {});+ };++ const next = (): void => {+ const after = stepAfter(shown.value, step);++ if (!filled(after)) {+ finish('completed', total.value);++ return;+ }++ active.value = { tour, step: after };+ };++ const back = (): void => {+ const before = stepBefore(shown.value, step);++ if (!filled(before)) {+ return;+ }++ active.value = { tour, step: before };+ };++ const skip = (): void => {+ finish('skipped', position.value);+ };++ /** Closing the tour in another tab closes it here, and lets the next one open. */+ watch(wentThrough, (went) => {+ if (!went) {+ return;+ }++ if (active.value?.tour !== tour) {+ return;+ }++ closeActive();+ });++ /**+ * A dialog opened over the open tour (the command palette, the composer)+ * puts it away; once the page is free again (the dialog closed, the survey+ * answered), the tour opens, at the step it was on.+ */+ watch(isPageBusy, (busy) => {+ if (busy) {+ putAway();++ return;+ }++ start();+ });++ /**+ * A window narrowed to a phone's width hides the open tour without a+ * record, and widening it again opens the tour at the step it was on.+ */+ watch(isPhone, (phone) => {+ if (!phone) {+ start();++ return;+ }++ putAway();+ });++ /** Takes one mount of this step off the page, keeping any other mount of it. */+ const leavePage = (): void => {+ const mounted = [...(onPage.get(tour) ?? [])];++ if (!mounted.includes(step)) {+ return;+ }++ mounted.splice(mounted.indexOf(step), 1);+ onPage.set(tour, mounted);+ };++ onMounted(() => {+ if (!enabled) {+ return;+ }++ onPage.set(tour, [...(onPage.get(tour) ?? []), step]);+ starters.add(start);+ nextTick(start);+ });++ onBeforeUnmount(() => {+ if (!enabled) {+ return;+ }++ leavePage();+ starters.delete(start);++ if (isOpenStep(tour, step)) {+ putAway();+ }+ });++ return { isActive, position, total, next, back, skip };+};diff --git a/resources/js/composables/tours/useTourWaitsForDialogs.ts b/resources/js/composables/tours/useTourWaitsForDialogs.tsnew file mode 100644index 000000000..d108be2b0--- /dev/null+++ b/resources/js/composables/tours/useTourWaitsForDialogs.ts@@ -0,0 +1,40 @@+import { injectDialogRootContext } from 'reka-ui';+import { computed, onBeforeUnmount, ref, watch } from 'vue';++const openDialogs = ref(0);++/**+ * Whether a dialog, alert dialog or sheet of `components/ui` is open on the+ * page, so a tour waits for it to close instead of opening over it.+ */+export const isDialogBlockingTours = computed(() => openDialogs.value > 0);++/**+ * Tells the tours while the dialog this content belongs to is open, read+ * from the dialog's own state. Called by the content component of every+ * dialog in `components/ui` (dialog, alert dialog, sheet); only the tours+ * read it (`isDialogBlockingTours`).+ */+export const trackDialogForTours = (): void => {+ const { open } = injectDialogRootContext();+ let counted = false;++ const sync = (isOpen: boolean): void => {+ if (isOpen === counted) {+ return;+ }++ counted = isOpen;++ if (isOpen) {+ openDialogs.value += 1;++ return;+ }++ openDialogs.value -= 1;+ };++ watch(open, sync, { immediate: true });+ onBeforeUnmount(() => sync(false));+};diff --git a/resources/js/layouts/app/AppSidebarLayout.vue b/resources/js/layouts/app/AppSidebarLayout.vueindex 702946cc0..cb85f270d 100644--- a/resources/js/layouts/app/AppSidebarLayout.vue+++ b/resources/js/layouts/app/AppSidebarLayout.vue@@ -12,10 +12,11 @@ import AppSidebar from '@/components/AppSidebar.vue';import ChangelogDialog from '@/components/changelog/ChangelogDialog.vue';import ConnectChannelDialog from '@/components/channels/ConnectChannelDialog.vue';import CommandPalette from '@/components/command-palette/CommandPalette.vue';-import McpPromptCard from '@/components/mcp/McpPromptCard.vue';import GlobalPostComposer from '@/components/posts/composer/GlobalPostComposer.vue';import ReferralSourceSurvey from '@/components/ReferralSourceSurvey.vue';import Toast from '@/components/Toast.vue';+import McpPromptTour from '@/components/tours/McpPromptTour.vue';+import TourOverlay from '@/components/tours/TourOverlay.vue';import {SidebarInset,SidebarProvider,@@ -123,6 +124,7 @@ watch(isCompactViewport, (isCompact) => {<ChangelogDialog /><CommandPalette /><ReferralSourceSurvey />- <McpPromptCard />+ <McpPromptTour />+ <TourOverlay /><Toast /></template>diff --git a/resources/js/lib/mcpClients.ts b/resources/js/lib/mcpClients.tsindex f19a024fd..b74fa7647 100644--- a/resources/js/lib/mcpClients.ts+++ b/resources/js/lib/mcpClients.ts@@ -14,25 +14,8 @@ import NousresearchHermes from '@thesvg/vue/nousresearch-hermes';import OpenWebui from '@thesvg/vue/open-webui';import OpenaiChatgpt from '@thesvg/vue/openai-chatgpt';import Opencode from '@thesvg/vue/opencode';-import type { Component } from 'vue';--export type McpClientId = 'claude' | 'chatgpt' | 'other';--export interface McpClient {- id: McpClientId;- /** A brand name, or a lang key to resolve with `$t` when `labelKey` is set. */- label: string;- labelKey?: boolean;- /** The mark on neutral surfaces, in its brand color or the text color. */- logo: Component;- /** Where the user adds a connector in that client; none for a generic app. */- settingsUrl?: string;- /** Listed in the client's app store: the user connects from its page, nothing to paste. */- listed?: boolean;- /** A button filled in the brand's color, with the mark in the button's text color. */- brandButtonClass?: string;-}+import type { McpAppLogo, McpClient } from '@/types/mcp';/** TryPost's page in the ChatGPT app store. */const CHATGPT_APP_URL =@@ -42,20 +25,23 @@ const CHATGPT_APP_URL =const CLAUDE_ADD_CONNECTOR_URL ='https://claude.ai/new?modal=add-custom-connector#customize/connectors/yours';+/** Claude: the app whose connect steps open first, before the user picks one. */+export const claudeMcpClient: McpClient = {+ id: 'claude',+ label: 'Claude',+ logo: Claude,+ settingsUrl: CLAUDE_ADD_CONNECTOR_URL,+ brandButtonClass:+ 'bg-[#d97757] text-white hover:bg-[#c4643f] dark:bg-[#d97757] dark:text-white dark:hover:bg-[#c4643f]',+};+/*** First-class MCP clients surfaced on workspace MCP settings and the in-app- * card that invites the user to connect an AI (`McpPromptCard`).+ * card that invites the user to connect an AI (`McpPromptTour`).* `settingsUrl` is where the user adds a connector in that client.*/export const mcpClients: McpClient[] = [- {- id: 'claude',- label: 'Claude',- logo: Claude,- settingsUrl: CLAUDE_ADD_CONNECTOR_URL,- brandButtonClass:- 'bg-[#d97757] text-white hover:bg-[#c4643f] dark:bg-[#d97757] dark:text-white dark:hover:bg-[#c4643f]',- },+ claudeMcpClient,{id: 'chatgpt',label: 'ChatGPT',@@ -75,14 +61,6 @@ export const otherMcpClient: McpClient = {logo: McpModelContextProtocol,};-/** A connected app's logo, found by a word of the name the app registered with. */-export interface McpAppLogo {- id: string;- name: string;- logo: Component;- logoClass?: string;-}-/*** The logos of the MCP apps people connect, most specific name first* ("Claude Code" before Claude's own mark). An app without one shows the MCP mark.diff --git a/resources/js/lib/tours.ts b/resources/js/lib/tours.tsnew file mode 100644index 000000000..1b378f430--- /dev/null+++ b/resources/js/lib/tours.ts@@ -0,0 +1,64 @@+/**+ * Every tour and its steps, in the order they show, mirrored by+ * `App\Enums\Tour\Tour`. Each step's copy is+ * `tours.<tour>.steps.<step>.title` and `.description` in+ * `lang/<locale>/tours.php` (`ToursTest` keeps the three in step). A+ * `TourStep` tour is tracked through `app.tours.store`; `mcp.prompt`, the card+ * inviting the user to connect an AI (`McpPromptTour`), keeps its own+ * tracking and only records its "Not now" with the tours.+ */+export const TOURS = {+ 'publish.views': ['views'],+ 'insights.filters': ['range', 'channels', 'labels'],+ 'mcp.prompt': ['card'],+} as const satisfies Record<string, readonly string[]>;++/**+ * The steps of a tour whose control is on the page, in the tour's order: a+ * step whose control is not there (another page, a permission) is left out.+ */+export const shownSteps = (+ steps: readonly string[],+ onPage: readonly string[],+): string[] => steps.filter((step) => onPage.includes(step));++/**+ * The step a tour opens on: the first of those shown, or null when none of+ * its controls is on the page. This file imports nothing, `@/lib/helpers`+ * included, so the Node harness of `ToursTest` can load it as it is.+ */+export const firstStep = (shown: readonly string[]): string | null => {+ if (shown.length === 0) {+ return null;+ }++ return shown[0];+};++/** The last of the steps shown, or null when none is. */+export const lastStep = (shown: readonly string[]): string | null =>+ firstStep([...shown].reverse());++/** The step after `current` among those shown: the first of those after it, or null when it is the last. */+export const stepAfter = (+ shown: readonly string[],+ current: string,+): string | null => {+ if (!shown.includes(current)) {+ return null;+ }++ return firstStep(shown.slice(shown.indexOf(current) + 1));+};++/** The step before `current` among those shown: the last of those before it, or null when it is the first. */+export const stepBefore = (+ shown: readonly string[],+ current: string,+): string | null => {+ if (!shown.includes(current)) {+ return null;+ }++ return lastStep(shown.slice(0, shown.indexOf(current)));+};diff --git a/resources/js/pages/insights/Index.vue b/resources/js/pages/insights/Index.vueindex 5969413ca..0f65b3f4a 100644--- a/resources/js/pages/insights/Index.vue+++ b/resources/js/pages/insights/Index.vue@@ -17,6 +17,7 @@ import EmptyState from '@/components/EmptyState.vue';import HeaderTitle from '@/components/HeaderTitle.vue';import LabelFilter from '@/components/labels/LabelFilter.vue';import PostChannelFilter from '@/components/posts/PostChannelFilter.vue';+import TourStep from '@/components/tours/TourStep.vue';import { useAnalyticsCoveragePoll } from '@/composables/useAnalyticsCoveragePoll';import AppLayout from '@/layouts/AppLayout.vue';import { accountColor } from '@/lib/analyticsColors';@@ -185,30 +186,40 @@ const accountColors = computed<Record<string, string>>(() => {class="flex min-h-12 min-w-0 flex-wrap items-center justify-between gap-2 border-b border-border-strong pt-2 pb-3"data-testid="analytics-toolbar">- <AnalyticsRangePresets- :filters="report.filters"- :bounds="report.bounds"- :url="insightsRoute.url()"- :range="report.range"- :keep="filterQuery"- />+ <TourStep+ tour="insights.filters"+ step="range"+ align="start"+ >+ <AnalyticsRangePresets+ :filters="report.filters"+ :bounds="report.bounds"+ :url="insightsRoute.url()"+ :range="report.range"+ :keep="filterQuery"+ />+ </TourStep><divclass="flex min-w-0 flex-wrap items-center gap-2"data-testid="analytics-filters">- <PostChannelFilter- v-model="selectedChannelIds"- :channels="channelOptions"- test-id="analytics-channel"- sheet-below-sm- />- <LabelFilter- v-model="selectedLabelIds"- v-model:untagged="selectedUntagged"- :labels="labels"- test-id="analytics-label"- sheet-below-sm- />+ <TourStep tour="insights.filters" step="channels">+ <PostChannelFilter+ v-model="selectedChannelIds"+ :channels="channelOptions"+ test-id="analytics-channel"+ sheet-below-sm+ />+ </TourStep>+ <TourStep tour="insights.filters" step="labels">+ <LabelFilter+ v-model="selectedLabelIds"+ v-model:untagged="selectedUntagged"+ :labels="labels"+ test-id="analytics-label"+ sheet-below-sm+ />+ </TourStep></div></div></header>diff --git a/resources/js/pages/settings/workspace/Mcp.vue b/resources/js/pages/settings/workspace/Mcp.vueindex 3a235c6d6..ec466cf8e 100644--- a/resources/js/pages/settings/workspace/Mcp.vue+++ b/resources/js/pages/settings/workspace/Mcp.vue@@ -24,8 +24,14 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import date from '@/date';import SettingsLayout from '@/layouts/SettingsLayout.vue';import { DOCS_URL } from '@/lib/docs';-import { mcpAppLogos, mcpClients, otherMcpClient, type McpClient } from '@/lib/mcpClients';+import {+ claudeMcpClient,+ mcpAppLogos,+ mcpClients,+ otherMcpClient,+} from '@/lib/mcpClients';import { disconnect as mcpDisconnect } from '@/routes/app/mcp';+import type { McpClient } from '@/types/mcp';import { fireCelebration } from '@/utils/confetti';interface ConnectedClient {@@ -66,7 +72,7 @@ const confirmDisconnect = (client: ConnectedClient, keyword: string): void => {const connectableClients: McpClient[] = [...mcpClients, otherMcpClient];-const activeClient = ref<McpClient>(mcpClients[0]);+const activeClient = ref<McpClient>(claudeMcpClient);const dialogOpen = ref(false);const connectWith = (client: McpClient): void => {diff --git a/resources/js/types/browser-storage.ts b/resources/js/types/browser-storage.tsindex 648fa274f..0403dc8af 100644--- a/resources/js/types/browser-storage.ts+++ b/resources/js/types/browser-storage.ts@@ -2,6 +2,7 @@ import type { AutosaveSnapshot } from '@/composables/useComposerAutosave';import type { PerformanceMetric, SummaryMetric } from '@/types/analytics';import type { PlatformValue } from '@/types/platform';import type { PublishView } from '@/types/publish';+import type { TourName, TourProgress } from '@/types/tour';/** The columns picked for each network's per-post table on the channel insights. */type ChannelColumns = {@@ -13,7 +14,6 @@ type ChannelColumns = {* (`area.thing`, like lang keys). An item never set is absent.*/export interface UserStorage extends ChannelColumns {- 'mcp.promptDismissed': boolean;'calendar.skipCustomTimeConfirm': boolean;'publish.tz': string;'publish.showSlots': boolean;@@ -21,6 +21,7 @@ export interface UserStorage extends ChannelColumns {'insights.performanceColumns': PerformanceMetric[];'composer.instagramCollaboratorsNoticeSeen': boolean;'emoji.recents': string[];+ tours: Partial<Record<TourName, TourProgress>>;}/** What the app keeps for a user in one workspace: channel and post ids, the draft. */diff --git a/resources/js/types/index.d.ts b/resources/js/types/index.d.tsindex 7fb52550a..3ee5adb2f 100644--- a/resources/js/types/index.d.ts+++ b/resources/js/types/index.d.ts@@ -117,6 +117,7 @@ export interface SharedData {changelog?: SharedChangelog | null;changelogEntries?: ScrollChangelogEntries;mediaUploadLimits?: MediaUploadLimits | null;+ toursEnabled?: boolean;[key: string]: unknown;}diff --git a/resources/js/types/mcp.ts b/resources/js/types/mcp.tsnew file mode 100644index 000000000..f494ca7ba--- /dev/null+++ b/resources/js/types/mcp.ts@@ -0,0 +1,27 @@+import type { Component } from 'vue';++/** The MCP apps TryPost shows connect steps for; `other` is any other MCP-capable app. */+export type McpClientId = 'claude' | 'chatgpt' | 'other';++export interface McpClient {+ id: McpClientId;+ /** A brand name, or a lang key to resolve with `$t` when `labelKey` is set. */+ label: string;+ labelKey?: boolean;+ /** The mark on neutral surfaces, in its brand color or the text color. */+ logo: Component;+ /** Where the user adds a connector in that client; none for a generic app. */+ settingsUrl?: string;+ /** Listed in the client's app store: the user connects from its page, nothing to paste. */+ listed?: boolean;+ /** A button filled in the brand's color, with the mark in the button's text color. */+ brandButtonClass?: string;+}++/** A connected app's logo, found by a word of the name the app registered with. */+export interface McpAppLogo {+ id: string;+ name: string;+ logo: Component;+ logoClass?: string;+}diff --git a/resources/js/types/tour.ts b/resources/js/types/tour.tsnew file mode 100644index 000000000..4e36911b6--- /dev/null+++ b/resources/js/types/tour.ts@@ -0,0 +1,41 @@+import type { TOURS } from '@/lib/tours';++/** A tour of `TOURS`, named by its key in `lang/<locale>/tours.php`. */+export type TourName = keyof typeof TOURS;++/** A step of the given tour (of any tour when none is given). */+export type TourStepName<Tour extends TourName = TourName> =+ (typeof TOURS)[Tour][number];++/** How a tour ended: its last step reached, or closed before. Mirrors `App\Enums\Tour\Outcome`. */+export type TourOutcome = 'completed' | 'skipped';++/** What the browser keeps of a tour the user went through: how it ended and the step reached, from 1. */+export interface TourProgress {+ status: TourOutcome;+ step: number;+}++/** Where the open step's control is on screen, in pixels. */+export interface TourSpotlight {+ top: number;+ left: number;+ width: number;+ height: number;+}++/** What the open step shows and does, drawn by the one overlay of every tour (`TourOverlay`). */+export interface OpenTourStep {+ tour: TourName;+ step: string;+ position: number;+ total: number;+ tag?: string;+ tagColor: string;+ align: 'start' | 'center' | 'end';+ control: HTMLElement;+ frame: TourSpotlight;+ next: () => void;+ back: () => void;+ skip: () => void;+}diff --git a/routes/app.php b/routes/app.phpindex 05bd1a12d..48a798668 100644--- a/routes/app.php+++ b/routes/app.php@@ -54,6 +54,7 @@ use App\Http\Controllers\App\Settings\PasswordController;use App\Http\Controllers\App\Settings\PreferencesController;use App\Http\Controllers\App\Settings\ProfileController;use App\Http\Controllers\App\Settings\SessionController;+use App\Http\Controllers\App\TourController;use App\Http\Controllers\App\UnsplashController;use App\Http\Controllers\App\WebhookController;use App\Http\Controllers\App\WelcomeController;@@ -400,6 +401,10 @@ Route::middleware(['auth', EnsureAccountReady::class, EnsureHasWorkspace::class]->middleware('throttle:30,1')->name('app.mcp.prompt.store');+ Route::post('tours', [TourController::class, 'store'])+ ->middleware('throttle:30,1')+ ->name('app.tours.store');+Route::get('repurposes', [RepurposeController::class, 'index'])->name('app.repurposes.index');Route::post('repurposes', [RepurposeController::class, 'store'])->name('app.repurposes.store');Route::get('repurposes/{repurpose}', [RepurposeController::class, 'show'])->name('app.repurposes.show');diff --git a/storage/framework/lsp-0d246215c7f727e3.php b/storage/framework/lsp-0d246215c7f727e3.phpnew file mode 100644index 000000000..b26396282--- /dev/null+++ b/storage/framework/lsp-0d246215c7f727e3.php@@ -0,0 +1,434 @@+<?php+define('LARAVEL_START', microtime(true));+require getcwd() . '/vendor/autoload.php';+$app = require getcwd() . '/bootstrap/app.php';+$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();+error_reporting(error_reporting() & ~(E_WARNING | E_CORE_WARNING | E_COMPILE_WARNING | E_USER_WARNING | E_DEPRECATED | E_USER_DEPRECATED));+class LspHelper+{+public static function relativePath($path)+{+if (!str_contains($path, base_path())) {+return (string) $path;+}++return ltrim(str_replace(base_path(), '', realpath($path) ?: $path), DIRECTORY_SEPARATOR);+}++public static function isVendor($path)+{+return str_contains($path, base_path('vendor'));+}++public static function propertyDefault(ReflectionProperty $property, ?ReflectionParameter $parameter = null): array+{+if ($property->hasDefaultValue()) {+return ['default' => $property->getDefaultValue()];+}++if ($parameter?->isDefaultValueAvailable()) {+return ['default' => $parameter->getDefaultValue()];+}++return [];+}++public static function formatDefaultValue(mixed $value): mixed+{+return match (true) {+is_array($value) => 'array(...)',+$value instanceof UnitEnum => get_class($value) . '::' . $value->name,+$value instanceof Closure => 'Closure',+is_object($value) => get_class($value),+is_string($value) => var_export($value, true),+is_null($value) => 'null',+is_bool($value) => $value ? 'true' : 'false',+default => $value,+};+}+}++use Illuminate\Support\Arr;+use Illuminate\Support\Facades\App;+use Illuminate\Support\Facades\File;+use Illuminate\Support\LazyCollection;++$translator = new class+{+public $paths = [];++public $values = [];++public $paramResults = [];++public $params = [];++public $emptyParams = [];++public $directoriesToWatch = [];++public $languages = [];++public function all()+{+$final = [];++foreach ($this->retrieve() as $value) {+if ($value instanceof LazyCollection) {+foreach ($value as $val) {+$dotKey = $val['k'];+$final[$dotKey] ??= [];++if (!in_array($val['la'], $this->languages)) {+$this->languages[] = $val['la'];+}++$final[$dotKey][$val['la']] = $val['vs'];+}+} else {+foreach ($value['vs'] as $v) {+$dotKey = "{$value['k']}.{$v['k']}";+$final[$dotKey] ??= [];++if (!in_array($value['la'], $this->languages)) {+$this->languages[] = $value['la'];+}++$final[$dotKey][$value['la']] = $v['arr'];+}+}+}++return $final;+}++protected function retrieve()+{+$loader = app('translator')->getLoader();+$namespaces = $loader->namespaces();++$paths = $this->getPaths($loader);++$default = collect($paths)->flatMap(+fn ($path) => $this->collectFromPath($path)+);++$namespaced = collect($namespaces)->flatMap(+fn ($path, $namespace) => $this->collectFromPath($path, $namespace)+);++return $default->merge($namespaced);+}++protected function getPaths($loader)+{+$reflection = new ReflectionClass($loader);+$property = null;++if ($reflection->hasProperty('paths')) {+$property = $reflection->getProperty('paths');+} elseif ($reflection->hasProperty('path')) {+$property = $reflection->getProperty('path');+}++if ($property !== null) {+return Arr::wrap($property->getValue($loader));+}++return [];+}++public function collectFromPath(string $path, ?string $namespace = null)+{+$realPath = realpath($path);++if (!is_dir($realPath)) {+return [];+}++if (!LspHelper::isVendor($realPath)) {+$this->directoriesToWatch[] = LspHelper::relativePath($realPath);+}++return array_map(+fn ($file) => $this->fromFile($file, $realPath, $namespace),+File::allFiles($realPath),+);+}++protected function fromFile($file, $path, $namespace)+{+if (pathinfo($file, PATHINFO_EXTENSION) === 'json') {+return $this->fromJsonFile($file, $path, $namespace);+}++return $this->fromPhpFile($file, $path, $namespace);+}++protected function linesFromJsonFile($file)+{+$contents = file_get_contents($file);++try {+$json = json_decode($contents, true) ?? [];+} catch (Throwable $e) {+return [[], []];+}++if (count($json) === 0) {+return [[], []];+}++$lines = explode(PHP_EOL, $contents);+$encoded = array_map(+fn ($k) => [json_encode($k, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), $k],+array_keys($json),+);+$result = [];+$searchRange = 5;++foreach ($encoded as $index => $keys) {++if (strpos($lines[$index + 1] ?? '', $keys[0]) !== false) {+$result[$keys[1]] = $index + 2;++continue;+}+++$start = max(0, $index - $searchRange);+$end = min($index + $searchRange, count($lines) - 1);+$current = $start;++while ($current <= $end) {+if (strpos($lines[$current], $keys[0]) !== false) {+$result[$keys[1]] = $current + 1;+break;+}++$current++;+}+}++return [$json, $result];+}++protected function linesFromPhpFile($file)+{+$tokens = token_get_all(file_get_contents($file));+$found = [];++$inArrayKey = true;+$arrayDepth = -1;+$depthKeys = [];++foreach ($tokens as $index => $token) {+if (!is_array($token)) {+if ($token === '[') {+$inArrayKey = true;+$currentIndex = 0;+$arrayDepth++;+}++if ($token === ']') {+$inArrayKey = true;+$arrayDepth--;+array_pop($depthKeys);+}++continue;+}++if ($token[0] === T_DOUBLE_ARROW) {+$inArrayKey = false;+}++if ($inArrayKey && $token[0] === T_CONSTANT_ENCAPSED_STRING) {+$nextToken = isset($tokens[$index + 1]) ? $tokens[$index + 1] : null;+$nextValue = isset($nextToken[1]) ? $nextToken[1] : $nextToken;++if ($nextValue === ',' || str_contains($nextValue, "\n")) {+$token[1] = $currentIndex;++$currentIndex++;+}++$depthKeys[$arrayDepth] = trim($token[1], '"\'');++Arr::set($found, implode('.', $depthKeys), $token[2]);+}++if (!$inArrayKey && $token[0] === T_CONSTANT_ENCAPSED_STRING) {+$inArrayKey = true;+}+}++return Arr::dot($found);+}++protected function getDotted($key, $lang)+{+try {+return Arr::dot(+Arr::wrap(+__($key, [], $lang),+),+);+} catch (Throwable $e) {++return [];+}+}++protected function getPathIndex($file)+{+$path = LspHelper::relativePath($file);++$index = $this->paths[$path] ?? null;++if ($index !== null) {+return $index;+}++$this->paths[$path] = count($this->paths);++return $this->paths[$path];+}++protected function getValueIndex($value)+{+$index = $this->values[$value] ?? null;++if ($index !== null) {+return $index;+}++$this->values[$value] = count($this->values);++return $this->values[$value];+}++protected function getParamIndex($key)+{+$processed = $this->params[$key] ?? null;++if ($processed) {+return $processed[0];+}++if (in_array($key, $this->emptyParams)) {+return null;+}++$params = preg_match_all("/\:([A-Za-z0-9_]+)/", $key, $matches)+? $matches[1]+: [];++if (count($params) === 0) {+$this->emptyParams[] = $key;++return null;+}++$paramKey = json_encode($params);++$paramIndex = $this->paramResults[$paramKey] ?? null;++if ($paramIndex !== null) {+$this->params[$key] = [$paramIndex, $params];++return $paramIndex;+}++$paramIndex = count($this->paramResults);++$this->paramResults[$paramKey] = $paramIndex;++$this->params[$key] = [$paramIndex, $params];++return $paramIndex;+}++protected function fromJsonFile($file, $path, $namespace)+{+$lang = pathinfo($file, PATHINFO_FILENAME);++$relativePath = $this->getPathIndex($file);++$lines = File::lines($file);++return LazyCollection::make(function () use ($file, $lang, $relativePath, $lines) {+[$json, $lines] = $this->linesFromJsonFile($file);++foreach ($json as $key => $value) {+if (!array_key_exists($key, $lines) || is_array($value)) {+continue;+}++yield [+'k' => $key,+'la' => $lang,+'vs' => [+$this->getValueIndex($value),+$relativePath,+$lines[$key] ?? null,+$this->getParamIndex($key),+],+];+}+});+}++protected function fromPhpFile($file, $path, $namespace)+{+$lang = str($file)+->after($path . DIRECTORY_SEPARATOR)+->before(DIRECTORY_SEPARATOR)+->value();++$key = str($file)+->after($path . DIRECTORY_SEPARATOR)+->after(DIRECTORY_SEPARATOR)+->replaceLast('.php', '')+->value();++if ($namespace) {+$key = "{$namespace}::{$key}";+}++$relativePath = $this->getPathIndex($file);+$lines = $this->linesFromPhpFile($file);++return [+'k' => $key,+'la' => $lang,+'vs' => LazyCollection::make(function () use ($key, $lang, $relativePath, $lines) {+foreach ($this->getDotted($key, $lang) as $key => $value) {+if (!array_key_exists($key, $lines) || is_array($value)) {+continue;+}++yield [+'k' => $key,+'arr' => [+$this->getValueIndex($value),+$relativePath,+$lines[$key],+$this->getParamIndex($value),+],+];+}+}),+];+}+};++echo json_encode([+'default' => App::currentLocale(),+'translations' => $translator->all(),+'languages' => $translator->languages,+'paths' => array_keys($translator->paths),+'values' => array_keys($translator->values),+'params' => array_map(fn ($p) => json_decode($p, true), array_keys($translator->paramResults)),+'to_watch' => $translator->directoriesToWatch,+], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);diff --git a/tests/Browser/ComposerUnsavedChangesTest.php b/tests/Browser/ComposerUnsavedChangesTest.phpindex b6827615a..8fb017a97 100644--- a/tests/Browser/ComposerUnsavedChangesTest.php+++ b/tests/Browser/ComposerUnsavedChangesTest.php@@ -181,7 +181,12 @@ test('after saving a post edited from the calendar, a channel drafts tab or the$page = visit(route('app.settings.preferences'))->resize(1280, 900)->navigate($list);$edit = $from === 'calendar' ? "@post-details-edit-{$post->id}" : "@post-edit-{$post->id}";waitFor($page, '@app-content-shell');- expect($page->script('document.querySelector(\'[data-testid="mcp-prompt"]\') !== null'))->toBe(! $aiConnected);+ if ($aiConnected) {+ letPageRun($page, 600);+ $page->assertMissing('@mcp-prompt');+ } else {+ waitFor($page, '@mcp-prompt');+ }if ($from === 'calendar') {waitFor($page, "@calendar-post-{$post->id}");$page->click("@calendar-post-{$post->id}");diff --git a/tests/Browser/Tours/InsightsFiltersTourTest.php b/tests/Browser/Tours/InsightsFiltersTourTest.phpnew file mode 100644index 000000000..9123e9b10--- /dev/null+++ b/tests/Browser/Tours/InsightsFiltersTourTest.php@@ -0,0 +1,289 @@+<?php++declare(strict_types=1);++use App\Enums\PostHog\TourEvent;+use App\Enums\User\Locale;+use App\Jobs\PostHog\CaptureAccountEvent;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ config(['trypost.tours.enabled' => true]);+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);++ $this->user = User::factory()->create(['timezone' => 'UTC', 'locale' => Locale::DEFAULT]);+ $workspace = Workspace::factory()->create(['user_id' => $this->user->id, 'account_id' => $this->user->account_id]);+ $workspace->members()->attach($this->user->id, membershipPivot('admin'));+ $this->user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($this->user->account);+ $this->user = $this->user->fresh();+ connectAiTo($this->user);++ $this->actingAs($this->user);+});++/**+ * Whether the end of the filters tour reached PostHog's queue with this+ * outcome and step.+ */+function insightsTourTracked(User $user, TourEvent $event, int $step): bool+{+ return Queue::pushed(CaptureAccountEvent::class, fn (CaptureAccountEvent $job): bool => $job->event === $event+ && $job->distinctId === (string) $user->id+ && $job->properties['tour'] === 'insights.filters'+ && $job->properties['step'] === $step+ && $job->properties['steps'] === 3)->isNotEmpty();+}++test('the filters tour walks the period, channels and labels with Next and Back, and Done completes it', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);++ waitForOpen($page, '@tour-insights-filters-range-content');+ $page->assertSeeIn('@tour-insights-filters-range-content', 'Filter by period')+ ->assertSeeIn('@tour-insights-filters-range-progress', '1 of 3')+ ->assertMissing('@tour-insights-filters-range-back')+ ->assertSeeIn('@tour-insights-filters-range-next', 'Next');++ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');+ waitForGone($page, '@tour-insights-filters-range-content');+ $page->assertSeeIn('@tour-insights-filters-channels-content', 'Filter by channel')+ ->assertSeeIn('@tour-insights-filters-channels-progress', '2 of 3');++ $page->click('@tour-insights-filters-channels-back');+ waitForOpen($page, '@tour-insights-filters-range-content');+ waitForGone($page, '@tour-insights-filters-channels-content');++ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');+ $page->click('@tour-insights-filters-channels-next');+ waitForOpen($page, '@tour-insights-filters-labels-content');+ $page->assertSeeIn('@tour-insights-filters-labels-content', 'Filter by label')+ ->assertSeeIn('@tour-insights-filters-labels-progress', '3 of 3')+ ->assertSeeIn('@tour-insights-filters-labels-next', 'Done');++ $page->click('@tour-insights-filters-labels-next');+ waitForGone($page, '@tour-insights-filters-labels-content');+ waitForGone($page, '@tour-backdrop');++ expect(browserStorageItem($page, $this->user, 'tours'))->toBe(['insights.filters' => ['status' => 'completed', 'step' => 3]]);+ waitForDatabase($page, fn (): bool => insightsTourTracked($this->user, TourEvent::Completed, 3));++ $page->navigate(route('app.insights'));+ waitFor($page, '@analytics-filters');+ $page->assertMissing('@tour-insights-filters-range-content');++ $page->assertNoJavaScriptErrors();+});++test('moving to the next step slides the one backdrop and its card to the next control together, instead of replacing them', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');+ rememberElement($page, '@tour-backdrop', 'backdrop');+ rememberElement($page, '@tour-insights-filters-range-content', 'card');++ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');+ waitForState($page, '@tour-backdrop', 'element === window.__remembered.backdrop && element.getBoundingClientRect().left > 640');+ waitForState($page, '@tour-insights-filters-channels-content', 'element === window.__remembered.card && element.getBoundingClientRect().left > 640');++ $page->assertNoJavaScriptErrors();+});++test('the arrow keys move a longer tour on and back, never past its first or last step, and leave it open for Done', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');++ $page->keys('@tour-insights-filters-range-content', 'ArrowLeft');+ letPageRun($page, 500);+ $page->assertVisible('@tour-insights-filters-range-content');++ $page->keys('@tour-insights-filters-range-content', 'ArrowRight');+ waitForOpen($page, '@tour-insights-filters-channels-content');+ waitForGone($page, '@tour-insights-filters-range-content');++ $page->keys('@tour-insights-filters-channels-content', 'ArrowLeft');+ waitForOpen($page, '@tour-insights-filters-range-content');++ $page->keys('@tour-insights-filters-range-content', 'ArrowRight');+ waitForOpen($page, '@tour-insights-filters-channels-content');+ $page->keys('@tour-insights-filters-channels-content', 'ArrowRight');+ waitForOpen($page, '@tour-insights-filters-labels-content');+ $page->keys('@tour-insights-filters-labels-content', 'ArrowRight');+ letPageRun($page, 500);++ $page->assertVisible('@tour-insights-filters-labels-content');+ expect(browserStorageItem($page, $this->user, 'tours'))->toBeNull();++ $page->click('@tour-insights-filters-labels-next');+ waitForGone($page, '@tour-backdrop');++ expect(browserStorageItem($page, $this->user, 'tours'))->toBe(['insights.filters' => ['status' => 'completed', 'step' => 3]]);++ $page->assertNoJavaScriptErrors();+});++test('picking a period from the highlighted control moves the tour on, and the visit it makes keeps it there', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');++ $page->click('@insights-range-7d');+ waitForQueryParameter($page, 'range', '7d');+ waitForOpen($page, '@tour-insights-filters-channels-content');+ letPageRun($page, 500);++ $page->assertVisible('@tour-insights-filters-channels-content')+ ->assertMissing('@tour-insights-filters-range-content');+ expect(browserStorageItem($page, $this->user, 'tours'))->toBeNull();++ $page->assertNoJavaScriptErrors();+});++test('a dialog opened over the tour puts it away, and the tour comes back at the same step once the dialog closes', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');+ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');++ $page->keys('@tour-insights-filters-channels-content', 'ControlOrMeta+k');+ waitFor($page, '@command-palette-input');+ waitForGone($page, '@tour-backdrop');+ expect(browserStorageItem($page, $this->user, 'tours'))->toBeNull();++ $page->keys('@command-palette-input', 'Escape');+ waitForGone($page, '@command-palette-input');+ waitForOpen($page, '@tour-insights-filters-channels-content');++ $page->assertNoJavaScriptErrors();+});++test('where one user left a tour is never where it opens for the next user signed in on the same tab', function () {+ $next = User::factory()->create(['timezone' => 'UTC', 'locale' => Locale::DEFAULT]);+ $workspace = Workspace::factory()->create(['user_id' => $next->id, 'account_id' => $next->account_id]);+ $workspace->members()->attach($next->id, membershipPivot('admin'));+ $next->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($next->account);+ connectAiTo($next->fresh());++ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');+ setBrowserStorageItem($page, $this->user, 'tours', ['publish.views' => ['status' => 'completed', 'step' => 1]]);+ announceBrowserStorageFromAnotherTab($page, $this->user);+ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');++ $page->keys('@tour-insights-filters-channels-content', 'ControlOrMeta+k');+ waitFor($page, '@command-palette-item-nav-publish');+ $page->click('@command-palette-item-nav-publish');+ waitForPath($page, route('app.posts.index', absolute: false));++ $page->click('@sidebar-workspace-menu');+ waitFor($page, '@logout-button');+ $page->click('@logout-button');+ waitFor($page, '@login-email');+ $page->type('@login-email', $next->email)+ ->type('@login-password', 'password')+ ->click('@login-submit');+ waitForOpen($page, '@tour-publish-views-views-content');+ $page->click('@tour-publish-views-views-next');+ waitForGone($page, '@tour-backdrop');++ $insightsPath = route('app.insights', absolute: false);+ $page->click("@nav-{$insightsPath}");+ waitForOpen($page, '@tour-insights-filters-range-content');+ $page->assertSeeIn('@tour-insights-filters-range-progress', '1 of 3');++ $page->assertNoJavaScriptErrors();+});++test('in a right-to-left language the left arrow moves the tour on and the right arrow moves it back', function () {+ $this->user->update(['locale' => Locale::Arabic]);++ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');++ $page->keys('@tour-insights-filters-range-content', 'ArrowLeft');+ waitForOpen($page, '@tour-insights-filters-channels-content');+ waitForGone($page, '@tour-insights-filters-range-content');++ $page->keys('@tour-insights-filters-channels-content', 'ArrowRight');+ waitForOpen($page, '@tour-insights-filters-range-content');+ waitForGone($page, '@tour-insights-filters-channels-content');++ $page->assertNoJavaScriptErrors();+});++test('a press on the highlighted control that never became a click does not move the tour on later', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');++ pointerDownOn($page, '@insights-range-presets');+ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');++ clickWithoutPointer($page, '@insights-range-presets');+ letPageRun($page, 500);++ $page->assertVisible('@tour-insights-filters-channels-content')+ ->assertMissing('@tour-insights-filters-labels-content');++ $page->assertNoJavaScriptErrors();+});++test('Skip tour on a middle step records the step reached', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');++ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');+ $page->click('@tour-insights-filters-channels-skip');+ waitForGone($page, '@tour-backdrop');++ expect(browserStorageItem($page, $this->user, 'tours'))->toBe(['insights.filters' => ['status' => 'skipped', 'step' => 2]]);+ waitForDatabase($page, fn (): bool => insightsTourTracked($this->user, TourEvent::Skipped, 2));++ $page->assertNoJavaScriptErrors();+});++test('leaving the page midway records nothing, so the tour opens again from its first step', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');+ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');++ $page->navigate(route('app.insights'));+ waitForOpen($page, '@tour-insights-filters-range-content');++ expect(browserStorageItem($page, $this->user, 'tours'))->toBeNull();++ $page->assertNoJavaScriptErrors();+});++test('narrowing the window to a phone hides the tour, and widening it opens the tour at the same step', function () {+ $page = visit(route('app.insights'))->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-range-content');+ $page->click('@tour-insights-filters-range-next');+ waitForOpen($page, '@tour-insights-filters-channels-content');++ $page->resize(390, 844);+ waitForGone($page, '@tour-backdrop');+ $page->assertMissing('@tour-insights-filters-channels-content');+ expect(browserStorageItem($page, $this->user, 'tours'))->toBeNull();++ $page->resize(1280, 900);+ waitForOpen($page, '@tour-insights-filters-channels-content');++ $page->assertNoJavaScriptErrors();+});++test('on a phone no tour opens', function () {+ $page = visit(route('app.insights'))->resize(390, 844);+ waitFor($page, '@analytics-filters');++ $page->assertMissing('@tour-insights-filters-range-content');++ $page->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/McpPromptCardTest.php b/tests/Browser/Tours/McpPromptTourTest.phpsimilarity index 65%rename from tests/Browser/McpPromptCardTest.phprename to tests/Browser/Tours/McpPromptTourTest.phpindex bb57ce7f2..842280857 100644--- a/tests/Browser/McpPromptCardTest.php+++ b/tests/Browser/Tours/McpPromptTourTest.php@@ -4,6 +4,7 @@ declare(strict_types=1);use App\Models\User;use App\Models\Workspace;+use Illuminate\Support\Str;function mcpPromptUser(array $attributes = []): User{@@ -26,7 +27,7 @@ function mcpPromptUser(array $attributes = []): User*/function mcpPromptAvatars(mixed $page): array{- return $page->script("[...document.querySelectorAll('[data-testid^=\"mcp-prompt-avatar-\"]')].map((avatar) => avatar.dataset.testid.replace('mcp-prompt-avatar-', ''))");+ return elementsMap($page, '@mcp-prompt-avatars [data-testid]', "element.dataset.testid.replace('mcp-prompt-avatar-', '')");}test('a new user is invited to connect an AI, and closing it hides it for good in that browser', function () {@@ -35,10 +36,13 @@ test('a new user is invited to connect an AI, and closing it hides it for good i$page = visit(route('app.calendar'))->resize(1280, 900);waitFor($page, '@mcp-prompt');+ $layers = elementsMap($page, '@mcp-prompt-avatars [data-testid]', 'Number(getComputedStyle(element).zIndex)');+expect(mcpPromptAvatars($page))->toBe(['chatgpt', 'claude', 'grok', 'gemini', 'cursor', 'n8n'])- ->and($page->script("(() => { const layers = [...document.querySelectorAll('[data-testid^=\"mcp-prompt-avatar-\"]')].map((avatar) => Number(getComputedStyle(avatar).zIndex)); return layers.every((layer, index) => index === 0 || layer < layers[index - 1]); })()"))->toBeTrue();+ ->and($layers)->toBe(collect($layers)->sortDesc()->values()->all())+ ->and(array_unique($layers))->toHaveCount(count($layers));- $page->assertSeeIn('@mcp-prompt', __('mcp.prompt.title'))+ $page->assertSeeIn('@mcp-prompt', __('tours.mcp.prompt.steps.card.title'))->click('@mcp-prompt-close');waitForGone($page, '@mcp-prompt');@@ -50,21 +54,77 @@ test('a new user is invited to connect an AI, and closing it hides it for good i->assertNoJavaScriptErrors();});+test('the card waits while a tour is open and shows once the tour closes', function () {+ config(['trypost.tours.enabled' => true]);+ $this->actingAs(mcpPromptUser());++ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitForOpen($page, '@tour-publish-views-views-content');+ $page->assertMissing('@mcp-prompt');++ $page->click('@tour-publish-views-views-next');+ waitForGone($page, '@tour-publish-views-views-content');+ waitFor($page, '@mcp-prompt');++ $page->assertNoJavaScriptErrors();+});++test('the card shows once a tour open here is closed in another tab', function () {+ config(['trypost.tours.enabled' => true]);+ $user = mcpPromptUser();+ $this->actingAs($user);++ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitForOpen($page, '@tour-publish-views-views-content');+ $page->assertMissing('@mcp-prompt');++ setBrowserStorageItem($page, $user, 'tours', ['publish.views' => ['status' => 'completed', 'step' => 1]]);+ announceBrowserStorageFromAnotherTab($page, $user);++ waitForGone($page, '@tour-backdrop');+ waitFor($page, '@mcp-prompt');++ $page->assertNoJavaScriptErrors();+});++test('answering where they found us opens the waiting tour first, and the card still waits for it', function () {+ config(['trypost.tours.enabled' => true]);+ $this->actingAs(mcpPromptUser(['referral_source' => null, 'created_at' => now()->subDays(2)]));++ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitFor($page, '@referral-source-survey');+ $page->assertMissing('@mcp-prompt')+ ->assertMissing('@tour-publish-views-views-content');++ $page->click('@referral-source-option-google');+ $page->click('@referral-source-submit');+ waitForOpen($page, '@tour-publish-views-views-content');+ letPageRun($page, 1000);++ $page->assertMissing('@mcp-prompt');++ $page->click('@tour-publish-views-views-next');+ waitFor($page, '@mcp-prompt');++ $page->assertNoJavaScriptErrors();+});+test('closing the card keeps it in the user\'s one browser storage key, leaving the workspaces block as it was', function () {$user = mcpPromptUser();$this->actingAs($user);- $key = "trypost:{$user->id}";$page = visit(route('app.calendar'))->resize(1280, 900);waitFor($page, '@mcp-prompt');- $page->script(sprintf("localStorage.setItem('%s', JSON.stringify({ version: 1, user: {}, workspaces: { kept: { note: true } } }))", $key));+ setBrowserStorageItem($page, $user, 'note', true, 'kept');$page->click('@mcp-prompt-close');waitForGone($page, '@mcp-prompt');- expect($page->script("Object.keys(localStorage).filter((key) => key.startsWith('trypost:') || key.startsWith('mcp.'))"))->toBe([$key])- ->and($page->script("JSON.parse(localStorage.getItem('{$key}'))"))->toBe([+ $appKeys = collect(localStorageKeys($page))->filter(fn (string $key): bool => Str::startsWith($key, ['trypost:', 'mcp.']))->values()->all();++ expect($appKeys)->toBe(["trypost:{$user->id}"])+ ->and(browserStorage($page, $user))->toBe(['version' => 1,- 'user' => ['mcp.promptDismissed' => true],+ 'user' => ['tours' => ['mcp.prompt' => ['status' => 'skipped', 'step' => 1]]],'workspaces' => ['kept' => ['note' => true]],]);$page->assertNoJavaScriptErrors();@@ -73,17 +133,11 @@ test('closing the card keeps it in the user\'s one browser storage key, leavingtest('closing the card in another tab hides it here at once', function () {$user = mcpPromptUser();$this->actingAs($user);- $key = "trypost:{$user->id}";$page = visit(route('app.calendar'))->resize(1280, 900);waitFor($page, '@mcp-prompt');- $page->script(sprintf(<<<'JS'- (() => {- const value = JSON.stringify({ version: 1, user: { 'mcp.promptDismissed': true }, workspaces: {} });- localStorage.setItem('%1$s', value);- window.dispatchEvent(new StorageEvent('storage', { key: '%1$s', newValue: value }));- })()- JS, $key));+ setBrowserStorageItem($page, $user, 'tours', ['mcp.prompt' => ['status' => 'skipped', 'step' => 1]]);+ announceBrowserStorageFromAnotherTab($page, $user);waitForGone($page, '@mcp-prompt');$page->assertMissing('@mcp-prompt')@@ -93,11 +147,10 @@ test('closing the card in another tab hides it here at once', function () {test('an unreadable, older or malformed browser storage value reads as empty and is replaced on the next save', function (string $stored, array $workspaces = []) {$user = mcpPromptUser();$this->actingAs($user);- $key = "trypost:{$user->id}";$page = visit(route('app.calendar'))->resize(1280, 900);waitFor($page, '@app-header');- $page->script(sprintf("localStorage.setItem('%s', %s)", $key, json_encode($stored)));+ setRawBrowserStorage($page, $user, $stored);$page->navigate(route('app.posts.index'));waitForPath($page, route('app.posts.index', absolute: false));waitFor($page, '@mcp-prompt');@@ -105,17 +158,17 @@ test('an unreadable, older or malformed browser storage value reads as empty and$page->click('@mcp-prompt-close');waitForGone($page, '@mcp-prompt');- expect($page->script("JSON.parse(localStorage.getItem('{$key}'))"))->toBe([+ expect(browserStorage($page, $user))->toBe(['version' => 1,- 'user' => ['mcp.promptDismissed' => true],+ 'user' => ['tours' => ['mcp.prompt' => ['status' => 'skipped', 'step' => 1]]],'workspaces' => $workspaces,]);$page->assertNoJavaScriptErrors();})->with(['not JSON' => ['not json'],- 'an older version' => ['{"version":0,"user":{"mcp.promptDismissed":true},"workspaces":{}}'],+ 'an older version' => ['{"version":0,"user":{"tours":{"mcp.prompt":{"status":"skipped","step":1}}},"workspaces":{}}'],'no user or workspaces block' => ['{"version":1}'],- 'an item of the wrong shape' => ['{"version":1,"user":{"mcp.promptDismissed":"yes"},"workspaces":{}}'],+ 'an item of the wrong shape' => ['{"version":1,"user":{"tours":"yes"},"workspaces":{}}'],'a list instead of the value' => ['[1]'],'a user block that is not an object' => ['{"version":1,"user":"dismissed","workspaces":{}}'],'a workspace block that is not an object' => ['{"version":1,"user":{},"workspaces":{"workspace-a":"draft"}}', ['workspace-a' => []]],@@ -126,19 +179,11 @@ test('a browser that refuses storage still shows the card and closes it, on the$page = visit(route('app.calendar'))->resize(1280, 900);waitFor($page, '@app-header');- $page->script(<<<'JS'- (() => {- const refuse = () => { throw new DOMException('denied', 'SecurityError'); };- Storage.prototype.getItem = refuse;- Storage.prototype.setItem = refuse;- })()- JS);+ refuseBrowserStorage($page);$page->click('@sidebar-logo');waitForPath($page, route('app.posts.index', absolute: false));waitFor($page, '@mcp-prompt');- expect($page->script("(() => { try { localStorage.getItem('x'); return 'allowed'; } catch { return 'refused'; } })()"))->toBe('refused');-$page->click('@mcp-prompt-close');waitForGone($page, '@mcp-prompt');@@ -194,7 +239,7 @@ test('the steps stay open while nothing connected, even when the account loses awaitFor($page, '@mcp-dialog');$user->account->subscriptions()->delete();- $page->script('new Promise((resolve) => setTimeout(resolve, 4500))');+ letPageRun($page, 4500);$page->assertVisible('@mcp-dialog')->assertNoJavaScriptErrors();diff --git a/tests/Browser/Tours/PublishViewsTourTest.php b/tests/Browser/Tours/PublishViewsTourTest.phpnew file mode 100644index 000000000..bbb8fb135--- /dev/null+++ b/tests/Browser/Tours/PublishViewsTourTest.php@@ -0,0 +1,196 @@+<?php++declare(strict_types=1);++use App\Enums\PostHog\TourEvent;+use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use App\Enums\User\Locale;+use App\Jobs\PostHog\CaptureAccountEvent;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ config(['trypost.tours.enabled' => true]);++ $this->user = User::factory()->create(['timezone' => 'UTC', 'locale' => Locale::DEFAULT]);+ $workspace = Workspace::factory()->create(['user_id' => $this->user->id, 'account_id' => $this->user->account_id]);+ $workspace->members()->attach($this->user->id, membershipPivot('admin'));+ $this->user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($this->user->account);+ $this->user = $this->user->fresh();+ connectAiTo($this->user);++ $this->actingAs($this->user);+});++/**+ * Whether the end of the views tour reached PostHog's queue with this outcome+ * and step.+ */+function tourTracked(User $user, TourEvent $event, int $step): bool+{+ return Queue::pushed(CaptureAccountEvent::class, fn (CaptureAccountEvent $job): bool => $job->event === $event+ && $job->distinctId === (string) $user->id+ && $job->properties['tour'] === 'publish.views'+ && $job->properties['step'] === $step+ && $job->properties['steps'] === 1)->isNotEmpty();+}++test('the views tour opens over a dark page once: "Got it" completes it on every page that has the view switch', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);++ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitForOpen($page, '@tour-publish-views-views-content');+ waitFor($page, '@tour-backdrop');++ rememberElement($page, '@tour-backdrop', 'backdrop');+ waitForState($page, '@tour-publish-views-views-content', "Number(getComputedStyle(element.closest('[data-reka-popper-content-wrapper]')).zIndex) > Number(getComputedStyle(window.__remembered.backdrop).zIndex)");++ $page->assertSeeIn('@tour-publish-views-views-content', 'Switch views');+ $page->assertMissing('@tour-publish-views-views-tag');+ $page->assertMissing('@tour-publish-views-views-progress');++ $page->click('@tour-publish-views-views-next');+ waitForGone($page, '@tour-publish-views-views-content');+ waitForGone($page, '@tour-backdrop');++ expect(browserStorageItem($page, $this->user, 'tours'))->toBe(['publish.views' => ['status' => 'completed', 'step' => 1]]);+ waitForDatabase($page, fn (): bool => tourTracked($this->user, TourEvent::Completed, 1));++ $page->click('@schedule-view-calendar');+ waitForPath($page, route('app.calendar', ['view' => 'week'], absolute: false));+ waitFor($page, '@schedule-view-board');+ $page->assertMissing('@tour-publish-views-views-content');++ $page->assertNoJavaScriptErrors();+});++test('closing the tour with Escape skips it for good', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);++ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitForOpen($page, '@tour-publish-views-views-content');++ $page->keys('@tour-publish-views-views-content', 'Escape');+ waitForGone($page, '@tour-backdrop');++ expect(browserStorageItem($page, $this->user, 'tours'))->toBe(['publish.views' => ['status' => 'skipped', 'step' => 1]]);+ waitForDatabase($page, fn (): bool => tourTracked($this->user, TourEvent::Skipped, 1));++ $page->navigate(route('app.posts.index'));+ waitFor($page, '@schedule-view-board');+ $page->assertMissing('@tour-publish-views-views-content');++ $page->assertNoJavaScriptErrors();+});++test('using the control the tour points at works and completes the tour', function () {+ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitForOpen($page, '@tour-publish-views-views-content');++ $page->click('@schedule-view-calendar');+ waitForPath($page, route('app.calendar', ['view' => 'week'], absolute: false));+ waitForGone($page, '@tour-backdrop');++ expect(browserStorageItem($page, $this->user, 'tours'))->toBe(['publish.views' => ['status' => 'completed', 'step' => 1]]);++ $page->assertNoJavaScriptErrors();+});++test('a click elsewhere on the page leaves the tour open', function () {+ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitForOpen($page, '@tour-publish-views-views-content');++ pointerDownOn($page, '@app-header');+ letPageRun($page, 500);++ $page->assertVisible('@tour-publish-views-views-content')+ ->assertVisible('@tour-backdrop');+ expect(browserStorageItem($page, $this->user, 'tours'))->toBeNull();++ $page->assertNoJavaScriptErrors();+});++test('the tour stays closed on a channel\'s Instagram grid, whose switch has a fourth view, and opens on the list of all channels', function () {+ $instagram = SocialAccount::factory()->create([+ 'workspace_id' => $this->user->current_workspace_id,+ 'platform' => Platform::Instagram,+ ]);++ $page = visit(route('app.channels.grid', $instagram))->resize(1280, 900);+ waitFor($page, '@schedule-view-board');+ $page->assertMissing('@tour-publish-views-views-content');++ $page->navigate(route('app.posts.index'));+ waitForOpen($page, '@tour-publish-views-views-content');++ $page->assertNoJavaScriptErrors();+});++test('the tour waits while a post opens in the composer, and opens once it closes', function () {+ $channel = SocialAccount::factory()->create([+ 'workspace_id' => $this->user->current_workspace_id,+ 'platform' => Platform::LinkedIn,+ ]);+ $post = Post::factory()->forAccount($channel, ContentType::LinkedInPost)->create([+ 'user_id' => $this->user->id,+ 'content' => 'Waiting for the composer',+ ]);++ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);+ waitForOpen($page, '@post-composer-dialog');+ letPageRun($page, 500);+ $page->assertMissing('@tour-publish-views-views-content');++ $page->click('@composer-close');+ waitForGone($page, '@post-composer-dialog');+ waitForOpen($page, '@tour-publish-views-views-content');++ $page->assertNoJavaScriptErrors();+});++test('the tour waits while the user is asked where they found us, and opens once they answer', function () {+ config(['trypost.self_hosted' => false]);+ $this->user->forceFill(['referral_source' => null, 'created_at' => now()->subDays(2)])->save();++ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitFor($page, '@referral-source-survey');+ letPageRun($page, 500);+ $page->assertMissing('@tour-publish-views-views-content');++ $page->click('@referral-source-option-google');+ $page->click('@referral-source-submit');+ waitForGone($page, '@referral-source-survey');+ waitForOpen($page, '@tour-publish-views-views-content');++ $page->assertNoJavaScriptErrors();+});++test('closing the tour in another tab closes it here at once', function () {+ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitForOpen($page, '@tour-publish-views-views-content');++ setBrowserStorageItem($page, $this->user, 'tours', ['publish.views' => ['status' => 'completed', 'step' => 1]]);+ announceBrowserStorageFromAnotherTab($page, $this->user);++ waitForGone($page, '@tour-publish-views-views-content');+ waitForGone($page, '@tour-backdrop');++ $page->assertNoJavaScriptErrors();+});++test('tours stay closed when they are turned off', function () {+ config(['trypost.tours.enabled' => false]);++ $page = visit(route('app.posts.index'))->resize(1280, 900);+ waitFor($page, '@schedule-view-board');+ $page->assertMissing('@tour-publish-views-views-content');++ $page->assertNoJavaScriptErrors();+});diff --git a/tests/Feature/TourTest.php b/tests/Feature/TourTest.phpnew file mode 100644index 000000000..5c8a7a28a--- /dev/null+++ b/tests/Feature/TourTest.php@@ -0,0 +1,75 @@+<?php++declare(strict_types=1);++use App\Enums\PostHog\TourEvent;+use App\Jobs\PostHog\CaptureAccountEvent;+use App\Models\Account;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ $this->user = User::factory()->create();+ $this->workspace = Workspace::factory()->create([+ 'account_id' => $this->user->account_id,+ 'user_id' => $this->user->id,+ ]);+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));+ $this->user->update(['current_workspace_id' => $this->workspace->id]);+ subscribeAccount($this->user->account);+});++test('how a tour ended is tracked for the workspace account, with the step reached', function (string $outcome, TourEvent $event, int $step) {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);++ $this->actingAs($this->user)+ ->post(route('app.tours.store'), ['tour' => 'publish.views', 'outcome' => $outcome, 'step' => $step, 'steps' => 3])+ ->assertNoContent();++ Queue::assertPushedOn('posthog', CaptureAccountEvent::class, fn (CaptureAccountEvent $job): bool => $job->event === $event+ && $job->distinctId === (string) $this->user->id+ && $job->accountId === (string) $this->workspace->account_id+ && $job->properties === ['tour' => 'publish.views', 'step' => $step, 'steps' => 3, 'workspace_id' => $this->workspace->id]);+})->with([+ 'completed' => ['completed', TourEvent::Completed, 3],+ 'skipped' => ['skipped', TourEvent::Skipped, 2],+]);++test('an unknown tour or outcome, or a step past the last, is refused and tracks nothing', function (array $payload, string $field) {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);++ $this->actingAs($this->user)+ ->postJson(route('app.tours.store'), [...['tour' => 'publish.views', 'outcome' => 'completed', 'step' => 1, 'steps' => 1], ...$payload])+ ->assertUnprocessable()+ ->assertJsonValidationErrors($field);++ Queue::assertNotPushed(CaptureAccountEvent::class);+})->with([+ 'unknown tour' => [['tour' => 'publish.unknown'], 'tour'],+ 'unknown outcome' => [['outcome' => 'closed'], 'outcome'],+ 'step past the last' => [['step' => 3, 'steps' => 2], 'step'],+ 'no step' => [['step' => 0], 'step'],+]);++test('the queued job hands the end of a tour to PostHog for the user and their account', function (string $outcome, string $event, int $step) {+ enablePostHog();++ $this->mock(PostHogService::class)+ ->shouldReceive('capture')+ ->once()+ ->withArgs(fn (string $distinctId, string $sent, array $properties, ?Account $account): bool => $distinctId === (string) $this->user->id+ && $sent === $event+ && $properties === ['tour' => 'insights.filters', 'step' => $step, 'steps' => 3, 'workspace_id' => $this->workspace->id]+ && $account?->is($this->user->account) === true);++ $this->actingAs($this->user)+ ->post(route('app.tours.store'), ['tour' => 'insights.filters', 'outcome' => $outcome, 'step' => $step, 'steps' => 3])+ ->assertNoContent();+})->with([+ 'completed' => ['completed', 'tour.completed', 3],+ 'skipped' => ['skipped', 'tour.skipped', 2],+]);diff --git a/tests/Pest.php b/tests/Pest.phpindex 089fc082e..dfe1ab9e3 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -50,7 +50,10 @@ pest()->extend(TestCase::class)pest()->extend(BrowserTestCase::class)->use(RefreshDatabase::class)- ->beforeEach(fn () => fakePwnedPasswords())+ ->beforeEach(function (): void {+ fakePwnedPasswords();+ config(['trypost.tours.enabled' => false]);+ })->in('Browser');pest()->in('Feature/Social')@@ -575,7 +578,7 @@ function mcpAccessToken(/*** Connects an AI to the user's current workspace, as connecting one through- * MCP does, so the in-app invitation to connect one (`McpPromptCard`) is not+ * MCP does, so the in-app invitation to connect one (`McpPromptTour`) is not* shown. A browser test whose page should not carry the card calls it.*/function connectAiTo(User $user): void@@ -788,13 +791,33 @@ function jsSelector(string $selector): string/*** Wait until the note editor matching the selector shows that text, trimmed.- * The editor is a contenteditable, so it has no value to assert.+ * The editor is a contenteditable, so it has no value to assert. When it never+ * does, the failure says what the editor shows instead and where the focus is.*/function waitForEditorText(mixed $page, string $selector, string $text): void{- $text = json_encode($text, JSON_THROW_ON_ERROR);+ $expected = json_encode($text, JSON_THROW_ON_ERROR);+ $element = 'document.querySelector('.jsSelector($selector).')';++ $result = $page->script(<<<JS+ (async () => {+ const read = () => {$element}?.innerText.trim() ?? null;++ for (let i = 0; i < 600; i++) {+ if (read() === {$expected}) return { met: true };+ await new Promise((resolve) => setTimeout(resolve, 50));+ }++ const focused = document.activeElement;++ return { met: false, shown: read(), focus: focused?.dataset?.testid ?? focused?.tagName ?? null };+ })();+ JS);++ $shown = json_encode(data_get($result, 'shown'), JSON_UNESCAPED_UNICODE);+ $focus = json_encode(data_get($result, 'focus'));- waitForState($page, $selector, "element.innerText.trim() === {$text}");+ expect(data_get($result, 'met'))->toBeTrue("Waited 30s for {$selector} to show {$expected}; it shows {$shown}, with the focus on {$focus}.");}/**@@ -808,6 +831,36 @@ function waitForState(mixed $page, string $selector, string $expression, int $sewaitForCondition($page, "((element) => element && ({$expression}))(document.querySelector({$selector}))", $seconds);}+/**+ * Keeps the element matching the selector as `window.__remembered[$name]`, so+ * a later wait can tell whether the page still shows that same element+ * (`element === window.__remembered.<name>`) or replaced it.+ */+function rememberElement(mixed $page, string $selector, string $name): void+{+ waitFor($page, $selector);++ $selector = jsSelector($selector);+ $name = json_encode($name);++ $page->script("(() => { window.__remembered = { ...window.__remembered, [{$name}]: document.querySelector({$selector}) }; })()");+}++/**+ * Presses the pointer down on the element matching the selector, the start of+ * a click: an open modal layer takes the pointer events of the page around+ * it, so a real click cannot reach that element, while the layer still hears+ * the press as one outside it.+ */+function pointerDownOn(mixed $page, string $selector): void+{+ waitFor($page, $selector);++ $selector = jsSelector($selector);++ $page->script("document.querySelector({$selector}).dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))");+}+/*** Wait until an element matching the selector is mounted and laid out.*/@@ -900,6 +953,106 @@ function browserStorageItem(mixed $page, User $user, string $item, ?string $workreturn $page->script(browserStorageItemJs($user, $item, $workspaceId));}+/**+ * The whole value of a user's browser storage key (`trypost:<user id>`), as+ * the page keeps it, or null when it holds none or no JSON.+ */+function browserStorage(mixed $page, User $user): mixed+{+ $key = json_encode("trypost:{$user->id}");++ return $page->script("(() => { try { return JSON.parse(localStorage.getItem({$key})); } catch { return null; } })()");+}++/**+ * Every key the page keeps in its localStorage.+ *+ * @return list<string>+ */+function localStorageKeys(mixed $page): array+{+ return $page->script('Object.keys(localStorage)');+}++/**+ * Writes a raw text as a user's browser storage value, for the values the app+ * must read past (not JSON, another version, a wrong shape); a well-formed+ * item goes through `setBrowserStorageItem()`.+ */+function setRawBrowserStorage(mixed $page, User $user, string $raw): void+{+ $key = json_encode("trypost:{$user->id}");+ $raw = json_encode($raw);++ $page->script("localStorage.setItem({$key}, {$raw})");+}++/**+ * Makes the page's browser refuse its storage from now on, as a private+ * window or blocked site data does, and fails when it still allows it.+ */+function refuseBrowserStorage(mixed $page): void+{+ $page->script(<<<'JS'+ (() => {+ const refuse = () => { throw new DOMException('denied', 'SecurityError'); };+ Storage.prototype.getItem = refuse;+ Storage.prototype.setItem = refuse;+ })()+ JS);++ expect($page->script("(() => { try { localStorage.getItem('x'); return 'allowed'; } catch { return 'refused'; } })()"))->toBe('refused');+}++/**+ * The value of an expression about `element` for every element matching the+ * selector, in page order.+ *+ * @return list<mixed>+ */+function elementsMap(mixed $page, string $selector, string $expression): array+{+ $selector = jsSelector($selector);++ return $page->script("[...document.querySelectorAll({$selector})].map((element) => ({$expression}))");+}++/**+ * Lets the page run for a while without waiting on anything, to show that+ * something stays as it is (a dialog left open across polls). Never a+ * PHP `sleep()`, which would stop the page's own requests.+ */+function letPageRun(mixed $page, int $milliseconds): void+{+ $page->script("new Promise((resolve) => setTimeout(resolve, {$milliseconds}))");+}++/**+ * Fires a click on the element matching the selector without moving the+ * pointer there, for an element an open modal layer keeps out of the+ * pointer's reach (a click through `$page->click()` would never land).+ */+function clickWithoutPointer(mixed $page, string $selector): void+{+ waitFor($page, $selector);++ $selector = jsSelector($selector);++ $page->script("document.querySelector({$selector}).click()");+}++/**+ * Tells the page that the user's browser storage changed in another tab, as+ * the browser does with a `storage` event: seed the change with+ * `setBrowserStorageItem()` first.+ */+function announceBrowserStorageFromAnotherTab(mixed $page, User $user): void+{+ $key = json_encode("trypost:{$user->id}");++ $page->script("window.dispatchEvent(new StorageEvent('storage', { key: {$key}, newValue: localStorage.getItem({$key}) }))");+}+/*** Saves one item of a user's browser storage the way the app does, keeping* every other item.diff --git a/tests/Unit/ToursTest.php b/tests/Unit/ToursTest.phpnew file mode 100644index 000000000..a7f121d1b--- /dev/null+++ b/tests/Unit/ToursTest.php@@ -0,0 +1,70 @@+<?php++declare(strict_types=1);++use App\Enums\Tour\Tour;+use Illuminate\Support\Facades\Lang;+use Symfony\Component\Process\ExecutableFinder;+use Symfony\Component\Process\Process;++/**+ * Runs `tests/fixtures/tours-harness.ts` over `resources/js/lib/tours.ts`.+ *+ * @param list<array{steps: list<string>, onPage: list<string>, current: string}> $cases+ * @return array{tours: array<string, list<string>>, cases: list<array{shown: list<string>, first: ?string, after: ?string, before: ?string}>}+ */+function runToursHarness(array $cases = []): array+{+ $node = (new ExecutableFinder)->find('node');++ if ($node === null) {+ test()->markTestSkipped('node is unavailable');+ }++ $process = (new Process([+ $node,+ base_path('tests/fixtures/tours-harness.ts'),+ resource_path('js/lib/tours.ts'),+ json_encode($cases),+ ]))->mustRun();++ return json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);+}++test('a tour opens on its first step on the page and walks its steps in its own order, skipping the ones not on the page', function () {+ $cases = [+ ['steps' => ['one', 'two', 'three'], 'onPage' => ['three', 'one', 'two'], 'current' => 'one'],+ ['steps' => ['one', 'two', 'three'], 'onPage' => ['one', 'two', 'three'], 'current' => 'two'],+ ['steps' => ['one', 'two', 'three'], 'onPage' => ['one', 'two', 'three'], 'current' => 'three'],+ ['steps' => ['one', 'two', 'three'], 'onPage' => ['one', 'three'], 'current' => 'one'],+ ['steps' => ['one'], 'onPage' => ['one'], 'current' => 'one'],+ ['steps' => ['one', 'two'], 'onPage' => ['two'], 'current' => 'two'],+ ['steps' => ['one', 'two'], 'onPage' => [], 'current' => 'one'],+ ];++ expect(runToursHarness($cases)['cases'])->toBe([+ ['shown' => ['one', 'two', 'three'], 'first' => 'one', 'after' => 'two', 'before' => null],+ ['shown' => ['one', 'two', 'three'], 'first' => 'one', 'after' => 'three', 'before' => 'one'],+ ['shown' => ['one', 'two', 'three'], 'first' => 'one', 'after' => null, 'before' => 'two'],+ ['shown' => ['one', 'three'], 'first' => 'one', 'after' => 'three', 'before' => null],+ ['shown' => ['one'], 'first' => 'one', 'after' => null, 'before' => null],+ ['shown' => ['two'], 'first' => 'two', 'after' => null, 'before' => null],+ ['shown' => [], 'first' => null, 'after' => null, 'before' => null],+ ]);+});++test('the tours of the frontend are the tours of the backend, and each of their steps has its copy', function () {+ $tours = runToursHarness()['tours'];+ $names = array_map(fn (Tour $tour): string => $tour->value, Tour::cases());++ expect(array_keys($tours))->toEqualCanonicalizing($names);++ foreach ($tours as $tour => $steps) {+ expect(array_keys(Lang::get("tours.{$tour}.steps", [], 'en')))->toBe($steps);++ foreach ($steps as $step) {+ expect(Lang::has("tours.{$tour}.steps.{$step}.title", 'en', false))->toBeTrue()+ ->and(Lang::has("tours.{$tour}.steps.{$step}.description", 'en', false))->toBeTrue();+ }+ }+});diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.phpindex 583cce428..1c1ce52c2 100644--- a/tests/fixtures/single-line-copy.php+++ b/tests/fixtures/single-line-copy.php@@ -164,6 +164,12 @@ return ['posts.form.google_business.topic_type.offer' => 11,'posts.form.google_business.topic_type.standard' => 14,'posts.form.instagram.collaborators.got_it' => 10,+ 'tours.tags.new' => 7,+ 'tours.actions.got_it' => 10,+ 'tours.actions.back' => 8,+ 'tours.actions.next' => 9,+ 'tours.actions.done' => 8,+ 'tours.actions.skip' => 13,'posts.form.instagram.collaborators.label' => 16,'posts.form.instagram.music.add' => 16,'posts.form.instagram.music.audio_volume' => 8,@@ -258,7 +264,7 @@ return ['mcp.connect_other' => 10,'mcp.tabs.connected' => 23,'mcp.tabs.connect' => 21,- 'mcp.prompt.not_now' => 11,+ 'tours.mcp.prompt.steps.card.not_now' => 11,'mcp.connect' => 13,'mcp.copy' => 10,'mcp.copied' => 11,diff --git a/tests/fixtures/tours-harness.ts b/tests/fixtures/tours-harness.tsnew file mode 100644index 000000000..1db561c6b--- /dev/null+++ b/tests/fixtures/tours-harness.ts@@ -0,0 +1,35 @@+/**+ * Prints `TOURS` of `resources/js/lib/tours.ts` and its step navigation over+ * the cases in a JSON argument, as JSON, so `ToursTest.php` can check them.+ * Node strips the types, so the source is loaded as-is.+ */+import path from 'node:path';+import { pathToFileURL } from 'node:url';++const [sourceFile, casesJson] = process.argv.slice(2);++const { TOURS, firstStep, shownSteps, stepAfter, stepBefore } = await import(+ pathToFileURL(path.resolve(sourceFile)).href+);++const cases = JSON.parse(casesJson) as {+ steps: string[];+ onPage: string[];+ current: string;+}[];++console.log(+ JSON.stringify({+ tours: TOURS,+ cases: cases.map(({ steps, onPage, current }) => {+ const shown = shownSteps(steps, onPage);++ return {+ shown,+ first: firstStep(shown),+ after: stepAfter(shown, current),+ before: stepBefore(shown, current),+ };+ }),+ }),+);