Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion docs/guides/ai-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ priority, and confidence gates.
| Minimum triage confidence | 0.7 | Below this the customer's own choices are kept |
| Auto-resolve grounded tier-1 tickets | off | Posts and closes only a non-urgent answer grounded in published articles |
| Minimum auto-resolve confidence | 0.92 | Below this the ticket remains open for staff |
| Read-only customer assistant | off | Adds a client-area chat over published articles and that customer's account summary |
| Customer questions per hour | 20 | Per-account cost and abuse limit; `0` stops requests |

## Reply drafts

Expand Down Expand Up @@ -85,11 +87,27 @@ the same database transaction, and `ticket.auto_resolved` records its confidence
and source article IDs in the audit log. If a staff/customer update races the
model response, the optimistic write fails and no automated message is posted.

## Customer assistant

When enabled, **Dashboard → AI assistant** provides a read-only chat grounded in:

- published knowledgebase articles;
- up to 50 of the signed-in customer's own services; and
- up to 30 of that customer's recent invoices.

The assistant receives no service configuration, credentials, payment methods,
or other customers' data. It cannot mutate the account or claim that it took an
action. Requests are rate-limited per account through audited successful calls.
The customer can send the visible transcript to the normal support queue with
**Escalate to ticket** whenever a person or account change is needed.

## Costs and privacy

- You are billed by your provider for the tokens each feature uses. A reply
draft and auto-resolution send published knowledgebase content plus relevant
ticket text; classification sends the subject and first message.
ticket text; classification sends the subject and first message. Customer
assistant requests send the published knowledgebase and the requesting
customer's limited account summary.
- Ticket content and knowledgebase articles are sent to the provider you
configured, when a feature runs. Customer passwords, payment details and API
keys are never part of a prompt.
Expand Down
12 changes: 12 additions & 0 deletions src/app/admin/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ const SECTIONS: Array<{
type: "text",
help: "Defaults to 0.92. Lower thresholds increase the risk of an incorrect automatic answer.",
},
{
key: "ai_customer_assistant",
label: "Read-only customer assistant",
type: "checkbox",
help: "Lets signed-in customers ask about published documentation and their own services or invoices.",
},
{
key: "ai_customer_assistant_hourly_limit",
label: "Customer assistant questions per hour",
type: "number",
help: "Per account. Set to 0 to disable customer requests even when the assistant is enabled.",
},
],
},
{
Expand Down
29 changes: 29 additions & 0 deletions src/app/dashboard/assistant/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { CustomerAssistant } from "@/components/customer-assistant";
import { requireUser } from "@/lib/auth";
import { customerAssistantEnabled } from "@/lib/services/ai";

export const metadata = { title: "AI assistant" };

export default async function CustomerAssistantPage() {
await requireUser();
const enabled = await customerAssistantEnabled();

return (
<div>
<h1 className="text-2xl font-bold">AI assistant</h1>
<p className="mt-1 text-sm text-slate-500">
Read-only answers grounded in published help articles and your account.
</p>
<div className="mt-6">
{enabled ? (
<CustomerAssistant />
) : (
<div className="card p-6 text-sm text-slate-500">
The customer assistant is not enabled for this installation. You can
still contact the support team from the Tickets page.
</div>
)}
</div>
</div>
);
}
1 change: 1 addition & 0 deletions src/app/dashboard/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const NAV: Array<{ href: string; label: MessageKey }> = [
{ href: "/dashboard/invoices", label: "dash.nav.invoices" },
{ href: "/dashboard/quotes", label: "dash.nav.quotes" },
{ href: "/dashboard/tickets", label: "dash.nav.support" },
{ href: "/dashboard/assistant", label: "dash.nav.assistant" },
{ href: "/dashboard/account/billing", label: "dash.nav.billing" },
{ href: "/dashboard/affiliate", label: "dash.nav.affiliate" },
{ href: "/dashboard/account", label: "dash.nav.account" },
Expand Down
123 changes: 123 additions & 0 deletions src/components/customer-assistant.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"use client";

import { useActionState, useEffect, useRef, useState } from "react";
import { useFormStatus } from "react-dom";
import { askCustomerAssistant } from "@/lib/actions/assistant";
import { createTicket } from "@/lib/actions/client";
import { ActionForm } from "@/components/forms";

type Message = { role: "user" | "assistant"; content: string };

function AskButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} className="btn-primary shrink-0">
{pending ? "Thinking…" : "Ask"}
</button>
);
}

export function CustomerAssistant() {
const [state, action] = useActionState(askCustomerAssistant, null);
const [question, setQuestion] = useState("");
const [messages, setMessages] = useState<Message[]>([]);
const handledResponse = useRef<string | null>(null);

useEffect(() => {
if (!state?.id || handledResponse.current === state.id) return;
handledResponse.current = state.id;
setMessages((current) => [
...current,
{ role: "user", content: state.question },
{ role: "assistant", content: state.answer },
]);
setQuestion("");
}, [state]);

const transcript = messages.length
? messages
.map(
(message) =>
`${message.role === "user" ? "Customer" : "Assistant"}: ${message.content}`,
)
.join("\n\n")
: "Customer requested help from the read-only assistant and asked to escalate to support.";
const lastQuestion = [...messages]
.reverse()
.find((message) => message.role === "user")?.content;

return (
<div className="space-y-5">
<div className="card min-h-72 space-y-4 p-5" aria-live="polite">
{messages.length === 0 && (
<div className="mx-auto max-w-xl py-16 text-center">
<p className="font-medium">How can I help?</p>
<p className="mt-2 text-sm text-slate-500">
I can explain published documentation and summarize your services
or invoices. I cannot change your account or operate a service.
</p>
</div>
)}
{messages.map((message, index) => (
<div
key={`${message.role}-${index}`}
className={`max-w-2xl rounded-xl px-4 py-3 text-sm whitespace-pre-wrap ${
message.role === "user"
? "ml-auto bg-brand-600 text-white"
: "bg-slate-100 text-slate-700"
}`}
>
{message.content}
</div>
))}
</div>

{state?.error && (
<p className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
{state.error}
</p>
)}

<form action={action} className="flex items-end gap-3">
<input
type="hidden"
name="history"
value={JSON.stringify(messages.slice(-10))}
/>
<label className="flex-1">
<span className="label">Your question</span>
<textarea
name="question"
rows={2}
minLength={3}
maxLength={2_000}
required
className="input resize-y"
value={question}
onChange={(event) => setQuestion(event.target.value)}
placeholder="Why is invoice #123 still pending?"
/>
</label>
<AskButton />
</form>

<div className="card flex flex-wrap items-center justify-between gap-4 p-4">
<div>
<p className="text-sm font-medium">Need a person or an account change?</p>
<p className="text-xs text-slate-500">
Send this conversation to the support team as a new ticket.
</p>
</div>
<ActionForm action={createTicket} className="m-0">
<input type="hidden" name="subject" value={(lastQuestion ?? "AI assistant handoff").slice(0, 120)} />
<input type="hidden" name="department" value="general" />
<input type="hidden" name="priority" value="MEDIUM" />
<input type="hidden" name="message" value={transcript.slice(0, 20_000)} />
<button type="submit" className="btn-secondary">
Escalate to ticket
</button>
</ActionForm>
</div>
</div>
);
}
87 changes: 87 additions & 0 deletions src/lib/actions/assistant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"use server";

import { randomUUID } from "node:crypto";
import { z } from "zod";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { audit } from "@/lib/audit";
import { getSetting } from "@/lib/settings";
import {
answerCustomerQuestion,
customerAssistantEnabled,
} from "@/lib/services/ai";

const historySchema = z
.array(
z.object({
role: z.enum(["user", "assistant"]),
content: z.string().min(1).max(2_000),
}),
)
.max(10);

export type AssistantState =
| { error: string; id?: undefined; question?: undefined; answer?: undefined }
| { id: string; question: string; answer: string; error?: undefined }
| null;

export async function askCustomerAssistant(
_previous: AssistantState,
formData: FormData,
): Promise<AssistantState> {
const user = await requireUser();
if (!(await customerAssistantEnabled())) {
return { error: "The customer assistant is not available." };
}
const question = String(formData.get("question") ?? "").trim();
if (question.length < 3 || question.length > 2_000) {
return { error: "Enter a question between 3 and 2,000 characters." };
}

let history: z.infer<typeof historySchema> = [];
try {
const parsed = historySchema.safeParse(
JSON.parse(String(formData.get("history") ?? "[]")),
);
if (!parsed.success) return { error: "The conversation history is invalid." };
history = parsed.data;
} catch {
return { error: "The conversation history is invalid." };
}

const configuredLimit = Number(
await getSetting("ai_customer_assistant_hourly_limit"),
);
const hourlyLimit = Number.isFinite(configuredLimit)
? Math.max(0, Math.floor(configuredLimit))
: 20;
if (hourlyLimit === 0) {
return { error: "The customer assistant is not accepting questions." };
}
const used = await db.auditLog.count({
where: {
userId: user.id,
action: "customer.ai_assistant_asked",
createdAt: { gte: new Date(Date.now() - 3_600_000) },
},
});
if (used >= hourlyLimit) {
return { error: "You have reached the assistant's hourly question limit." };
}

try {
const answer = await answerCustomerQuestion(user.id, question, history);
if (!answer) return { error: "The customer assistant is not available." };
await audit("customer.ai_assistant_asked", {
userId: user.id,
targetType: "user",
targetId: user.id,
metadata: { questionLength: question.length },
});
return { id: randomUUID(), question, answer };
} catch {
return {
error: "The assistant could not answer right now. Please open a ticket.",
};
}
}
5 changes: 5 additions & 0 deletions src/lib/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const en = {
"dash.nav.services": "Services",
"dash.nav.invoices": "Invoices",
"dash.nav.support": "Support",
"dash.nav.assistant": "AI assistant",
"dash.nav.billing": "Billing",
"dash.nav.account": "Account",
"dash.nav.notifications": "Notifications",
Expand Down Expand Up @@ -222,6 +223,7 @@ const nl: Record<MessageKey, string> = {
"dash.nav.services": "Diensten",
"dash.nav.invoices": "Facturen",
"dash.nav.support": "Support",
"dash.nav.assistant": "AI-assistent",
"dash.nav.billing": "Betaalmethoden",
"dash.nav.account": "Account",
"dash.nav.notifications": "Meldingen",
Expand Down Expand Up @@ -391,6 +393,7 @@ const fr: Record<MessageKey, string> = {
"dash.nav.services": "Services",
"dash.nav.invoices": "Factures",
"dash.nav.support": "Support",
"dash.nav.assistant": "Assistant IA",
"dash.nav.billing": "Paiement",
"dash.nav.account": "Compte",
"dash.nav.notifications": "Notifications",
Expand Down Expand Up @@ -461,6 +464,7 @@ const de: Record<MessageKey, string> = {
"dash.nav.services": "Dienste",
"dash.nav.invoices": "Rechnungen",
"dash.nav.support": "Support",
"dash.nav.assistant": "KI-Assistent",
"dash.nav.billing": "Zahlung",
"dash.nav.account": "Konto",
"dash.nav.notifications": "Benachrichtigungen",
Expand Down Expand Up @@ -531,6 +535,7 @@ const es: Record<MessageKey, string> = {
"dash.nav.services": "Servicios",
"dash.nav.invoices": "Facturas",
"dash.nav.support": "Soporte",
"dash.nav.assistant": "Asistente de IA",
"dash.nav.billing": "Pago",
"dash.nav.account": "Cuenta",
"dash.nav.notifications": "Notificaciones",
Expand Down
Loading
Loading