Commit Graph

20 Commits

Author SHA1 Message Date
Carel de Waal
0acc0eb8b3 feat: Support Form - Sync AI assistant conversation to Front (#46778)
# Sync AI assistant conversation to Front

## What & why

When a user submits a support ticket, an AI assistant chat opens so they
get help
immediately while waiting for a human agent. This PR mirrors every turn
of that chat into
the Front conversation the support form already created, so the support
team sees the full
context and Front automations (routing, emails, CSAT) can act on it.

Studio holds no Front credentials — it calls the platform endpoints (see
the platform PR)
to do the syncing. The assistant card is gated behind the
`supportAssistantFollowUp`
ConfigCat flag.

## How it works

1. **Submit** — `SupportFormV3` generates a stable `threadRef` (via the
`uuid` package —
`crypto.randomUUID()` is `undefined` in insecure contexts like
non-localhost HTTP and
would throw, silently aborting the submit) and sends it on
`/platform/feedback/send`.
The response returns the Front `conversationId`. Both are stored on
`SubmittedSupportRequest`.
2. **Open chat** — `SupportAssistantSuccessCardContent` opens a chat
seeded with
`supportMetadata` (`threadRef`, `frontConversationId`, subject,
category, severity, …).
   The first message is a `<support>…</support>` XML block.
3. **First user message** — the chat is tagged `isSupportChat = true`;
the `onFinish` hook
   fires `syncSupportChatToFront`.
4. **Subsequent turns** — each `onFinish` slices the unsynced delta,
strips the XML
metadata block from the seed message, and posts to the platform messages
endpoint.
5. **Escalation / resolve** — the `escalate_to_human` /
`resolve_support_conversation` tools
(and manual **Escalate**/**Resolve** buttons in the assistant input)
flip lifecycle status
via `setSupportLifecycleStatus` → `syncSupportLifecycleToFront`, which
calls the
escalation/resolve endpoints. Front rules act on `ai_support_status`.
The assistant only
   resolves after the user explicitly confirms the issue is fixed.

## Key design decisions

- **`threadRef` as the shared key** — one UUID travels as `threadRef` on
submit and as
`chatId` on every sync, so all messages thread into a single Front
conversation.
- **`conversationId` from the form response** — passed to all
sync/lifecycle calls so the
  platform skips lazy derivation and PATCHes custom fields directly.
- **Delta-only sync** — `lastSyncedMessageCount` tracks what's been
sent; the boundary is
snapshotted before the async call to avoid skipping messages that arrive
mid-flight.
- **Server-side de-dup** — stable `external_id` (`chatId:msg.id`) means
retries don't
  duplicate in Front.
- **Fire-and-forget** — sync failures log to Sentry, never break the
chat; `isSyncing`
resets on rehydration so the next `onFinish` retries the same delta.
Message and lifecycle
syncs use separate guards (`isSyncing` / `isLifecycleSyncing`) so an
in-flight message
  sync can't drop an escalate/resolve.
- **Lifecycle queued until the conversation exists** — if a lifecycle
transition is requested
before the initial message sync has returned a `frontConversationId`,
it's stored as
`pendingLifecycleStatus` and flushed once the id is assigned, rather
than dropped.
- **Tools return immediately** — the lifecycle tools return a stub to
the AI SDK; the real
Front call happens in `onFinish`, keeping async I/O out of the tool
execute path.
- **XML seed stripped before sync** — only the user's actual `<message>`
is sent to Front
  (or dropped entirely if the form already created the conversation).

## Changes

| Area | File(s) |
| --- | --- |
| Support form state | `SupportForm.state.ts` — `threadRef` /
`frontConversationId` on `SubmittedSupportRequest` |
| Support form submit | `support-ticket-send.ts` — sends `threadRef`,
reads `conversationId` |
| Support form UI | `SupportFormV3.tsx` — generates `threadRef`, stores
`conversationId` |
| AI assistant state | `ai-assistant-state.tsx` — `SupportChatMetadata`,
`setSupportLifecycleStatus`, `onFinish` wiring, tool handling |
| Message sync | `state/ai-chat-front-sync.ts` — delta tracking, message
filtering, initial vs. incremental |
| API data layer | `data/feedback/ai-chat-front-sync.ts` — typed
platform-client wrappers for the three conversation endpoints |
| Support tools | `lib/ai/tools/support-tools.ts` — `escalate_to_human`,
`resolve_support_conversation` |
| Tool integration | `lib/ai/tool-filter.ts`, `tools/index.ts`,
`generate-assistant-response.ts` |
| Success card | `SupportAssistantSuccessCardContent.tsx` — tags chat on
first engagement |
| Assistant panel UI | `AIAssistant.tsx` — Escalate/Resolve buttons,
disabled input on closed chats, support placeholders |



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

## Summary by CodeRabbit

- **New Features**
  - Support chats now include “Escalate to human” and “Resolve” actions.
- Support submissions can be associated with a stable Front thread via a
generated `threadRef`, preserving linkage across follow-ups.
- AI assistant responses and input hints adapt when support mode is
active.

- **Bug Fixes**
- Improved support chat state management and lifecycle handling to keep
conversation metadata and message history synchronized more reliably
with Front.

- **Chores**
- Added/updated coverage to reflect the new support-chat state and
syncing behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-07-08 12:41:53 +02:00
Jordi Enric
42ca11f89e fix(support): handle rate-limited support submissions gracefully (#46928)
## Problem

When a support ticket submission is rejected by the API's rate limiter,
the form surfaced the raw server exception text to the user and reported
every rejection as an application error. This produced a steady stream
of noisy error reports for what is actually expected, recoverable
behavior.

The rejections are not random: the submit endpoint allows only a small
number of requests in a short window, so a quick second submission (a
fast retry or a follow-up ticket moments later) gets rejected. The first
submission usually succeeds; it's the immediate follow-up that fails.
Surfacing the raw error and logging it made this look worse than it is.

Separately, the success screen had only top padding, leaving its actions
flush against the bottom edge of the card.

## Fix

- Detect the rate-limit response and show a clear, friendly message that
tells the user how long to wait before trying again, instead of the raw
exception text.
- Stop reporting rate-limit rejections as errors to our monitoring. They
are expected and recoverable, so they no longer add noise.
- Give the success state the same vertical padding as the rest of the
form so its actions are not flush against the card edge.

## How to test

- Open the support form and simulate a 429 from the submit endpoint.
- Expected: a friendly message telling the user when they can retry, and
no error reported to monitoring.
- Submit a ticket successfully and confirm the success screen has even
padding above and below its content.

## Notes

This covers the user-facing handling. The rate-limit threshold itself is
tuned conservatively on the API and can be revisited separately so that
ordinary, legitimate resubmissions are not caught.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Improved support form handling for rate-limited (429) submissions by
suppressing unnecessary error reporting while still showing the error
and returning the form to editing.
* Fixed inconsistent support form spacing so padding is consistent
regardless of submission outcome.
* **Improvements**
* Propagated backend error `code` through the support-ticket submission
flow so the UI can react more intelligently to failures (including 429
retry-window messaging).
* Enhanced retry timing extraction for rate-limited errors by using
`Retry-After` with a fallback to rate-limit reset data.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 14:58:48 +00:00
Charis
3b7052b5a9 cleanup: fix import order and prefixes for studio/data (#44501) 2026-04-03 09:15:57 +02:00
Charis
9caa0d548a feat(studio): clean up support form message (#42174)
* feat(studio): clean up support form message

Support form message currently has the studio version and dashboard logs
link appended to the end. On request from the Support team, we're moving
this to metadata fields so it won't be as distracting.

* Hide IncidentAdmonition if event is maintenance

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-01-27 08:50:52 -05:00
barcofourie
f5d9cb1b60 feat: adds link conversation support form (#40553)
* feat: adds link conversation support form

* style: fixes prettier styling issues

* fix: type checking errors

* feat: adds redirect to 404 for self hosted

* style: prettier formatting
2025-11-20 08:23:20 -07:00
Ivan Vasilov
8b657165b5 chore: Migrate to use custom type for ReactQuery queries and mutations (#40073)
* Add custom types for queries, mutations and infinite queries.

* Migrate all queries to use the new type.

* Migrate all infinite queries to useCustomInfiniteQueryOptions.

* Migrate all mutations to use useCustomMutationOptions.

* Add type to all imports in `types` folder.
2025-11-03 13:18:13 +01:00
Alaister Young
8855d05803 chore(studio): swap react-query to object syntax (#39842)
* chore(studio): swap react-query to object syntax

* Fix small issues found

* Fix realtime settings

* Nit

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-10-27 09:38:27 +01:00
Charis
f5ff10e195 refactor,tests(support form) (#39410)
* refactor: refactor support form

Refactor support form to make it easier to maintain:
- Split up large components into smaller components and hooks
- Lift state up so we don't have to do complex child/parent
state-syncing via useEffect
- Use nuqs parsing for consistent serialization/deserialization of
support form prefilled fields

* test: support form

Add comprehensive tests for support form

* fix(support form): project and org empty state

* Nit clean up

* More clean up

* cleannnn

* fix(support form): allow case-insensitive category in url

* clean(support form tests): remove unused param

* fix(support form): incorrect logic for sending affected services in payload

* clean(support form): use NO_ORG_MARKER and NO_PROJECT_MARKER instead of strings

* fix(support form): don't show upgrade cta if already on enterprise

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-10-14 11:04:33 +08:00
Ivan Vasilov
260d770148 Revert "Add sample rate to fetcher" (#39209)
Revert "Add sample rate to fetcher (#38785)"

This reverts commit 506b20734f.
2025-10-03 10:26:22 +02:00
Jordi Enric
506b20734f Add sample rate to fetcher (#38785)
* add sample rate to fetcher

* 20

* default to always capture and base sample rate of 20%

* rm unnecessray type
2025-09-17 14:39:35 +00:00
Jordi Enric
3d55164563 propagate sentry issue id to form (#38714)
* propagate sentry issue id to form

* fix, add to payload

* empty

* name fix

* add test button

* rm thrower

* Update apps/studio/components/ui/GlobalErrorBoundaryState.tsx

Co-authored-by: Charis <26616127+charislam@users.noreply.github.com>

---------

Co-authored-by: Charis <26616127+charislam@users.noreply.github.com>
2025-09-17 12:59:07 +02:00
Jordi Enric
c61026e530 update handleError to pass sentry context (#38411)
* update handleError to pass sentry context

* no spread

* Fix the types for the sentry context.

---------

Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2025-09-03 17:17:52 +02:00
Carel de Waal
4824114b84 chore: Support form - Always capture a Sentry exception when support form request fails (#36557)
* chore: Support form - Always capture a Sentry error when support form request fails
2025-06-23 15:16:06 +02:00
Terry Sutton
8fe31d903b Chore/feedback classifier (#36147)
* First

* Update

* Cleanup

* Reduce debounce

* Add a picker before displaying feedback widget

* Update styles

* Clean up

* Fix error msg

* More prompt examples

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-06-06 16:01:10 -02:30
Joshen Lim
e539b892a6 Chore/more refactoring of data fetchers methods (#33553)
* Update postgres-service-status-query, password-strength, and free-project-limit-check-query

* Update exit-survey-send

* Update project-postgrest-config-query

* Update project-disk-resize-mutation

* Update project-update-mutation

* Update project-postgrest-config-update-mutation

* Update organization-audit-logs-query

* Fix types

* Update bucket-object-download-mutation

* Update organization-member-delete-invitation

* remove console log

* Add integer validation for disk size (enforced on the API, but lacking client side validation)

* Fix audit logs
2025-02-13 13:34:12 +08:00
Ivan Vasilov
df52ea7ee0 feat: Replace all toasts with sonner (#28250)
* Update the design of the sonner toasts. Add the close button by default.

* Migrate studio and www apps to use the SonnerToaster.

* Migrate all toasts from studio.

* Migrate all leftover toasts in studio.

* Add a new toast component with progress. Use it in studio.

* Migrate the design-system app.

* Refactor the consent toast to use sonner.

* Switch docs to use the new sonner toasts.

* Remove toast examples from the design-system app.

* Remove all toast-related components and old code.

* Fix the progress bar in the toast progress component. Also make the bottom components vertically centered.

* Fix the width of the toast progress.

* Use text-foreground-lighter instead of muted for ToastProgress text

* Rename ToastProgress to SonnerProgress.

* Shorten the text in sonner progress.

* Use the correct classes for the close button. Add a const var for the default toast duration. Remove the custom width class from sonner.

* Set the position for all progress toasts to bottom right. Set the duration for all toasts to the default (when reusing a toast id from loading/progress toast, the duration is set to infinity).

* Fix the playwright tests.

* Refactor imports to use ui instead of @ui.

* Change all imports of react-hot-toast with sonner. These components were merged since the last commit to this branch.

* Remove react-hot-toast lib.

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
Co-authored-by: Jonathan Summers-Muir <MildTomato@users.noreply.github.com>
2024-08-31 07:50:51 +08:00
Joshen Lim
163263c3c5 First round of wrapping RQ errors with handleError (#26384)
* First round of wrapping RQ errors with handleError

* Remove the throw before the handleError usage.

* Make the handling of an API error more versatile. Add logging in Sentry if the error is of unknown type.

* Remove throwing of the handleError function.

* Add return type to the handleError function to be never so that we're sure it always throws.

---------

Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2024-05-17 16:30:55 +08:00
Pamela Chia
39be400fef Feat/add upgrade survey flow (#22310)
* feat: add upgrade survey flow

* add codegen changes
2024-04-01 14:58:59 +07:00
Kevin Grüneberg
f9a55935f5 chore: use type imports for types/interfaces (#21738) 2024-03-04 20:48:22 +08:00
Ivan Vasilov
436bdb10ae chore: Move the studio app to apps/studio (#18915)
* Move all studio files from /studio to /apps/studio.

* Move studio specific prettier ignores.

* Fix the ui references from studio.

* Fix the css imports.

* Fix all package.json issues.

* Fix the prettier setup for the studio app.

* Add .turbo folder to prettierignore.

* Fix the github workflows.
2023-11-15 12:38:55 +01:00