Support cases
A signed-in member can raise a support case for their team, reply to it, and read its history. Cases are persisted, authorized and audited.
What this is not, yet. There is no Jira link. Cases work on the site, over Slack threads and by email, all in both directions, and an assistant can answer first.
Enabling it
builder.Services.AddThargaTeamRepository(o =>
{
o.RegisterTeamRepository<TeamEntity, TeamMember>(); // provides the case store
});
builder.Services.AddThargaSupportCases();
AddThargaSupportCases() is separate from AddThargaSupport() on purpose: notifications must be usable
without the case machinery, so a product that only wants "post to Slack when a team is created" does not
acquire a case store and a scope pair for it.
The case store comes from AddThargaTeamRepository. Nothing in the support package registers storage — that
choice belongs to the host, and this package must not acquire a database dependency.
The model
A case belongs to a team — or to no team at all — and has an author, a status, and a transcript.
SupportCase |
Header: id, team, author, subject, status, timestamps, message count, channel bindings, and for mail that opened without a team the teams it may belong to |
SupportMessage |
One transcript entry: sequence, kind (user or system), author, body as text and as sanitized HTML, files, timestamp, and whether it reached its channels |
SupportChannelBinding |
A projection onto an external system: the Slack thread, the mail conversation. Carries the correspondent's address where there is one, the support mailbox it came in through, and for a mailed answer which entry it was |
The team owns the case; the author is a link that may dangle. A case is raised by a person but is about the team's account, and the team is what still exists a year later. Deleting a user removes their membership from every team — so a case keyed on a member would be orphaned by design. Authorization keys on the team alone, and nothing requires the author to still resolve.
The author is recorded twice: a stable subject for exact matching, and a display-name snapshot so the transcript stays readable after that person is deleted or leaves. The audit trail carries the same pair for the same reason.
The header does not carry the transcript. A case can accumulate years of messages, so SupportCase has a
MessageCount and history is read separately and paged.
Who may do what
| Operation | Authorized by |
|---|---|
| Raise a case; list your own cases | Membership. No scope |
| Read, reply to, close or reopen your own case | Authorship |
| Read or list anyone's case | support:read |
| Reply to, close or reopen anyone's case | support:manage |
| Read or list a case with no team | support:unassigned:read — a system scope |
| Reply to, close, reopen or assign a case with no team | support:unassigned:manage — a system scope |
| Read or list cases in any team, without belonging to it | support:all:read — a system scope |
| Reply to, close, reopen or hand over a case in any team | support:all:manage — a system scope |
| Assign a case to a member of support staff, or take the assignee away | support:unassigned:manage for a case with no team, support:all:manage for a team's — system scopes. A team's own support:manage does not |
| Read how much the assistant was used, per team | support:usage:read — a system scope |
Not everything is a scope, deliberately. Raising a case about your own team is what an ordinary member does; gating it would mean every host granting that scope to everybody, and a scope everyone holds checks nothing. Membership and authorship are still checks — they are simply not grants.
support:readis a real privilege boundary. A support case contains whatever a user typed into it, which is exactly where somebody pastes a password, a token or a customer's details. Grant it as carefully as you grantaudit:read.
support:read and support:manage are team scopes, registered at Administrator by default — see
Taking support off the access level. A case with a team is always
loaded through it, so holding a valid case id from another tenant gains nothing.
Changed in 3.22:
support:readno longer authorizes writing. It used to satisfy reply, close, reopen, hand over and answer as well, which is not what the table above has ever said. If you granted onlysupport:readto people who have been answering cases, grant themsupport:manageas well — nothing else changes, and reading, listing and marking read are unaffected.
The unassigned scopes are system-wide, and that is not a convenience. support:read is held against a
team, and a case with no team has nothing to hold it against — so widening the team scope to cover these
would let a member of the smallest team read everything that arrived by mail. Granting these is a decision
about the whole product, which is what a system scope is for. They are registered by
AddThargaSupportCases, so they appear in the scope catalogue only where support cases exist.
An unassigned case is deny-by-default. No grant, no access — authorship does not open one either, because every case that has no team today arrived by mail from somebody with no account to match.
Support staff who belong to no team
The ordinary shape of a support queue is a customer raising a case inside their own organisation and the
product's own staff answering it. Staff belong to none of the customers' teams, so no team scope can reach
those cases — which is what support:all:read and support:all:manage are for.
// Every team's cases, for whoever runs support
var page = await supportCases.GetCasesAcrossTeamsAsync();
// How many of them are waiting on an answer
var waiting = await supportCases.GetAwaitingSupportCountAcrossTeamsAsync();
SupportAcrossTeamsView renders that queue — see Components.
Grant them through a system role, as you would any system scope:
builder.AddThargaTeam(o =>
{
o.ConfigureSystemRoles = roles => roles.Map("Support", SystemSupportScopes.AllRead, SystemSupportScopes.AllManage);
});
Do not put staff in each customer's team instead. It does not scale past a handful of tenants and it lists product staff in tenant membership lists. Access simulation is not the answer either: it is a deliberate reduction of access, and the audit trail would say a member acted when a member did not. A support reply has to be attributable to the person who wrote it, and with this grant it is.
These do not reach the unassigned queue, and the unassigned scopes do not reach a team. The two pairs
cover different populations and neither confers the other — GetCasesAcrossTeamsAsync lists every team's
cases and leaves out the ones no team owns, which is GetUnassignedCasesAsync and its own grant.
support:all:manage does not grant assignment. Assigning decides which tenant an unassigned case and
its whole transcript become part of, so it stays with support:unassigned:manage.
Answering as support
ReplyToCaseAsync adds to a case; AnswerCaseAsync answers it from the support side. The difference is
who the message counts as, not who wrote it: an answer takes the case out of the waiting count and is unread
for whoever raised it, even when they wrote the answer themselves, from a support page. Every support view
uses it, and so does a reply typed in a case's Slack thread. Each message carries AsSupport so a
transcript can show it on support's side.
AnswerCaseAsync needs a support grant — support:all:manage, support:manage on the case's team, or for a
case with no team support:unassigned:manage. Having raised the case confers nothing, or anybody could clear
their own case from the queue by answering it.
GetMyUnreadByCaseAsync(teamKey) returns each of the caller's cases that holds unread entries, with how many,
so a list can mark where to look.
Taking support off the access level
By default support:read and support:manage are granted to every Owner and Administrator of every team,
because in most products support is a shared team function and an administrator should see what their team
has raised.
Where a support conversation is personal, that default is wrong. If a case is one member talking to your own staff, their manager reading it is a different product from the one you are building. Turn the level off and the scopes become grantable only deliberately:
builder.Services.AddThargaSupportCases(o =>
{
o.TeamScopeAccessLevel = null; // registered, enforced, granted by no access level
});
null does not unregister anything. Both scopes still appear in the scope catalogue with their
descriptions and are enforced exactly as before; they are simply granted by no access level, refused in
tenant-defined custom roles, and left out of the scope-override pickers. Holding one then takes a
code-registered tenant role or an explicit override — a recorded decision rather than a consequence of
being an Owner.
Only some values differ from each other. Owner and Administrator are granted every registered scope regardless of the declared minimum, so
AccessLevel.Ownerbehaves exactly as the default does. The choices that actually differ areAdministrator,User,Viewerandnull. Do not useAccessLevel.Customto mean "nobody" — it grants the scope to every level.
The author of a case still reaches their own without holding anything, whatever you set here.
Letting each case decide
TeamScopeAccessLevel decides who holds the team's support scopes. Visibility decides which cases
those scopes reach:
builder.Services.AddThargaSupportCases(o =>
{
o.Visibility = SupportCaseVisibilityMode.PerCase; // default: TeamWide
});
| Mode | A team's support:read / support:manage holder reaches |
|---|---|
TeamWide (default) |
every case in the team — the behaviour before this option existed |
PerCase |
only cases their author has shared with the team, plus their own |
Under PerCase a new case starts as DefaultVisibility (Private unless you say otherwise), and its
author shares it — or takes it back — at any time:
builder.Services.AddThargaSupportCases(o =>
{
o.Visibility = SupportCaseVisibilityMode.PerCase;
o.DefaultVisibility = SupportCaseVisibility.Team; // a support case is the team's
o.AssistantDefaultVisibility = SupportCaseVisibility.Private; // a conversation with the assistant is the asker's own
});
await supportCases.SetCaseVisibilityAsync(teamKey, caseId, SupportCaseVisibility.Team);
- A conversation with the assistant starts as
AssistantDefaultVisibility(null usesDefaultVisibility), and takesDefaultVisibilitywhen it is handed to a person — from then on it is a support case and reads as one. - Only the author decides. A team manager cannot share somebody else's case, and neither can your own support staff: a grant to answer every case is not a grant to widen who else reads one.
- Open or closed. Who may read a case's history matters as much once it is over, so a closed case can still change.
- Private only while nobody else in the team has written in it. Once a colleague has joined the
conversation it is no longer only the author's to hide; support's answers do not count as the team writing.
GetVisibilityChoiceAsync(teamKey, caseId)says what the caller may choose — whether they may change it at all, and whetherPrivateis on offer — so a component offers exactly what the service would accept. - Your support staff are unaffected.
support:all:*reaches a case whatever it says, and so does the author. - Listings and counts follow it.
GetCasesAsyncandGetAwaitingSupportCountAsyncreturn only what the caller may read, so a team reader is never shown a case they would be refused. - A case stored before this option existed has no visibility, and reads as
PrivateunderPerCase— nobody ever chose to share it. UnderTeamWideit reads exactly as before. - Changing visibility is audited (action
visibility) and raisesSupportCaseChange.VisibilityChanged.
SetCaseVisibilityAsync is refused under TeamWide, where there is nothing to decide.
The subject is optional
A subject is a small tax on somebody who has already typed the problem into the box below it, and what it usually collects is a worse version of the first sentence. So it is off by default:
builder.Services.AddThargaSupportCases(o => o.UseSubject = true); // default: false
UseSubject decides what a person is asked for, never whether the case ends up with a subject. With no
subject supplied, the service derives one from the first 50 characters of the message — cut at a word
boundary, with whitespace collapsed first and an ellipsis marking the truncation. SupportCase.Subject is
never null, so nothing downstream has to cope with a case that has none.
That means a half-filled form cannot produce a case that renders as an empty row in a list, even with the field shown.
Reopening a case
await supportCases.ReopenCaseAsync(teamKey, caseId);
Authorized exactly as replying is: the member who raised it, a holder of support:manage on the team, or
a holder of support:all:manage. Reading the case is not enough.
It writes a system entry, clears the closure, and returns the case to Open — keeping the history, which
is the whole reason it exists rather than telling somebody to raise a second case that explains nothing.
Reopening an already-open case does nothing and is not an error. Two people looking at the same closed case both press the button; the second sees an open case rather than a complaint.
A reply reopens a closed case on its own, from every channel: an answer on the site, in the Slack thread, or
by e-mail. A case closed by hand, by AutoCloseAfter or by a sender rule earlier in the thread is open again, with a
system entry saying which channel reopened it, and a Reopened notification followed by Replied. The reply is appended after the
reopen, so it counts as awaiting support. A mail that is not accepted as a reply (from an address the case does not
correspond with, or empty) reopens nothing.
Writing to a closed case reopens it. Whatever is written — on the site, by mail, or as a reply in its Slack thread — continues the conversation that explains it rather than being refused, so the case opens again first and the entry lands in it.
Who closes a case
Closing is the customer's word that the problem is solved. The author and the team's own support readers close
whenever they like. Your own staff (support:all:manage) may too, unless you hold them to a window:
builder.Services.AddThargaSupportCases(o => o.StaffCloseAfter = TimeSpan.FromDays(14)); // default: null
With a window set, staff close a case only once support answered last and the customer has said nothing for
that long; otherwise the service refuses. SupportAcrossTeamsView takes the same value as a parameter, so it
does not offer Close where the service would refuse it. Without a window, the view still asks first, and says
it is better that the team closes the case themselves.
Saying why a case was closed
Support can leave a reason when closing, from the close dialog in SupportAcrossTeamsView and in the unassigned
queue, or in code:
await cases.CloseCaseAsync(teamKey, caseId, "Answered by phone, a duplicate of another case.");
The comment is stored with the closure and shown under it in the conversation, with who closed it and when. It is
internal: it is never mailed or posted to Slack, and GetMessagesAsync leaves it out for the case's author, their
team and the team's own support readers. Only callers holding support:all:read or support:all:manage, and those
reading the unassigned queue, get it back. It is not written to the audit log either, so it can name people.
Closing without a comment, or with a blank one, is unchanged, and the comment stays in the history when the case is
reopened. It is limited to the length of a message. A person closing their own case is not asked for one, since they
would never see it.
Closing after inactivity
A case support answered and nobody came back to closes itself after seven days.
builder.Services.AddThargaSupportCases(o =>
{
o.AutoCloseAfter = TimeSpan.FromDays(7); // default; Zero turns it off
o.AutoCloseSweepInterval = TimeSpan.FromHours(1);
o.AutoCloseBatchSize = 100;
});
The direction is the important part. The clock runs only while the case is waiting on the customer: the newest entry is support's and nobody has replied. A case whose newest entry is the customer's never closes, however old — that one is waiting on you, and closing it would hide your backlog rather than tidy it. A system entry does not start the clock either, so reopening a case does not immediately re-arm it.
SupportCase.ClosedReason distinguishes the two closures — Manual or Inactivity — so a component can say
"closed automatically, reopen it if the problem is still there" rather than something that reads as a
dismissal. It is derived from ClosedBy, which the sweep records as SupportCaseActors.AutoClose.
TimeSpan.Zero registers no background work at all, rather than a sweep that finds nothing every hour.
Existing cases are not swept until they are next written to. The sweep needs the last-activity timestamp, which older documents do not carry. That is deliberate: applying new behaviour retroactively would close an untouched backlog in bulk on the first sweep after upgrading.
Components
Five components ship in Tharga.Team.Blazor, and all are optional:
@* Help beside every page: the assistant where the team has one, and support, in a right-hand panel *@
<SupportPanel />
@* What a team member sees: raise a case, read the conversation, reply, reopen *@
<SupportCasesView ShowSubject="false" />
@* What support sees: every case in the team, answer, close, reopen *@
<SupportQueueView />
@* Cases that belong to no team: answer them, and assign a team when you know which it is *@
<SupportUnassignedView />
@* Your own support staff: every team's cases, each naming its team, answered in place *@
<SupportAcrossTeamsView />
SupportAcrossTeamsView needs support:all:read (or :manage to answer) and, like
SupportUnassignedView, renders a note rather than throwing when the caller holds neither. It names each
case's team through ITeamOversightService when the caller can list teams, and shows the team key when
they cannot.
A side panel beside every page
SupportPanel is a right-hand sidebar. Place it inside your RadzenLayout, beside the RadzenBody, for signed-in
members:
<RadzenLayout>
<NavMenu />
<RadzenBody>@Body</RadzenBody>
<AuthorizeView>
<Authorized><SupportPanel /></Authorized>
</AuthorizeView>
</RadzenLayout>
- Collapsed, it is a narrow rail: a button for each channel offered, and one to your support page carrying the member's unread count.
- Open, it has Assistant and Support tabs, a new conversation, the earlier conversations still open or with the
assistant, and the conversation itself. It is the same case
SupportCasesViewshows, so a conversation started in the panel continues on the support page and back. - Writing to support on a conversation the assistant is answering hands it to a person, keeping the conversation. Going back to the assistant after that starts a new conversation beside it. When the assistant does not answer, the panel says so and, for a team that is limited, shows how much of its allowance is spent (A spend allowance per team).
- Its width and open state are remembered in the browser, under
StorageKey. It opens atDefaultWidth(320) until dragged, never narrower than 280 pixels. - On a screen 768 pixels wide or less,
NarrowScreendecides.SupportPanelNarrowScreen.Hide, the default, hides it, and your support page (SupportPagePath,/supportby default) is where to ask.Drawerkeeps it: collapsed, it is a floating button in the corner carrying the unread count; open, it lies over the page at full height, under any dialog, at most 85% of the screen wide. On a wider screen both are the sidebar above. - An answer is marked read only while the panel is open and the page is looked at, and the panel redraws when the member changes team, a reply arrives from Slack or mail, or a host relays a change made on another instance (Knowing when something changed).
<SupportPanel NarrowScreen="SupportPanelNarrowScreen.Drawer" />
Who may be asked. The assistant shows when the team is ready for one (GetAssistantReadinessAsync), so a team that
turned the assistant off, or has no model, gets only support. Offered narrows what shows, as on SupportCasesView.
To switch either channel per team, for example behind a feature a team has bought, register an
ISupportPanelAvailability. Its GetOfferedAsync(teamKey) says who may be asked, and raising its Changed event
redraws an open panel. It can only narrow: the assistant is never offered to a team that is not ready for it (a team
whose allowance is used up, whose provider refused the account, or that the host holds back still has the tab, to say why). With
nobody to ask, or no team selected, the panel is not drawn at all.
SupportCasesView has two tabs — the cases first, then where help is asked for. Tab names the one to
show (SupportCasesView.CasesTab or NewCaseTab) and TabChanged reports a change, so a page can keep its
address in step and link straight to either. A host can add tabs of its own after those two through ExtraTabs,
each a SupportCasesExtraTab with a Name and a Text; the name works in Tab and TabChanged like the built-in
ones. The host decides whether a tab is there at all, so a reader without the right to it sees none: put the condition
around the tab inside ExtraTabs. The usual use is the back-office queue beside the customer's own cases:
<SupportCasesView>
<ExtraTabs>
@if (_canSeeQueue)
{
<SupportCasesExtraTab Name="queue" Text="Support queue">
<SupportQueueView />
</SupportCasesExtraTab>
}
</ExtraTabs>
</SupportCasesView>
Cases are expandable cards; each conversation loads when its card
opens. Every case list shares one filter — status and kind of conversation, open support cases by default —
remembered in the browser under StorageKey, and every list reads every page of the listing rather than the
first. SupportCaseFilter also takes ShowSearch — a search over the subject, who wrote, the case id, the team
and suggested teams, the address a case corresponds with and the support address it came in to, which is not
remembered — and ShowKinds, to leave the kind out where no assistant answers.
Where help is asked for, Offered says who may be talked to: SupportAssistance.Assistant, SupportAssistance.None
(a person), or both, which is what null offers. With both on offer the customer chooses on a select bar — Assistant
or Support, with support chosen until they choose — and the case is raised the way they chose. With one there is
nothing to choose: the bar gives way to its name and the case is raised that way. The assistant is never offered
to a team that is not ready for it (GetAssistantReadinessAsync), whatever is passed. A team with no model of
its own is handled by the resolver (A model per team); an assistant that the team has but
the host switches off for one organisation is a matter of what the host passes for that organisation:
@* Human support only for this organisation, although the assistant is registered *@
<SupportCasesView Offered="_humanSupportOnly" />
@code {
private readonly SupportAssistance[] _humanSupportOnly = [SupportAssistance.None];
}
The two options are named by team.support.cases.answeredBy.assistant and team.support.cases.answeredBy.human.
SupportUnassignedView reads like the cases view: each case an expandable card with the sender, status,
Needs an answer and last activity in its header, whose conversation is read only while it is open; waiting
cases first, then the newest activity, with the count awaiting an answer beside the filter (with search, and
without kinds, since no assistant answers a case without a team). It takes TimeTemplate and StorageKey
(default Tharga.Team.Support.Unassigned.Filter), and RefreshAsync() for a host that relays changes from other
instances over its own backplane. It carries no heading; SupportUnassignedViewText.Title is there for a
host that labels the tab or card it sits in.
Every answer box in these views takes formatting (RichTextEditor) and files
(SupportAttachmentPicker), and every staff view shows the support address a case came in to
and whether each answer was delivered. Above each support answer box, SupportAnswerRouteLine says where the
answer goes — the address it is mailed to and the support address it is sent from, or that it is shown on the
site — and beside the button that answers, Preview opens the mail as the person who raised the case would
receive it; see Where the answer goes, and its preview.
Closing asks first. The team's dialog offers who may read the case from now on, under PerCase, with
Private offered only where GetVisibilityChoiceAsync allows it; the staff dialog says it is better left to the
team. A conversation with the assistant is neither open nor closed, so it has nothing to close and shows
what it is instead of a status.
An answer is marked read only once somebody is looking. An open conversation on a page in a background
tab, or in a window without focus, leaves the answer unread — and every count saying so — until the reader
comes back. SupportAttention exposes the same check to a host's own components.
SupportAcrossTeamsView marks what needs an answer and lists it first, shows each case's team with its
icon (through IIconResolver), and shows who may read a private case.
SupportQueueView needs support:read, and the service refuses without it — so gate rendering on the scope
to spare a member a refusal they can do nothing about.
SupportUnassignedView needs the system scopes instead, and behaves differently in two ways worth
knowing before you place it:
- It renders a note instead of throwing when the caller cannot read the queue, because it is a panel
beside content they can see.
SupportQueueViewlets the refusal propagate, because there it is the page. - Its assign control lists teams through
ITeamOversightService, which needsteams:read. An operator holding the unassigned scopes but not that one can still answer and close; they simply have nothing to assign to, and the component says so. This is deliberate rather than a limitation: nothing validates a team key on the way through, so a free-text field would let somebody assign a case to a team that does not exist — out of the queue and into nobody's.
A host can always build its own instead, and that is the point. Both components go through
ISupportCaseService and nothing else — no store, no internal service — and a test asserts it. If a shipped
component needed something you cannot reach, the surface would be incomplete and the component would be
hiding it.
ShowSubject is a parameter rather than a read of UseSubject, because the options live in
Tharga.Team.Support while the components depend on contracts only. Pass the same value you configured; or
differ per page, which reading the options could not express.
Closing from SupportQueueView warns first and suggests letting the person who raised the case close it
— they are best placed to say the problem is solved, and a case closed while somebody is still typing reads
as a dismissal. It is advisory: support can still close a case that is finished.
Working a contact-form message
A message raised through RaiseExternalCaseAsync shows who wrote as a table of label and value (SupportContactTable): name,
e-mail, phone, organisation, each of the form's own fields in the order the host gave them, and when consent was given, or
that none was recorded. Rows with nothing in them are left out. The labels go through IThargaTextProvider
(SupportContactText), so a host can translate them.
Copy buttons beside the e-mail address and the phone number put the value on the clipboard and show a short "Copied" notice.
The contact stays after the case is given a team: the same table shows on the case in
SupportAcrossTeamsView."Connect to organisation" can be searched, case-insensitively, matching anywhere in the name.
A slot for your own content. Both boards take
CaseExtras, aRenderFragment<SupportCase>rendered inside each opened case below the contact, with the case as its context. It is how a host links a message to something the package knows nothing about, such as a sales prospect, without the package ever holding the host's concept:<SupportUnassignedView CaseExtras="@(c => @<ProspectLink CaseId="@c.Id" />)" />Assignment can be left to the host.
SupportUnassignedView(andSupportUnassignedConversation) takeShowAssignment, which istrueby default. Set it tofalseand neither the suggested-team buttons nor the team dropdown render, so a host that links a case to its own records inCaseExtrascan offer one control for both. Nothing else in the conversation changes, and the case keeps itsSuggestedTeamsandSuggestionReasonfor the host's control to show. The host gives the case its team withAssignCaseAsync, which now stores the team's name inTeamNamealong withTeamKey, as a case placed on receipt already did. The name is read through the cross-team read (ITeamOversightService) first, since the staff who triage the queue are rarely members of the team, and falls back to the caller's own teams; a name that cannot be read leavesTeamNameempty and the case is assigned all the same.Open one case on load.
CaseIdon either board opens that case, so a host can link straight to it, for instance from a query value:<SupportUnassignedView CaseId="@Case" />with[SupplyParameterFromQuery(Name = "case")]. An id that names nothing the reader can list opens nothing and does not throw; a filter does not hide the case asked for.One case by id, for staff.
ISupportCaseService.GetCaseByIdAsync(caseId)returns a case whichever team it belongs to, ornull; read its messages with the team the case reports. It takessupport:readfor a case with no team andsupport:all:readfor a team's.
Who has the case
A case can be assigned to one member of the product's own support staff, or to nobody. On a desk with several people it answers "whose case is this" from the list, without a host having to build it on top.
- On the card.
SupportAcrossTeamsViewandSupportUnassignedViewshow who has each case, and the opened case has a picker to change it (clear it to take the assignee away). The list filter gains an assigned to choice, anyone, nobody or one person, remembered with the other filter choices; the search box on the unassigned queue also finds a case by its assignee's name or address.SupportCaseByIdoffers the picker in the conversation it shows. - Who can be chosen. The toolkit cannot tell staff from users, because who holds a system support scope is decided by your own claims. So
you tell it. Register an
ISupportStaffDirectory, which returns each person's authentication subject (SupportCaseAssignee.Key), name and address, and those people are offered. Without one a person can only assign a case to themselves, which needs nothing registered. Being listed grants nothing: reading and answering are still governed by the system support scopes. - The service refuses anybody not offered, so a hand-made call gains nothing over the picker.
GetAssignableStaffAsyncreturns exactly the peopleSetCaseAssigneeAsync(teamKey, caseId, assigneeKey)will accept, the caller always among them. A blank key takes the assignee away; naming the person who already has the case changes nothing. PassnullforteamKeyon a case with no team. - A host with its own control sets
ShowAssignee="false"on the views (and onSupportCaseById), and nothing about assignees is shown, picked or filtered. The conversation components themselves take the same parameter, off by default. - Live. An assignment is announced as
SupportCaseChange.AssigneeChanged, so every open staff screen reads the case again, on every instance when the host relays the notifier as described under Knowing when something changed. - It is staff's, not the customer's. Nothing is written to the transcript, which the customer's own team reads. The audit log is the history, and the case carries only the current assignee, with the name and address as they were when it was assigned.
- Independent of the team. Giving an unassigned case a team keeps its assignee, and closing a case leaves it, so a reopened case is still its owner's.
builder.Services.AddSingleton<ISupportStaffDirectory, MySupportStaff>();
internal sealed class MySupportStaff(IMyStaffStore staff) : ISupportStaffDirectory
{
public async Task<SupportCaseAssignee[]> GetStaffAsync(CancellationToken cancellationToken = default)
=> [.. (await staff.ListAsync(cancellationToken)).Select(x => new SupportCaseAssignee { Key = x.Subject, Name = x.Name, Email = x.Email })];
}
A host with its own ISupportCaseService or ISupportCaseStore keeps compiling: the new members default to throwing NotSupportedException,
and the picker and the filter leave themselves out when the service says so. A store of your own implements SetAssigneeAsync to support it.
Who is writing
While somebody on the other side is writing an answer, the open conversation shows three flashing dots where
their message will appear, and a screen reader hears "Sam is typing…" (team.support.transcript.typing). It works
in the side panel, SupportCasesView, SupportQueueView and SupportAcrossTeamsView. Nobody sees dots for their
own side, so someone who writes as a member in the panel and answers at the desk sees each side from the other. A
member writing to the assistant tells nobody.
- A writer reports through the service, at most once every two seconds while writing:
ReportTypingAsync(teamKey, caseId, asSupport). It is authorized exactly as replying, or as answering whenasSupport, so nobody can show dots in a case they could not answer. Nothing is stored, audited or counted as activity. - The dots go away by themselves, five seconds after the last report, or when the message arrives. There is no "stopped" signal, so a writer who closes the page never leaves the dots behind.
ISupportTypingNotifierraises the reports, a singleton likeISupportCaseNotifierwith the same rules: marshal withInvokeAsync, and unsubscribe. It is separate because a report changes nothing, and every listener to a case change reads the case again.SupportCaseTypingEventArgssays who and where, never what is being written.- It is in-process: across several instances, only circuits on the writer's instance see the dots. Slack and mail do not report writing, so a reply typed there arrives without dots first.
Reading history
Paging uses an explicit cursor, and the cursor is the sequence of the last message returned:
var page = await support.GetMessagesAsync(teamKey, caseId, pageSize: 50);
while (page.NextCursor != null)
{
page = await support.GetMessagesAsync(teamKey, caseId, page.NextCursor, pageSize: 50);
}
A sequence cursor rather than an offset, because a support conversation is appended to while somebody is reading it. With an offset, a reply arriving between two page reads shifts every later entry and the reader silently sees one twice or misses one.
Limits
| Limit | Value | Why |
|---|---|---|
SupportCaseLimits.MaxMessageLength |
10,000 characters | Support text is where somebody pastes a log file |
SupportCaseLimits.MaxMessageHtmlLength |
10,000 characters | Longer formatting is dropped and the message kept as its text |
SupportCaseLimits.MaxMessagesPerCase |
500 | The transcript is embedded in one document |
Files are not in the case document; see Attachments for their limits.
Exceeding either throws with a message naming the limit. At their product the transcript is roughly 5 MB against MongoDB's 16 MB document limit, so a case of maximum-length messages still has headroom.
The transcript is embedded rather than kept in a second collection because that makes each operation a single write: raising a case creates the case and its first message, and closing one sets the status and records why. Neither can half-apply, so a case always has a transcript.
Auditing
Raise, reply and close are three distinct audited facts under the support feature, carrying the case id and
(on raise) the subject. Refusals are audited too, as failed entries with the reason — a denied attempt to
reach another team's case is worth knowing about.
Message bodies are never recorded. An audit entry has more readers, longer retention and easier export
than the case itself. Neither are file names: a reply or an answer carrying files records how many
(support.message.attachments). Sending an entry again is audited as resend, with where it stands afterwards
(support.message.delivery). Assigning a case to a member of staff is audited as assign-to-staff, with the case and the new assignee's
subject (support.case.assignee, empty when the assignee was taken away); the previous assignee is the entry before it.
Slack threads
A case can be projected onto a Slack thread. Replies flow both ways: a reply raised here appears in the thread, and a reply typed in the thread appears on the case.
builder.Services.AddThargaSupportCases(o =>
{
o.SlackChannel = builder.Configuration["Slack:SupportChannel"]; // e.g. "#support"
o.SigningSecret = builder.Configuration["Slack:SigningSecret"]; // only needed to receive replies
});
app.MapThargaSupportSlack(); // where Slack posts thread replies
Leave SlackChannel unset and nothing changes. Cases stay on the site, exactly as they behave without
this feature — that is the ordinary configuration for a host that does not want Slack, not a degraded one.
Configuring the Slack app
There is no Tharga app to install, and there cannot be. Slack issues tokens per workspace installation, so every consumer creates their own app. A distributed app would mean Tharga hosting an OAuth endpoint and holding your workspace's credentials — and it would not even help, because inbound events have to reach your deployment rather than ours.
What we ship instead is a manifest, so this is a short job rather than an afternoon of guessing at scopes.
Setting up is two phases, and the order matters. The manifest declares the app and its scopes, which is everything the outbound half needs. Event subscriptions come after, because Slack verifies the request URL the moment you save it — so there has to be something listening first.
Phase one — the app, and everything outbound:
- Create the app from the manifest. Slack API → Your Apps → Create New App → From an app manifest,
choose the workspace, and paste
slack-app-manifest.jsonfrom the repository root, unedited. - Install to workspace, then copy the Bot User OAuth Token (
xoxb-…) intoSlack:BotTokenand the Signing Secret (Basic Information → App Credentials) intoSigningSecret. - Invite the bot to each channel —
/invite @Tharga Support. It cannot post to a channel it is not in, and it cannot read the member list of one either, which is how presence is determined.
At this point notifications and case threads work. Replies typed in Slack do not yet.
Phase two — inbound replies, once you have a public URL:
- Get a public address. A deployment already has one; locally you need a tunnel — Visual Studio's Dev
Tunnels or ngrok. Slack cannot reach
localhost. The sample's README walks through it for the sample, settings and all. - Event Subscriptions → enable, and set the request URL to
https://your-host/_tharga/support/slack/events. Slack sends a one-off challenge as you save; the endpoint answers it automatically, so a green tick here means the whole inbound path is wired. - Under Subscribe to bot events, add
message.channelsfor a public support channel, ormessage.groupsfor a private one.
The manifest deliberately carries no
request_urland no comments. Slack validates the document strictly: an unknown key is rejected outright, and a placeholder URL is rejected because it is verified rather than merely stored. The guidance that belongs with a human lives here instead of in the file.
The manifest asks for exactly six scopes, each required by code or by Slack:
| Scope | Used by | For |
|---|---|---|
chat:write |
chat.postMessage |
posting notifications and case replies |
users:read |
users.getPresence |
whether anybody on support is active |
channels:read |
conversations.members |
who is on a public support channel |
groups:read |
conversations.members |
the same, for a private channel |
channels:history |
the message.channels event |
receiving replies typed in a public support channel's threads |
groups:history |
the message.groups event |
the same, for a private channel |
Without the history scope Slack will not let you subscribe to the message event, so replies typed in Slack never arrive. An app created from an older manifest needs the scope added and the app reinstalled.
Remove a scope and the feature that needs it stops working quietly, not loudly — the client reports failures rather than throwing, by design, so a missing scope looks like nothing happening.
In production
There is no tunnel. Your application already has a public HTTPS address, so the inbound endpoint is a
route rather than something to acquire — which is why a webhook was chosen over Socket Mode in the first
place. The tunnel exists only because Slack cannot reach localhost.
Four steps, once per deployment:
- Create a Slack app from the manifest, exactly as for local work.
- Set the request URL to the real address —
https://app.example.com/_tharga/support/slack/events. - Subscribe to
message.channelsand install to the workspace. - Put the bot token and signing secret into that environment's secret store.
The code is identical; only the URL differs.
One Slack app per deployment. An app has exactly one Event Subscriptions request URL, so production and staging cannot share one — and neither can two products in the same workspace. Use the same manifest for each, and give each its own channel so test traffic never reaches real support.
Three things in the request path break signature verification, and each fails looking like a wrong secret:
- Anything that alters the body. The signature covers the exact bytes Slack sent, so a proxy that re-serializes, re-encodes or reformats JSON invalidates every request.
- A redirect. Slack does not follow them, so an HTTP-to-HTTPS jump or a trailing-slash normalisation on that route fails verification.
- Stripping
X-headers.X-Slack-SignatureandX-Slack-Request-Timestampare the credential.
Running several instances needs nothing extra. Inbound is stateless and load-balances like any request,
and the event ledger deduplicates across instances through a unique index — so whichever instance takes a
retry, only one reply is appended. Keep
ThargaTeamOptions.SupportEventLedgerRetention (default 24 hours) above Slack's retry horizon.
Watch the log. SlackClient reports failures rather than throwing, so nothing surfaces in the
application: alert on its warnings. The two failures that otherwise pass unnoticed are the bot being removed
from a channel and Slack disabling an event subscription after repeated delivery failures.
The four settings
builder.Services.AddThargaSupport(o =>
{
o.Slack.BotToken = config["Slack:BotToken"]; // xoxb-… from step 2
o.Notifications.DefaultChannel = config["Slack:Channel"]; // where event notifications go
o.Notifications.CaseUrlTemplate = config["Slack:CaseUrl"]; // https://you.example.com/support/{caseId}
});
builder.Services.AddThargaSupportCases(o =>
{
o.SlackChannel = config["Slack:SupportChannel"]; // where case threads go
o.SigningSecret = config["Slack:SigningSecret"]; // from step 2; needed to receive replies
});
Keep the token and the secret out of source control — dotnet user-secrets locally, your platform's secret
store in a deployment. The sample reads exactly these keys and stays dormant without them.
The endpoint is public and unauthenticated, deliberately. Slack cannot present a credential, so the request signature is the credential: every request is verified with HMAC-SHA256 over the raw body before anything is read from it, and one older than five minutes is refused so a captured request cannot be replayed. Putting an authorization policy on the route would simply stop Slack reaching it.
Slack cannot reach
localhost. To try this locally you need a public URL — a tunnel such as ngrok pointed at your dev server — or you can exercise the endpoint by posting a correctly signed request yourself. Without one, outbound works and inbound silently never arrives.
Knowing when something changed
ISupportCaseNotifier is raised whichever side replied, so a UI reacts the same way to both:
@implements IDisposable
@inject ISupportCaseNotifier Notifier
protected override void OnInitialized() => Notifier.CaseUpdated += OnCaseUpdated;
public void Dispose() => Notifier.CaseUpdated -= OnCaseUpdated;
private void OnCaseUpdated(object sender, SupportCaseUpdatedEventArgs e)
=> _ = InvokeAsync(async () => { await ReloadAsync(); StateHasChanged(); });
Three things this will not forgive:
- Marshal with
InvokeAsync. A reply from Slack is handled on the request thread of Slack's POST, not on your circuit. Touching component state directly updates off the synchronization context and loses the render. - Unsubscribe. The notifier is a singleton and outlives every page. A component that subscribes and never detaches keeps itself alive for the lifetime of the application.
- It carries no authorization. Every subscriber hears about every case in every team — a singleton has no
caller to filter by, and
FromChannelplus the team key is all it says. Read the case back throughISupportCaseServiceto act on it, where the checks are.
FromChannel distinguishes a reply somebody typed here from one that arrived from Slack. The second is
usually the one worth notifying about; the first, the user is already looking at.
It reaches this instance only, unless you relay it. On more than one instance the notification is raised on
whichever instance handled the change — a Slack reply wakes the one whose endpoint Slack reached, not necessarily
the one holding the user's circuit. To reach every instance, relay over your own backplane (Redis, Service Bus, …):
publish each notification whose FromRemote is false, and hand what arrives from the other instances to Notify
with FromRemote set. A relayed change is never published again, so nothing bounces between instances, and every
view listening — the panel and the case views among them — shows changes made anywhere.
// Outgoing: what happened on this instance.
notifier.CaseUpdated += (_, e) =>
{
if (e.FromRemote) return;
backplane.Publish(new RelayedCaseChange(e.TeamKey, e.CaseId, e.Change, e.FromChannel));
};
// Incoming: what happened on another instance.
backplane.Received += m => notifier.Notify(new SupportCaseUpdatedEventArgs
{
TeamKey = m.TeamKey, CaseId = m.CaseId, Change = m.Change, FromChannel = m.FromChannel, FromRemote = true
});
A backplane that also delivers an instance's own messages back to it makes its views read the case twice; skip your own messages if it does. The relay carries what the notification carries and nothing more — never the message text.
Whether a message got there
Every entry records its own delivery state, so a message that never reached Slack is visible rather than only logged:
| State | Meaning |
|---|---|
NotApplicable |
The case has no channel — nothing to deliver to |
Pending |
Written, not confirmed sent. Retryable, and worth reminding about |
Sent |
The channel took it. A reply arriving from Slack is Sent by definition |
Failed |
The channel refused it, was unreachable, or the mail bounced — with the reason in DeliveryError |
A channel being down never blocks a case. The case is written first and is authoritative; projecting it
comes after. If Slack refuses, the case still exists and the entry is Pending.
"Not delivered" says why. A recipient the server refused, a bounce saying the sending domain failed SPF and
the outbound policy withholding mail outside production are three different fixes, so the reason is kept on the
entry. A channel of your own reports it by overriding ISupportChannel.PostWithResultAsync; the default wraps
PostAsync and reports no reason. A bounce that names a mailed answer marks that answer Failed with the
receiving server's words, and raises SupportCaseChange.DeliveryChanged.
Send it again. ResendAsync(teamKey, caseId, sequence) sends a Failed or Pending entry to the case's
channels again and returns where it stands; any other entry is left alone, so pressing the button twice sends
nothing twice. It is authorized as answering is and audited as resend with support.message.delivery. The
support views show Not sent yet, Not delivered with the reason, and Send again under such an answer.
A case can arrive by mail, and be answered by mail. IMAP in, SMTP out, against your own mailbox — no provider account, no public endpoint, no webhook to expose.
builder.Services.AddThargaSupportCases(o =>
{
o.Email.Imap.Host = builder.Configuration["Support:Mail:Imap:Host"];
o.Email.Imap.UserName = builder.Configuration["Support:Mail:Imap:UserName"];
o.Email.Imap.Password = builder.Configuration["Support:Mail:Imap:Password"];
o.Email.Smtp.Host = builder.Configuration["Support:Mail:Smtp:Host"];
o.Email.Smtp.UserName = builder.Configuration["Support:Mail:Smtp:UserName"];
o.Email.Smtp.Password = builder.Configuration["Support:Mail:Smtp:Password"];
o.Email.FromAddress = "support@example.com"; // where replies come back to
});
Leave the hosts unset and nothing is registered — no channel, no poller. IMAP alone and SMTP alone are both real configurations: read the mailbox without answering by mail, or answer by mail while questions come in on the site.
Email is the customer's channel; Slack is support's
A person is answered the way they made contact. Somebody who wrote to support@ gets a mail back; somebody
who typed into the site reads the answer on the site. Support works in the back office or in a Slack thread
and never touches mail in either direction.
That is why a case raised on the site opens no mail projection: the person who raised it is already looking at the page. An email projection is opened by mail arriving.
Both channels are live at once, so a case that arrived by mail can hold an email binding facing the customer and a Slack binding facing support, and an answer reaches both.
Which team does an emailed case belong to?
Only the one the sender provably belongs to, and otherwise none until somebody says. A From: header does
not say which tenant a problem concerns, and every way of guessing — a fallback team, a configured default — is
the guess that puts one customer's problem in another customer's list.
A mail opens in a team only when all of this holds:
- The sender is verified. Every mail read is checked by DKIM: a signature that verifies, signs
Fromand the whole body, and whose domain is theFromaddress's domain or a parent of it. The key is looked up in DNS, cached for ten minutes (a miss for one) and cut off after five seconds; anything that goes wrong means not verified, never an error. The result isInboundMail.SenderVerifiedandSenderDomain. - Exactly one user account holds the address, compared trimmed and ignoring case.
- That account is an active member of exactly one team: accepted, not suspended, with an access level, the account enabled. A membership with no access level grants nothing since 4.0, so mail neither opens there nor suggests it.
Then the case opens in that team with that user as its author, exactly as if they had raised it on the site.
Anything short of that opens unassigned, with the teams the address matched in SupportCase.SuggestedTeams
and why they are only suggestions in SuggestionReason:
SupportTeamSuggestionReason |
|
|---|---|
SeveralTeams |
The sender is verified and an active member of more than one team |
SenderNotVerified |
The address belongs to members of these teams, but the mail could not be verified as coming from it |
SharedAddress |
More than one user account holds the address |
An unknown sender opens unassigned with no suggestions. SupportUnassignedView shows the suggestions with their
reason and assigns to one in a click; that goes through AssignCaseAsync like any other assignment.
Verified vouches for the domain's mail system, not for a person. A large mail provider signs only what its own account holder sent, so there it amounts to the address; a company domain signs whatever its servers relay, so it is only as strict as that company is about who may send as whom.
The address compared is the one on the user record, which comes from the sign-in provider's e-mail claim.
Who a sender is comes from ISupportSenderDirectory, which AddThargaTeamRepository registers when it has both
the user and the team repository. If your sign-in provider issues addresses it has not verified, register one of
your own that finds nobody before it, and every mail opens unassigned without suggestions, as it did before 4.2.
An unassigned case is unattributed: no team, no author identity, the sender's address as the display name. An
operator holding support:unassigned:manage assigns a team when they know which it is, and leaving it
unassigned forever is a supported state, not a backlog. The assignment is recorded in the transcript, because
which tenant a case belongs to is part of its history.
Assignment is conditional: two operators triaging the same queue cannot both assign a case, and
AssignCaseAsync returns false to the one who lost rather than silently doing nothing.
The trust rule
A From: header authenticates nobody. So:
- Mail that matches an existing case is accepted only from the address that case already corresponds with. Anyone else is dropped and logged — otherwise learning a thread id would let a stranger write into a transcript a real person reads and trusts.
- Mail that matches no case opens a new one, which is the only thing an unknown sender can do.
- Automated mail — vacation responders, bounces,
Precedence: bulk— is never acted on. Answering one is how a support mailbox and an out-of-office reply fill each other overnight. - Mail this instance sent is never read back as a reply.
A support mailbox collects spam, and some of it becomes cases. Mail from a person to an address that accepts mail from anyone is a case by definition. The recipient filter narrows it and the checks above drop the machinery, but rate limiting is yours.
One mailbox, two sites
o.Email.Recipients = ["example.com"]; // this instance answers for this domain only
A bare domain matches any local part; a full address matches only itself; matching is case-insensitive and plus-addressing is stripped, so a per-case reply-to is not rejected. Unset accepts everything.
Three things make sharing a mailbox actually safe, and each of them is load-bearing:
- Nothing is ever flagged or moved. The mailbox is opened read-only, so a fetch cannot set
\Seenas a side effect. A flag meaning "handled" to one instance hides the message from the other. - The filter runs before deduplication. Recording a message id and then discarding the mail would leave the instance that wanted it seeing a duplicate and concluding somebody had handled it. Nobody had.
- Each instance keeps its own read position, keyed on the recipients it answers for. Sharing a position would let the first instance to poll advance past a message addressed to the second.
Mail that is not a support case: sender rules
Some automated mail carries no automated-mail marker and is addressed to the support address itself, so neither
the automated check nor the recipient filter can tell it apart. The usual one is a DMARC aggregate report, when
the support address is the rua=mailto: address: one mail a day, each opening an unassigned case and, in a host
that announces on SupportCaseChange.Raised, an alert.
o.Email.SenderRules =
[
new MailSenderRule { Senders = ["dmarc-reports@reports.example.org", "*@dmarc.example.org"], Action = MailSenderAction.Ignore }
];
or from settings:
"SenderRules": [ { "Senders": [ "dmarc-reports@reports.example.org" ], "Action": "Ignore" } ]
| Action | Result |
|---|---|
Ignore |
No case, no event. The mail stays untouched in the mailbox, like everything else the handler ignores |
Close |
The case is stored already closed (unassigned, ClosedBy = SupportCaseActors.SenderRule), for a host that wants a record |
- Neither action raises
SupportCaseChange.Raised. A host that announces on it stays silent with no code of its own. A rule that opened the case and closed it afterwards would still have raised it. - A sender is an address, or
*@domainfor every address at exactly that domain (not its subdomains). Matching ignores case. The first rule that names the sender decides. - Decided after the event ledger records the message id, so the mail is not reconsidered, and before anything is created. Each matched mail logs one Information line naming the sender and the action.
- Per mailbox: set it on the primary
Emailoptions or on an added mailbox's own options. A mail from a sender not on the list behaves as before. - A
Fromheader authenticates nobody, so anyone can send as a listed address and have their mail dropped. The rule only ever removes a case; it grants nothing.
Reading the mailbox
A background service polls on o.Email.PollInterval (default one minute) and applies what arrives. There is
no endpoint to map and nothing to verify — the cost is latency bounded by the interval.
The read position is a bookmark, not a record: it is stored by ISupportMailPositionStore
(AddThargaTeamRepository provides the MongoDB one), written only after mail is handled, and losing it costs
a re-read rather than duplicate cases — the event ledger recognises everything already applied. Without a
store registered the poller keeps its position in memory and says so once at startup.
A mailbox that reports a new UID generation is re-read from the start, for the same reason: the stored UIDs now refer to different messages, so trusting them is the one thing that could lose mail.
Connecting a mailbox that already holds mail? Set FirstReadSince to a date, and a mailbox with no read
position starts there instead of turning every message it ever received into a case. It applies whenever reading
starts from the beginning, including after a new UID generation.
A mailbox that cannot be read is logged with its name and the server's reason (MailFetchResult.Error, never the
password), and tried again on the next interval.
What is trimmed
Quoted history and signatures are cut on unambiguous markers only, and the whole body is kept when nothing is recognised — reading too much is untidy, cutting too much silently loses what somebody wrote. A mail's HTML is kept, sanitized and cut at the same point — see Formatting — and its files are stored — see Attachments.
Mail longer than MaxMessageLength is trimmed rather than refused, unlike a reply typed into a form:
there is nobody to tell, and the message id has already been recorded, so refusing would discard what a
customer sent and never ask again.
The thread
An answer carries the conversation. It is sent In-Reply-To the newest mail of the case, with every earlier
Message-ID in References, and quotes the conversation so far, newest first, under the answer — so the
customer's mail program threads it, and whoever reads it on a phone sees what it answers.
Every message id is recorded — the mail that opened the case, every reply, every answer sent — so a reply to any of them finds its case, whichever one the customer's mail program chose to answer.
A short tracking address brings a reply back to its case when the mail program drops the headers. With
PerCaseReplyTo on, an answer asks for replies at support+tracking-3a3aac94fd15@example.com: the sending address,
a +, then a short token the case is given the first time an answer needs one (12 hex characters, unique across
cases, stored on the case and kept for good). The prefix is MailOptions.TrackingPrefix, tracking- unless you change
it, and changing it breaks no address already sent. A case that existed before gets its token on its next answer, so
there is nothing to migrate, and an address carrying the full case id, from before tokens, still finds its case. A
store that cannot hold tokens keeps the full id in the address. The mailbox must accept plus-addressing, as before.
Outside production, a reply from the override address counts as the customer's. The outbound policy sends every answer to the override address, so the person testing answers from there; that reply is accepted on the case as if the customer had written it.
How an answer speaks for support
An answer mail names no staff member, unless you ask it to (signing with a name). It starts with the answer itself, with no author heading; the host's signature follows it, before the conversation it quotes, the way a mail program places a signature; and every earlier entry written by support — a person answering from the support side, or the assistant — is attributed to support's name, never the person. The customer's own entries keep the name they were written under.
builder.Services.AddThargaSupportCases(o =>
{
o.Answers.SupportName = "Example Support"; // default: the text key team.support.mail.supportName, "Support"
o.Answers.Signature = ["Kind regards,", "Example Support"]; // default: none
o.Answers.TimeZoneId = "Europe/Stockholm"; // default: UTC
});
- The signature is plain text lines: in the text body after a blank line, and in the HTML one paragraph,
<p class="signature">, its lines encoded and joined by<br>, so a template can style it. Without one nothing is added. - The quote is nested, as Gmail does it. After the answer and signature comes one line,
team.support.mail.wrote("On {0}, {1} wrote:",{0}when and{1}who), and one quoted block holding the latest earlier entry, with a vertical bar at its left. The older entries are nested inside that block, each under its own line and with a bar of its own, not stacked beside it. In the text part the same shape is>prefixes, one level deeper for each older entry. The HTML carries Gmail's own markers (gmail_quote,gmail_attr), so when a customer's reply brings it back, the cut that removes their mail client's quote removes ours too.o.Answers.QuoteStyle = SupportQuoteStyle.PerEntrykeeps one line and one block for each entry, as earlier versions did. - Each quoted entry is introduced by one translatable line,
team.support.mail.wrote— "On {0}, {1} wrote:",{0}when and{1}who. The time isyyyy-MM-dd HH:mminTimeZoneId, followed byUTConly when that is UTC. An unknown zone is refused at registration. - A frame of its own. With
MailTemplateOptions.SupportHtmlset, answers and their previews go out in it rather than in the template for mail to users — see the mail template. Its{{footer}}is always empty. - The language is the culture of whoever answers, as the request runs in it; there is no per-recipient language yet.
Signing an answer with a name
An answer can carry the name of the person who wrote it, in a closing you control. Off by default, so existing hosts send exactly what they sent before.
builder.Services.AddThargaSupportCases(o =>
{
o.Answers.NameTheAnswerer = true; // default: false
o.Answers.Closing = "Vänliga hälsningar,{newline}{Name}"; // default: the text key team.support.mail.closing, "Kind regards,{newline}{Name}"
o.Answers.Signature = ["Example Support"]; // still follows, as before
});
- The closing comes first, then the configured signature lines:
Vänliga hälsningar,/Daniel/Example Support, in the text and in the HTML signature paragraph.{Name}is the display name the service already records for the author, never their e-mail address;{newline}is a line break. The closing is a translatable text key. - Per answer. The answer box has a Sign with my name checkbox, ticked when the option is on and unticked when it
is off.
SupportAnswerChoice.SignWithNamecarries the choice toAnswerCaseAsyncandPreviewAnswerAsync. - Quoted history follows the answer. An earlier support entry that was signed with a name is quoted under that
name; one signed without is quoted under
SupportName, as before.
Which address an answer is sent from
A mailbox answers from its own FromAddress unless you declare more. Nothing about an address is built in: the
addresses, their names and their domains all come from configuration.
o.Email.FromAddress = "support@example.net";
o.Email.SendAs =
[
new() { Address = "help@example.net", Name = "Example Help" }, // an alias delivered into this mailbox
new() { Address = "info@example.org" } // an address on another domain works too
];
o.Email.SendAsDomains = ["example.net"]; // see "A staff member's own address"
"SendAs": [ { "Address": "help@example.net", "Name": "Example Help" } ],
"SendAsDomains": [ "example.net" ]
- An alias needs nothing more to be read. Mail to the alias is delivered into the mailbox's IMAP inbox, and the
address it was delivered to is remembered on the case.
SendAssays the same SMTP account may send as that alias, as with Google Workspace Send mail as; it need share neither the local part nor the domain ofFromAddress. - The default. An answer goes from the address the customer wrote to when it is the mailbox's own or one of its
SendAsaddresses, otherwise from the mailbox'sFromAddress. A case delivered to the main address is answered exactly as before. - Choose per answer. The route line of the answer box offers every address the person answering may send from,
across all mailboxes, with the default selected. The chosen address decides the SMTP account and the
Fromheader, and is stored on the entry (SupportMessage.SentFrom), so the history shows which address answered and a resend goes out from it again. - An address in no mailbox's list is refused by the service with an
InvalidOperationException, not only left out of the picker, whatever a component or a REST caller sends. - The reply address follows the sender, so the per-case address of a
help@answer ishelp+tracking-…@example.net, and a reply to it finds the case.
A staff member's own address
Some teams want the customer to see who answered. Set the role whose members may do that:
o.Answers.StaffSenderRole = "Support"; // default: none, so nobody answers from a personal address
A member of that role has an answer sent from Name <their e-mail address>, taken from their claims, when the
mailbox says its account may send as it: the address is in SendAs, or on one of SendAsDomains. Otherwise the
answer falls back, in order, to the address the customer wrote to and then the mailbox's own, and the personal
address is not offered in the picker.
- Replies still reach support.
Reply-Tois always the support address the customer wrote to, with the case's tracker when the mailbox uses one — also whenPerCaseReplyTois off — never the staff member's own address. - It is declared, not detected. A mail server that does not allow the account to send as an address either refuses the mail or quietly sends it from the account's own address, and neither says so up front, so the mailbox declares what it may do. If the server does refuse the sender, the answer is marked as not delivered with the address named, and is not silently sent from another one.
- Mail nobody wrote — receipts, the assistant's answers, notices — never goes from a personal address.
Where the answer goes, and its preview
Staff answering a mailed case see the address the answer is mailed to and the support address it is sent from — not only the author's name, which for a sender nobody knows is "Unknown". A case with no mail thread, raised on the site, says the answer is shown there instead. Outside production, when the outbound mail policy would not deliver to that address, it says so plainly: In this environment the answer is redirected to {override}, or …is not sent. In production, or for an address in an allowed domain, nothing more is added.
var route = await cases.GetAnswerRouteAsync(teamKey, caseId); // null for no such case
var preview = await cases.PreviewAnswerAsync(teamKey, caseId, body: null, bodyHtml: draft); // null when not mailed
GetAnswerRouteAsyncreturns aSupportAnswerRoute:ByMail,To,From(the address it goes from unless another is chosen),Senders(every address the caller may choose, each withAddress,NameandPersonal),SignWithName(the host's default),Mailbox(the mailbox whose account sends it), andEffect—MailPolicyEffect.None,RedirectwithRedirectedTo, orWithhold— fromIOutboundMailPolicy.Decide.SupportAnswerRoute.Siteis a case answered on the site: one with no mail thread, or a host that mails nothing.- A choice goes with the answer and the preview:
AnswerCaseAsync(…, new SupportAnswerChoice { SendFrom = "help@example.net", SignWithName = true })and the matchingPreviewAnswerAsyncoverload. Leave a part null for the default. PreviewAnswerAsyncreturns the draft as aMailPreview—From,To,ReplyTo(the per-case address when the mailbox uses one, and a support address whenever the answer is sent from a personal one),Subject, theHtmlin the host's mail template — its support frame when it has one — with the signature and the conversation so far quoted, and theTextalternative — composed by the code that sends the answer, without sending or storing anything. The draft is sanitized and derived exactly as an answer is, and written as by the caller. Files are not rendered; the dialog names them.- Both are authorized exactly as answering, since they show the correspondent's address to whoever may write to it; neither is audited, as reads are not — the answer is, when it is sent.
The components show them: SupportAnswerRouteLine (Route, and Choice to bind the sender and the signing choice) and MailPreviewDialog (in Tharga.Team.Blazor's
framework, Preview, FileNames), which renders the mail in an iframe given the HTML as srcdoc and sandboxed
with no permissions, so the template's styles stay inside it and nothing in it runs. A reader who may not answer
is shown no route and no preview. Their texts are team.support.answerRoute.* and team.mailPreview.*.
A case raised in the app, answered by mail
A case raised in the app has no mail thread, so its answers are shown on the site only. That is a dead end when the person who raised it cannot open support there, such as an organisation without access to the support panel. Support can answer such a case by mail, after which it continues as an ordinary mail thread.
The host says which address to write to, because the package knows an author only by identity and name:
public sealed class OrganisationContactResolver(IOrganisations organisations) : ISupportCaseContactResolver
{
public async Task<string> GetMailAddressAsync(SupportCase supportCase, CancellationToken cancellationToken = default)
=> (await organisations.FindOwnerAsync(supportCase.TeamKey, cancellationToken))?.Email; // null when there is none
}
builder.Services.AddScoped<ISupportCaseContactResolver, OrganisationContactResolver>();
- Without a resolver, or for a case it returns nothing for, nothing changes. The address must be one plain address and is never anything the person answering typed, so staff cannot send a case's answers somewhere of their own choosing. A resolver that throws is logged and read as no address.
- In
SupportCaseConversation, when the route is the site and an address resolves, staff are offered Answer by mail to . Ticking it shows where the mail would go from, with the send-from picker and the preview, and the outbound mail policy (redirect, withhold) shows in the route line as for any answer. - Through the service, the same:
GetAnswerRouteAsyncreturns the site route withMailOffer, the route the answer would take if mailed, andAnswerCaseAsync(..., new SupportAnswerChoice { ByMail = true, SendFrom = "help@example.net" })sends the first mail answer. - The first mail answer binds the case to the mail channel, with that address and the mailbox that sends from the chosen address. From then on
GetAnswerRouteAsyncreturnsByMail = truewith thatTo,FromandMailbox, the per-case reply address and the threading headers work as for a case that arrived by mail, and the customer's replies land on the case. AByMailfor a case that already has a thread does nothing more. An address the answerer may not send from is refused before the case is switched, and so isByMailfor a case the host resolves no address for. - The answer is still shown on the site; nothing about visibility changes.
- Audited as
switch-to-mail— who, the case, the address and the mailbox.
Or bind it when it is raised, when the host already knows the address:
var raised = await support.RaiseCaseAsync(teamKey, "Please add system X", body,
new SupportRaiseOptions { MailAddress = owner.Email }); // Mailbox: the name of one of the configured mailboxes, null for the primary
The case is then a mail thread from its first answer and staff need not switch. This overload is for host code: whatever address it is given is where answers go, so do not pass one the author typed without checking it belongs to them. It refuses an address that is not one plain address, an unknown mailbox, and a host with no mail set up, before anything is written, and is audited with the address and mailbox it bound.
Several mailboxes
o.Email is the primary mailbox. Add more with AddMailbox, each with a whole MailOptions of its own — its
own IMAP and SMTP account, sending address, folder, interval, recipient filter, PerCaseReplyTo and file limits:
builder.Services.AddThargaSupportCases(o =>
{
o.Email.Imap.Host = "imap.example.com"; // the primary, as before
o.Email.FromAddress = "support@example.com";
o.AddMailbox("billing", m =>
{
m.Imap.Host = "imap.example.com";
m.Smtp.Host = "smtp.example.com";
m.FromAddress = "billing@example.com";
});
// Or one per configuration section: Support:Mailboxes:{name}
foreach (var section in builder.Configuration.GetSection("Support:Mailboxes").GetChildren())
o.AddMailbox(section.Key, m => section.Bind(m));
});
- The name is a stable key stored on every case that comes in through the mailbox. It must be non-empty and
unique ignoring case, and
primaryis reserved: the primary is stored under that name, and its read position is unchanged, so there is nothing to migrate. Renaming a mailbox re-reads it from the start and sends its old cases from the primary. - Each mailbox is read on its own, by its own loop at its own interval, from its own position. One failing is logged by name and leaves the others reading.
- The same mail in two mailboxes opens one case. One ledger covers every mailbox, so a mail sent to both addresses becomes one case, bound to whichever mailbox read it first. Mail from any of our own addresses is never read back as a customer's.
- A case is answered from the mailbox it came in through — its account, its sending address and its reply address rules, behind the same outbound policy. A case whose mailbox is no longer configured is answered from the primary, with a warning naming it. A mailbox that reads but cannot send leaves its cases' answers not delivered rather than borrowing another mailbox's account.
- Staff see which address a case came in to, in the unassigned, across-teams and team queues
(
SupportMailboxAddress, "to {0}"), and the filter's search matches it. - A hosted mailbox works as any other, over IMAP and SMTP — for example with an app password where the provider requires one.
Cases from before 4.2 show no support address and are answered from the primary.
Health
The poller logs a failed read and tries again, and an answer that cannot go out is recorded on its case. Neither
tells anyone watching the service, so a changed password or a locked account shows as mail to support that simply
stops arriving. ISupportMailboxHealth.CheckAsync checks every mailbox that has an IMAP or SMTP server set, the
primary first, and returns one SupportMailboxHealth for each:
Name—primary, or the name the mailbox was added under.Reading— aMailboxHealth(IsConfigured,IsReachable,Error) for the IMAP account: it connects, signs in and opens the folder read-only. Not configured for a mailbox that only sends.Sending— the same for the SMTP server: it connects and signs in, and sends nothing. Not configured for a mailbox that only reads.IsHealthy— everything that is configured works.
It never throws, checks the mailboxes at the same time, and returns an empty list when no mailbox is configured. It
is registered with AddThargaSupportCases whatever is configured.
builder.Services.AddHealthChecks().AddCheck<SupportMailboxesCheck>("support-mail");
public class SupportMailboxesCheck(ISupportMailboxHealth mailboxes) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
var failing = (await mailboxes.CheckAsync(cancellationToken)).Where(x => !x.IsHealthy).Select(x => x.Name).ToArray();
return failing.Length == 0 ? HealthCheckResult.Healthy() : HealthCheckResult.Degraded($"Support mailboxes failing: {string.Join(", ", failing)}");
}
}
Each check opens a connection to every server, so let the health endpoint cache its result rather than call this on
every probe. Error carries the server's own message, which can name hosts and accounts: keep it off an endpoint
anonymous callers can read.
Bounces
A mail that cannot be delivered comes back to the address it was sent from as a delivery status notification.
When it names a support answer, that answer becomes not delivered, with the receiving server's reason; a bounce
never opens a case. A bounce that names no support answer is handed to every registered IMailBounceHandler until
one recognises it — that is how mail to users sent from a support address is marked
bounced. One that nobody recognises is logged at Debug, without addresses.
A reply to a mail the application sent
When someone answers a mail the application sent on its own, such as an invitation or a notice sent through mail to users, the answer reaches the support mailbox as a new case. The quoted thread is cut off the body, which is right for the transcript, so the mail being answered would appear nowhere.
A mail that matches no case is therefore looked up in the mail log by the thread ids it names (In-Reply-To, then
References), with the same Message-ID forms a bounce is matched with. Only a mail that was actually sent counts.
When one is found:
- The case records it as
InReplyToMailId. - When the reply has no subject of its own, the case takes the subject of the mail it answers.
- When the sender is verified and a member of several teams, the team the mail was about (its
TeamKeyin the mail log) settles which of them the case opens in. It is only looked for among the sender's own teams and never places an unverified sender, an address several accounts hold, or anybody the sender checks would not place; a team the sender is not in changes nothing. - Staff see In reply to: above the first message, with the subject, when it was sent and to whom, and a button to read the mail.
The mail is read under the mail log's own authorization: IUserMailHistoryService.GetMailContentAsync requires the
users:manage system scope, whoever sent the mail, and every read is audited with the mail's id and never an address.
A reader without it is told the case is a reply to a mail the application sent, and sees nothing of the mail.
A mail that has expired from the log is shown as no longer kept. A reply that continues a case, a reply to a mail the
log does not hold, and a reply to a mail this application never sent are handled exactly as before, and a mail log that
fails never costs the case.
Staff boards show this on their own. A host that renders SupportTranscript itself passes InReplyToMailId where the
reader is staff. A host's own IUserMailOutbox that does not implement FindSentByMessageIdAsync simply opens cases as
before.
Invitation mail is separate, deliberately
ThargaTeamOptions.Email configures invitation delivery and nothing else. It is not a fallback for support
mail and support mail is not a fallback for it: each sends from the address it is configured with, and every one
of them should be an address a reply reaches, because a no-reply address loses every reply. Bind both from the
same configuration section if you want one mailbox. With mail to users registered,
invitations go through its outbox and its address instead.
A public contact form
A contact form on a public page, with no signed-in user, opens a case in the unassigned queue through one call, exactly as a mail from an unknown sender does:
app.MapPost("/contact", async (ContactForm form, IExternalSupportCaseService support, CancellationToken ct) =>
{
// Your own defences first: a captcha, a honeypot, a rate limit. See "Whose job is what" below.
var raised = await support.RaiseExternalCaseAsync(new ExternalSupportContact
{
Name = $"{form.FirstName} {form.LastName}",
Email = form.Email,
Phone = form.Phone,
Organisation = form.Organisation,
ConsentGivenAt = form.Consent ? DateTime.UtcNow : null,
Fields = new Dictionary<string, string> { ["Source"] = "pricing page" }
}, subject: null, form.Message, ct);
return Results.Accepted();
});
IExternalSupportCaseService is its own interface, and the only anonymous one. ISupportCaseService stays
user-only; nothing in it is loosened for this. Registering AddThargaSupportCases registers both.
- Unassigned, never placed. The address is unverified, so it only suggests teams to staff, as a mailed case does
(
SenderNotVerified); it never places the case in a team and is never the author's identity. Staff assign it. - Answered by mail. The case is bound to the Email channel with the visitor's address as the correspondent, through the primary support mailbox, so an answer from staff is mailed to them and their reply by mail joins the case, as for any mailed case. With no mailbox that can send, the case is still opened so the message is never lost, but nothing can be mailed back.
- Who wrote is kept on the case.
SupportCase.ExternalContactholds the name, address, phone, organisation, your own extra fields and whether consent was given and when (ConsentGivenAt). The toolkit stores what the form says; what the consent covers is yours to word.SupportUnassignedViewshows it above the conversation, so staff see the phone number and the consent without hunting. The sample site has a working form at/contact. - Raised and audited like any case. The host is notified (
SupportCaseChange.Raised, from a channel, no team) and the audit trail gets asupport:raiseentry withsupport.case.source=web-form. The message, the address and the name are never recorded in it. A refused call is recorded too, as failed. - A receipt, if you want one.
o.External.SendReceipt = truemails the visitor a receipt through the same mailbox, quoting their message, with the thread started so their reply reaches the case.o.External.ReceiptTextsets what it says, for your site's language. It is off by default: a form that mails whoever types an address into it can be used to mail other people, so turn it on only behind the defences below. A receipt that cannot be sent is logged and never stops the case being opened.
Whose job is what
| The toolkit | The host | |
|---|---|---|
| Field and message length | Yes. Refused with an ArgumentException: subject 200, name and organisation 200, address 254, phone 50, message 10,000, at most 20 extra fields (name 50, value 500). SupportCaseLimits holds the numbers. |
Show the limits in the form |
| A missing or malformed address | Yes. One plain address only: no display name, no list, no line break to slip a header in. | Validate in the browser too, for the visitor's sake |
| Rate limiting | No | Yes. Only the host knows who is calling and how often is too often. ASP.NET Core's rate limiter on the endpoint does it. |
| Honeypot field, captcha | No | Yes, for the same reason |
| Whether the visitor consented | Stores the answer and the time | Asks, and words what is agreed |
| Telling the visitor it arrived | An optional receipt mail | Or your own confirmation page |
A support mailbox that accepts mail from anyone turns some of it into cases already; a public form is the same door with a form on it. The limits above bound each message, not how many arrive.
Writing first
Support staff sometimes have to start the conversation: to somebody who filled in the contact form days ago, or to a prospect. A mail sent from outside the toolkit loses the reply, because nothing ties the answer back to a case. Starting the case from here does:
var started = await SupportCases.StartMailCaseAsync(new StartMailCaseRequest
{
To = "lead@acme.example",
ToName = "A Prospect",
Subject = "Our offer",
BodyHtml = "<p>Hello, here is our offer.</p>",
Attachments = files, // optional
Choice = new SupportAnswerChoice { SendFrom = "help@example.net", SignWithName = true } // optional
});
It opens a case with the recipient as its ExternalContact and the message as its first entry, and sends the mail as an
answer is sent: from the chosen address or the mailbox's, signed and quoted as answers are, with the case's tracker in
Reply-To when the mailbox uses per-case reply addresses. The reply lands on the same case. The subject goes as written,
not as "Re:", since nothing is being answered. The case is returned.
- Unassigned or in a team. Leave
TeamKeyempty for the unassigned queue (needssupport:manageas a system scope), or give a team (needssupport:all:manage, as answering across teams does). A member of a team cannot start one; there is no author yet. - The case stands whatever the mail does. When the mail server is down the case is kept and its first message is marked as not delivered, where Send again reaches it. Everything that can be refused is refused before anything is written: a bad address, an empty message, files over the limits, and a sender the person may not use.
- Audited as
start-mail, with the case and how many files went, never the address or the text. - A case that support started waits on the reply, so it is not listed as needing an answer.
- The overload is a default interface member, so a host's own
ISupportCaseServicekeeps compiling and throwsNotSupportedExceptionfrom it.GetStartMailRouteAsync(to)gives the addresses the caller may send from, for a picker.
On the support boards
SupportUnassignedView and SupportAcrossTeamsView have a New message button. It opens the compose form: to and name, subject,
message, the send-from picker and the signature option as when answering, and attachments. In the across-teams view the case can be
placed in a team; the new case appears on the board without a reload. The texts are in SupportComposeMailText.
Elsewhere in your app
<SupportComposeMail To="@prospect.Email" ToName="@prospect.Name" Subject="Our offer" Started="OnStarted" />
@code {
private Task OnStarted(SupportCase started) => Link(prospect, started.Id); // connect the case to your own records
}
SupportComposeMail prefills what it is given and hands the new case back through Started; Contact keeps more than the address
and name on the case (phone, organisation, your own fields), and TeamKey places it. To show the conversation on a card, put
<SupportCaseById CaseId="@caseId" /> there:
<SupportCaseById CaseId="@prospect.CaseId" Loaded="OnLoaded">
<NotFound><p>No conversation yet.</p></NotFound>
</SupportCaseById>
It shows the thread in both directions with its files and the answer box, whichever team the case belongs to, and follows changes
to it live. It is guarded as the boards are, with ISupportCaseService.GetCaseByIdAsync(caseId): support:read for a case with no
team, support:all:read for a team's; a reader with neither is told so and shown nothing, and an unknown id is no case rather
than an error.
Attachments
A support message carries files both ways: what a customer's mail brought, and what support or the customer attaches to an answer or a reply.
- In: a mail's attachments, the images shown inside its body (with their Content-ID), and forwarded mail as
an
.emlfile. Signatures carry none, and neither does a bounce. - Out: an answer's files are mailed with it; an inline image is mailed beside the HTML that shows it.
- Kept outside the case, through
ISupportAttachmentStore, keyed by case.AddThargaTeamRepositoryregisters one over a GridFS bucket (SupportAttachment,ThargaTeamOptions.SupportAttachmentBucketName); register your own before it to keep files in blob storage. Without a store, a mail's files are named in its message as not stored, and a reply carrying files is refused. - Limits apply both ways, per mailbox, on
MailOptions:MaxAttachmentBytes(25 MB a file),MaxAttachmentTotalBytes(50 MB a message) andMaxAttachmentCount(20). A file over a limit, or one the store refuses, is left out with a note in the message, and the mail is kept. An answer is held to the strictest limits of the mailboxes that can send. - File names are sanitized — no path, no control characters, never empty — and the declared content type is kept as data, never trusted.
await cases.AnswerCaseAsync(teamKey, caseId, "Here is the report.",
[new SupportAttachmentUpload { FileName = "report.pdf", ContentType = "application/pdf", Content = stream }]);
await using var file = await cases.OpenAttachmentAsync(teamKey, caseId, sequence, attachmentId);
ReplyToCaseAsync and AnswerCaseAsync take files in their overloads, authorized exactly as without them; the
upload is measured while it is stored and every file of a refused message is discarded again. OpenAttachmentAsync
is authorized exactly as reading the transcript and returns null for an id that entry does not carry; you
dispose what it returns. GetAttachmentLimitsAsync() says what an answer may carry, so a form offers what the
service accepts.
Serve a file as SupportAttachmentContentTypes.ServedAs says, never as its declared type. A file opened from
your application runs in its origin, so only PDF, PNG, JPEG, GIF, WebP and plain text may open in the browser;
everything else is served as application/octet-stream and saved. The transcript does exactly this.
Reading an ordinary file is not audited; a reply or answer records how many files it carried
(support.message.attachments), never their names. Purging a team removes its files first.
SupportAttachmentPicker is the file chooser the answer boxes use: Files/FilesChanged, Disabled, and
Limits (the support service's when not set).
Files for support only
A member can hand support a file their colleagues reading the same case cannot open: a screenshot with customer data, an export, a contract. Only the product's support staff and the member who uploaded it see what it is or open it. The file never leaves the application, and its content is removed after a set time.
// A reply with ordinary files beside secure ones.
await cases.ReplyToCaseAsync(teamKey, caseId, "The export is attached.", null, [], [secureUpload]);
// A new case carrying secure files on its first entry.
await cases.RaiseCaseAsync(teamKey, null, "See the file.", new SupportRaiseOptions { SecureAttachments = [secureUpload] });
- Who sees it whole: cross-team support (
support:all:read/support:all:manage), the unassigned queue's staff for a case with no team, and the member who uploaded it (SupportAttachment.UploadedBy). Everyone else reading the case, the team's ownsupport:read/support:manageholders included, gets it withWithheld = true, its name and type blank and only its id and size kept, andOpenAttachmentAsyncrefuses them. This is decided once, in the authorizing decorator, so the UI, REST and MCP agree. - It never leaves. It is not attached to mail, not posted to Slack or any channel of your own, and not given to the assistant: the service strips secure files from everything it hands outward, and the mail channel skips any it is handed anyway.
- Only a member's reply or a new case carries one. Support's answers, mail-started cases and inbound mail cannot. Both lists on a reply count together against the attachment limits.
- Removed after
SupportCaseOptions.SecureFiles.KeepFor(30 days;TimeSpan.Zerokeeps them until support removes them and runs no sweep). A hosted sweep (SweepInterval, one hour;SweepBatchSize, 100) deletes the content and setsRemovedAt, so the entry still says a file was there. It is safe on several instances at once: each removal is recorded once. Cross-team support (support:all:manage) may remove one earlier withRemoveSecureAttachmentAsync; the uploader and the team's own readers may not. - Audited: opening a secure file and a refused opening (
open-secure-file), and removing one (remove-secure-file), withsupport.attachment.id, never the name. A reply or raise records how many it carried (support.message.secureAttachments). The sweep is logged, not audited. - Fail closed on the store.
ISupportCaseStore.KeepsSecureAttachmentsmust be true, or secure files are refused before anything is written: a store that drops the flag would turn the file into an ordinary one. The toolkit's MongoDB store keeps them. A store of your own sets it once it mapsSecure,UploadedByandRemovedAtand implementsGetSecureAttachmentsDueAsyncandTryMarkAttachmentRemovedAsync. After writing, the entry is read back, and if the flag was lost anyway the content is removed and the upload refused. GetAttachmentLimitsAsync()says whether secure files are taken (AcceptsSecureFiles) and how long they are kept (SecureKeepFor), so a component offers them only where they work.
In Blazor, SupportAttachmentPicker has a secure mode (Secure="true", with AlongWith for the files chosen in
the ordinary picker beside it); it shows nothing where the service does not take secure files. SupportCaseConversation
offers it to members, SupportPanel on its support tab only, and the transcript shows secure, withheld and removed
files distinctly, with a remove button for support staff.
The original of a mail
A mail that reaches a case is kept as it arrived (the raw MIME), beside the case's files, so staff can judge a suspicious sender, a delivery problem or a body trimmed too hard: its headers, To/Cc, original date, full quoted thread and structure.
- Kept on receipt, in the same store as the files (
ISupportAttachmentStore), and named bySupportMessage.OriginalId;HasOriginalsays whether there is one. It is never listed among a message'sAttachments, so the attachment limits do not apply to it and it is not offered as a file. Purging a case removes it with the files. - Its own limit,
MailOptions.MaxOriginalBytes(20 MB), because the original carries every file again, encoded. A mail over it is read as usual and kept without an original. A store that fails, or none registered, does the same; the mail is never lost. - Received mail only. An answer sent by mail has no original yet, and nothing received before this was kept has one.
- Read through the service:
ISupportCaseService.GetMessageOriginalAsync(teamKey, caseId, sequence)returns the bytes (amessage/rfc822message, ready to save as.eml) or null, authorized exactly as reading the transcript and not audited. It is a default member returning null, so a host's own implementation keeps compiling. - In the transcript, a message with an original shows Download original (.eml) and Read original (a window with the raw text, cut at 200,000 characters; the download has all of it), in the organisation's case view and the unassigned view alike.
- A host's own
IMailClientreads originals by implementing the newFetchAsync(position, includeRaw, cancellationToken); until then it reads as before and its mail has no original.
Formatting
Messages carry formatting: answers are written in a small rich-text editor, a mail's HTML is kept, and both are shown formatted — through one sanitizer, on every way in and again at every render.
SupportMessage.Bodyis always the plain text, which every reader can use: Slack, the notification, the mail's text part.BodyHtmlis the sanitized HTML beside it, or null for a plain message. Formatting that is only paragraphs, or longer thanSupportCaseLimits.MaxMessageHtmlLength(10 000), is not kept; the message is kept as its text.- The allow-list (
SafeHtml, inTharga.Team.Service): paragraphs, line breaks, headings toh4, bold, italic, underline, strike-through, lists, quotes, preformatted text and code, tables, links and images. Links are http, https or mailto only, and open in a new window withnoopener noreferrer. Images are shown only bycid:from the message's own files, or from data the caller read — a remote image becomes its alt text, so a mail cannot track who opened it. Scripts, styles, forms, frames, media and hidden text are removed with their content. - Inbound HTML is cut at the quoted thread — on the markers the common mail programs write — and dropped when the text lost a quote the HTML did not, when it carries no formatting, or when it is too long.
- Inline images show in place in the transcript: PNG, JPEG, GIF and WebP up to 2 MB, read through
OpenAttachmentAsync. An image shown in place is not listed again among the files; one that cannot be shown is. - A formatted answer is mailed as HTML beside the same text as before (
multipart/alternative), with the earlier conversation in quotes. With a mail template it is framed in it, and a plain answer is mailed as HTML too — its escaped text, the conversation in quotes — beside the same text.
await cases.AnswerCaseAsync(teamKey, caseId, body: null, bodyHtml: "<p>Fixed in <b>2.4</b>.</p>", attachments: []);
The HTML overloads of ReplyToCaseAsync and AnswerCaseAsync sanitize on the server, turn images into their alt
text, and derive the text from the HTML; body is used only when the HTML holds nothing readable.
For your own pages: RichTextEditor (Value/ValueChanged, Disabled, Label, Height, ShowHeadings) writes
HTML and sanitizes what is pasted into it, and RichTextView (Html, Images, Class) is the only way the toolkit
renders markup — it sanitizes whatever it is given, so a stored value is never shown as stored. SafeHtml and
HtmlImage are public for server code, and HtmlText in Tharga.Team.Email renders HTML as the plain text
the toolkit uses.
ShowHeadings="true" adds a text style picker to the editor's toolbar with Paragraph, Heading (h2) and
Subheading (h3), for text that is a structured document rather than a short reply. It is off by default, so
the answer boxes above keep their small toolbar. The picker offers only styles SafeHtml keeps as they are, and
its labels go through IThargaTextProvider under team.richText.textStyle, team.richText.paragraph,
team.richText.heading and team.richText.subheading. Text that already holds headings shows them whether or not
the picker is on.
An assistant answering first
A case can be answered by an assistant before, or instead of, a person. The customer chooses when they raise it, and can ask for a person at any point without losing the conversation.
Any model, because the toolkit does not choose one
The toolkit consumes IChatClient — Microsoft's abstraction from Microsoft.Extensions.AI — and nothing
else. It ships no provider adapter, references no vendor SDK, and names no model. Which model answers your
customers is one registration in your own host:
// Ollama, llama.cpp, a self-hosted model, OpenAI, Anthropic — all the same shape.
builder.Services.AddSingleton<IChatClient>(_ => new OllamaApiClient(uri, "llama3")
.AsBuilder()
.UseFunctionInvocation()
.Build());
Register nothing and there is no assistant. No responder resolves, the choice is never offered on the new-case form, and every case is answered by a person exactly as before. That is the default, and it is not a degraded state — it is what a host that never wanted one gets.
This is also why provider-specific capability is not lost by the toolkit being neutral. Prompt caching, effort levels, token counting and the rest belong to the client you construct, so they stay available to you: you own the object the toolkit calls.
A model per team
The registered IChatClient answers every team. To give teams different models, or none, register an
ISupportChatClientResolver. It is asked for the team's client on every answer, so a team that sets one up
or removes it is answered accordingly from its next message:
builder.Services.AddScoped<ISupportChatClientResolver, TeamModels>();
internal sealed class TeamModels(IMyTeamAiSettings settings) : ISupportChatClientResolver
{
// Null for a team means no assistant for that team.
public Task<IChatClient> GetAsync(string teamKey, CancellationToken cancellationToken = default)
=> settings.ClientForAsync(teamKey, cancellationToken);
}
A resolver is enough on its own: a host that registers one has an assistant without registering an
IChatClient. Register it before or after AddThargaSupportCases; either way it replaces the default.
A team the resolver returns null for is not configured:
- the new-case form does not offer it the assistant;
- a case raised asking for the assistant goes to a person;
- a case already with the assistant is declined, and the conversation says so beside Talk to a person.
Ask before offering. GetAssistantReadinessAsync(teamKey) answers Ready, NotConfigured, or
NotRegistered when the deployment has no assistant at all, so a component can say why the assistant is
missing rather than only hide it. It requires membership of the team, as raising a case does. A resolver that
throws reads as NotConfigured: somebody reporting a problem gets their case whatever the assistant's settings
are doing.
A host's own ISupportResponder answers readiness through GetReadinessAsync, a default member answering
Ready, so an existing responder is unchanged. A test double that skips the default member answers
NotRegistered, which the service reads as Ready too: only the service can say there is no responder.
Each team chooses its connection
Rather than writing a resolver, let each team choose in a component. A team administrator picks one of:
- The platform's model, the
IChatClientyou register. A team that never chose has this. The page names it, such as "The platform's model (ollama, llama3)", from theChatClientMetadatathe client reports; a client that reports none is shown without a name. - Neurolito, with the team's own key, with the model picked from what Neurolito offers that key.
- Anthropic, with the team's own API key, with the model picked from what Anthropic offers that key.
- OpenAI, with the team's own API key, with the model picked from what OpenAI offers that key.
- Ollama or llama.cpp, on the team's own server: the team gives the server's address, and a key only if the server asks for one.
- Off: no assistant for the team, so every case goes to a person.
builder.Services.AddThargaSupportCases();
builder.Services.AddThargaSupportAiConnections(); // the choice, its service and its component
builder.Services.AddThargaSupportAiProviders(); // Neurolito and Anthropic (package Tharga.Team.Support.Anthropic)
builder.Services.AddThargaSupportOpenAIProviders(); // OpenAI, Ollama and llama.cpp (package Tharga.Team.Support.OpenAI)
builder.Services.AddDataProtection() // the key is encrypted with Data Protection...
.SetApplicationName("MySite")
.PersistKeysToThargaMongo(); // ...so keep the key ring where every instance reads it
<SupportAssistantConnectionView />
Register the provider packages you want, one or both. Every provider either registers is offered. A factory of your own (
ISupportChatClientFactory) sits beside them; a kind two factories offer is reached through the last registered. Calling a registration again changes its options and adds nothing.Each kind can be left out.
o.OfferAnthropic = falseinAddThargaSupportAiProviders, ando.OfferOpenAI,o.OfferOllamaando.OfferLlamaCppinAddThargaSupportOpenAIProviders. A team already connected to a kind that is left out is treated as having no connection until it chooses again.An OpenAI-compatible address includes the version path, as each provider documents it:
https://api.openai.com/v1, an Ollama server's…/v1, a llama.cpp server's…/v1. The models are listed from{address}/models; OpenAI lists every model the key may use, including some that do not chat, so Test before saving.A server of the team's own starts from no address, because the site's own machine is not the team's server. Set
o.OllamaBaseAddressoro.LlamaCppBaseAddresswhere every team shares one server you run. Without a key, noAuthorizationheader is sent.An address is https, or http on the same machine as the site, and never carries credentials. A team's server elsewhere on the network needs https in front of it, such as a reverse proxy; plain http to other hosts is refused so nobody who may change the connection can make the site call internal addresses.
AddThargaSupportAiProviderswas calledAddThargaSupportAnthropicuntil 4.5. The old name still works and is marked obsolete.The
assistant:manageteam scope governs reading and changing the connection. It is granted to team Administrators by default; seto.ScopeAccessLevelto change who, or tonullto grant it by no level. Members are still offered the assistant by readiness, not by this scope.The key goes in and never comes out. It is encrypted under a Data Protection purpose of its own, never returned by the service, never logged, and never audited by value; the component clears it once saved. An empty key field keeps the stored key, but only for the same provider and address, so a stored key is never sent somewhere new. For a server that needs no key, moving it to a new address with the field empty sends none.
A provider is saved only once it answers. Saving lists the provider's models for the key and refuses a model the key may not use. Load models and Test do the same without saving; a refused key, a wrong address or an unreachable server is said in words.
Changes are audited under
assistant(connect,test,use-platform,turn-off), with the kind, model and host, and purging a team removes its connection.
Over REST. Where everything in your UI is also in your API, map the same service as endpoints instead of writing a controller over it:
// The endpoints use the toolkit's API policy, which comes with its controllers: on in AddThargaTeam unless
// o.Controllers is null, or AddThargaControllers() without it.
app.MapThargaSupportAiConnection(); // under /api/support/assistant/connection by default
| Method | Route | Does |
|---|---|---|
| GET | {path} |
The connection, without the key |
| GET | {path}/choices |
What the team may choose, with the address each provider starts from and whether it needs a key |
| POST | {path}/models |
The models a provider offers, for the key in the body or the stored one |
| POST | {path}/test |
Asks the model one short question; saves nothing |
| PUT | {path} |
Connects to a provider. The key is accepted here and never returned |
| PUT | {path}/platform |
Uses the platform's model |
| PUT | {path}/off |
Turns the assistant off for the team |
The body of models, test and the connecting PUT is a provider request:
{ "kind": "Ollama", "baseAddress": "https://ollama.example.com/v1", "apiKey": null, "model": "llama3.2:latest" }
- The team comes from the credential, never the request, as on the audit API: a team API key's own team, or the
team a system key names in
X-Team-Key. A caller bound to no team gets 400. - The service's checks are the endpoints' checks.
assistant:manageon the team is required (403 without it), and every change is audited as it is from the component. - Listing models, testing and connecting answer 200 when they worked and 422 when they did not, with why in the body. Platform and off answer 204. No answer carries the key, not even a provider's error that echoed it.
- Kinds are written by name (
"OpenAI") and read by name or number. The method returns the route group, so you can add conventions such as an OpenAPI tag.
Over MCP. An agent can do the same through seven tools (support.ai.get_connection, get_choices, list_models,
test, connect, use_platform_model, turn_off), opt in with mcp.AddTeam(o => o.ExposeSupportAiConnection = true).
They use this same service, so assistant:manage, the audit and the key rules above are the tools' too, and the team is
the caller's own. Unlike REST, kinds are written by name only. The Tharga.Team.Mcp README lists the tools.
Persist the key ring. Data Protection's default keeps its keys on the local file system. On more than one
instance, or in a container whose file system does not survive a restart, a key stored by one instance cannot
be read by another, and the team is asked to enter it again. PersistKeysToThargaMongo() keeps the ring in the
database the toolkit already uses.
What the customer sees
The new-case form offers the assistant, unticked, only when the team is ready for one. A case being answered by an assistant offers Talk to a person, which stops the assistant and leaves the same case, with the whole transcript, to whoever picks it up. That transition is one-way — handing back after somebody has asked for a human would answer a question they have already declined to have answered that way.
An answer the assistant wrote is recorded as SupportMessageKind.Assistant and badged in the back-office
transcript, so an agent can tell what the customer was already told by a machine from what a colleague told
them. The two carry very different weight.
What it does to the queue
A conversation the assistant is answering never waits for support. It waits for the assistant, so it is in no awaiting-an-answer count, and its answers are never unread — the customer reads them as they arrive. Counting it would flick support's counter up and back down on every message somebody writes to the assistant.
Once it is handed to a person it is an ordinary case, and the customer's first message to that person puts it in front of support like any other.
A conversation the assistant is answering reaches no channel. No Slack thread and no mail to support are opened for it. Asking for a person opens nothing by itself; the customer's first message to a person opens the channel, carrying the conversation so far, so whoever picks it up starts from what was already said. A customer who asks for a person from the start gets the channel at once.
It answers; it does not act
The built-in tools are reads: the caller's own cases (get_my_cases), a search through them by subject and by what
was written in them (search_my_cases), and one case's transcript (get_case_messages). Closing, assigning and
reopening stay with people — an assistant that can close its own cases can close the ones it answered badly.
It answers only the person who raised the case. RunAssistantAsync does nothing for anybody else, even somebody
who may write in the case. The tools read with the caller's rights, and the answer is kept where everybody who reads
the case sees it, so run by a teammate or by support with wider rights it could quote what the author may not see.
Every tool reads through the same scope-checked service any other caller uses, so the assistant sees exactly what the person it is answering would see. The responder is handed the case and its transcript rather than fetching them, so it holds nothing it could reach further with.
Add your own tools. The toolkit knows about teams, membership and cases; it knows nothing about the
product your customer is actually asking about. Implement ISupportAssistantTools to replace the built-in
set, or resolve the built-in one and add to what it returns. Keep every tool reading through a scope-checked
service — a tool that reaches the store directly is a second enforcement point, and the assistant would be
the one caller able to use it.
Answers with links
Set o.Assistant.CaseLinkTemplate to where a case is on your site, as a path such as /support/{caseId}, and every
case get_my_cases and search_my_cases return carries its Link; their descriptions tell the model to link to a case
it mentions, in Markdown. Unset, the default, the assistant has no links to give.
SupportPanel and SupportCasesView render the assistant's answers as Markdown with HTML off. A link stays a link
only when it is a path on your site, such as /support/abc. Any other, to another host or with a scheme such as
javascript:, is written out as its text and address: the model writes these, a member's own words can steer it, and a
link off the site is how a steered answer would send somebody to a page that only looks like yours.
What it could not do, and how its answers were rated
Whatever tools the host supplies, the assistant is also given report_missing_skill. When a member asks for
something none of its tools can do, the model calls it with what was asked, in a few words, and then says it cannot
help. What it reports comes back as SupportAnswer.Gaps and is kept on the case as SupportCase.AssistantGaps,
whether it answered or declined: trimmed, at most 200 characters each, once each, the newest 20 per case.
The person answered rates each answer, thumbs up or down, in the panel and on the support page; the same thumb
again takes it back (RateAnswerAsync, with SupportAnswerRating.None). Only the person who raised the case may rate,
because it is them the assistant answered, and only the assistant's answers can be rated. The rating is kept on the
answer (SupportMessage.Rating), counted on the case (AnswersRatedUp, AnswersRatedDown), audited as
support:rate-answer, and shown to support as a mark on the answer. Rating is off by default:
o.Blazor.Support.RateAnswers = true puts the thumbs and the marks on the panel and the support page. Turned off
again, ratings already given are kept.
SupportAssistantFeedbackView lists all of it across every team for the people who build the assistant: what it could
not do, the same thing asked in several cases as one entry, most asked first; and the cases with an answer rated not
helpful, and helpful, newest first. Each case opens as on the desk. It reads through GetCasesAcrossTeamsAsync, so it
needs support:all:read. SupportAcrossTeamsView marks a case with The assistant could not help (what it was
shows on hover), Rated not helpful or Rated helpful. A store of your own keeps them by implementing
ISupportCaseStore.AddAssistantGapsAsync, whose default keeps nothing, and SetAnswerRatingAsync, whose default
throws.
How the whole conversation was rated
The person answered can also rate the conversation as a whole, because a conversation can let somebody down even when each answer in it looked right on its own. Once the assistant has answered, the panel asks under the conversation how it did, with a thumb up and a thumb down. Thumbs-up is sent at once, and the same again takes it back. Thumbs-down asks what the assistant could have done better, which is optional, says what the feedback is used for, and is sent with Send; a short thank-you follows either way.
RateConversationAsync(teamKey, caseId, rating, comment) does it, with SupportAnswerRating.None to take a rating back.
Only the person who raised the case may rate, and only a conversation the assistant answered at least once; rating
again replaces the earlier rating. A comment is trimmed, a blank one is none, and one longer than a message is refused.
The rating is kept on the case as SupportCase.ConversationRating (the rating, the comment, when, and by whom), audited
as support:rate-conversation with the verdict but never the comment, and announced as
SupportCaseChange.ConversationRated. It is off by default: o.Blazor.Support.RateConversations = true puts the
question in the panel and the rated conversations in SupportAssistantFeedbackView, newest rated first, each with its
mark and, when it is opened, its comment above the conversation.
Every string is a key in SupportPanelText with an English default: team.support.panel.rateConversation,
conversationGood, conversationNotGood, conversationComment, conversationNotice, sendConversationRating and
conversationThanks. Give team.support.panel.conversationNotice your own wording through IThargaTextProvider, so the
person reads who will use what they send, in their own language.
Handing a rated conversation to you. Register an ISupportConversationFeedbackSink and every rating the options let
through reaches it once it is kept: thumbs-down only by default.
builder.Services.AddThargaSupportCases(o =>
{
o.Assistant.ConversationFeedbackRatings = [SupportAnswerRating.Down];
});
builder.Services.AddScoped<ISupportConversationFeedbackSink, MailFeedbackToSupport>();
internal sealed class MailFeedbackToSupport(IMySupportMail mail) : ISupportConversationFeedbackSink
{
public Task HandleAsync(SupportConversationFeedback feedback, CancellationToken cancellationToken = default)
=> mail.SendAsync($"The assistant was rated {feedback.Rating}", SupportConversationFeedbackJson.Serialize(feedback), cancellationToken);
}
SupportConversationFeedback carries the case id, the team key, the rating, the comment, when it was rated, the culture
the person was using, and the conversation: each entry's sequence, kind, whether it was written from the support side,
time and text, and for the assistant's answers each tool it called, by name, and whether the call succeeded. It never
carries what a tool was asked for or what it returned, which can hold data the person did not choose to send, nor
anything written for support's eyes only. SupportConversationFeedbackJson.Serialize writes it in the one shape every
host sends: indented, camelCase, enums by name, letters of every script as they are.
- Every sink is told. One that throws is logged and never fails the rating; the others are still told.
- Whether a call succeeded is
SupportAssistantCall.Succeeded. The built-in assistant records it from the tool loop: a call whose result came back without an exception succeeded. A responder of your own sets it onSupportAnswer.Calls; left unset, and on every answer kept before it existed, it reads as unknown. - A store of your own keeps the rating by implementing
ISupportCaseStore.SetConversationRatingAsync, whose default throws, for the same reason asSetAnswerRatingAsync.
Running it
Raising and replying stay fast; asking for the answer is a separate call, because a model can take tens of seconds and burying that inside a write makes reporting a problem feel broken.
var raised = await cases.RaiseCaseAsync(teamKey, subject, body, SupportAssistance.Assistant);
await cases.RunAssistantAsync(teamKey, raised.Id); // returns false when there is nothing to do
RunAssistantAsync is safe to call unconditionally: it does nothing when the case has no assistant, when the
customer has asked for a person, when the host registered no responder, or when the team has no model. The shipped components already
call it, so a host using <SupportCasesView /> needs none of this.
Watching the answer being written
Pass an IProgress<SupportAssistantProgress> and you are told how far the assistant has got while it works: the answer
as written so far, which round it is on, the tools running now, and every service call it has made.
SupportPanel and SupportCasesView do this, so the customer reads the answer as it is written instead of waiting for
all of it:
var answered = await cases.RunAssistantAsync(teamKey, caseId, new Progress<SupportAssistantProgress>(p => Show(p.AnswerSoFar, p.Tools, p.Calls)));
- How long it has been working is shown beside the dots, counting up each second: Working 2 (1m 23s), or Working 2 (23s) under a
minute. Each report carries
StartedAt, set by the service when it began on the question, so a display counts from the real start and not from when a page was opened. It is one translatable text with the pass and the time as placeholders,team.support.transcript.workingLoopTimed(Working {0} ({1}), in Swedish Arbetar {0} ({1})), and the time is worded byteam.support.transcript.elapsedSeconds({0}s) andelapsedMinutes({0}m {1}s). The same time is kept with the answer asSupportAssistantUsage.Elapsedand shown under it beside its service calls and tokens, 2 service calls · 830 tokens · 1m 23s, also when the provider reported no tokens.SupportAssistantStatusis the component that ticks, if you build your own display. - A round is one call to the model. The model either writes or asks for tools; when their results go back, the next
round starts. An answer that looks something up takes two rounds or more, which the tool loop of
UseFunctionInvocationruns for you. - Until the first words arrive, the assistant's side says what it is doing, followed by flashing dots that stand
for the "…": "Working" (
team.support.panel.workingin the panel,team.support.cases.assistant.thinkingon the support page), then "Working 2" once it has gone round the tool loop twice, counting each time it asks for service calls (team.support.transcript.workingLoop). A service call part way through the text is said the same way under it. - While a reasoning model thinks,
SupportAssistantProgress.Thinkingis true and the text reads "Thinking" (team.support.transcript.thinking), or "Thinking 2" once it has gone round the loop (team.support.transcript.thinkingLoop).ChatSupportRespondersets it when an update carriesTextReasoningContentand no text yet, and clears it on the first text or tool call. A host with its own responder sets the flag the same way. - Each report is the whole state, the text so far included, not what changed, so a report that is missed costs nothing.
- What is kept is what is returned. The answer is appended once, when it is complete, and everybody else reads it then. An answer that breaks off halfway is declined, and nothing that was shown on the way is kept.
- Only the caller sees it on the way. Reports go to the progress you pass and nowhere else, never through
ISupportCaseNotifier. The call is authorized and audited exactly as the one without reports. - Reports arrive on another thread, so a component marshals with
InvokeAsyncbefore showing one. - The model is streamed only when somebody watches. Without a progress, it is asked for the answer in one piece,
as before.
ChatSupportResponderstreams throughIChatClient.GetStreamingResponseAsync, tools included, and Neurolito and the Anthropic API both stream. A responder of your own answers in one piece and reports nothing, unless it implements theISupportResponder.AnswerAsyncoverload that takes the progress.
What an answer took
The calls the assistant made for an answer are kept with it, as SupportMessage.AssistantCalls: each tool's name and
what it was asked for, written out short as text: "export". So are the tokens the model reported, every round of the
tool loop added up, as SupportMessage.AssistantUsage (input, cached input, output and total, with the provider and
the model that answered). The panel and the support page show
them under the answer, folded as 2 service calls · 830 tokens, opening to a row per call such as
search_my_cases(text: "export") and Tokens: 610 in, 220 out.
The tokens are the provider's own count, read from what the tool loop returns in one piece, or added up from each round's report when streamed. A provider that reports none leaves the usage empty rather than zero.
The provider and the model come from the chat client's
ChatClientMetadataand the response'sModelId; a response that names no model is taken to be the client's default model.Asked in one piece or streamed, they are read from what the tool loop yields, so a host's own tools are listed as well as the built-in ones.
report_missing_skillis not: it notes what the assistant could not do, which is listed on its own.They are bounded like anything else the model writes: the first
SupportCaseLimits.MaxAssistantCalls(20) of an answer, each written out to at mostMaxAssistantCallArgumentsLength(200) characters.What a call was asked for can hold words from the conversation, such as what the member searched for, so it is kept on the case and shown only where the case can be read. It is not audited.
Who sees them is the host's choice,
o.Blazor.Support.AnswerDetailsShownTo:Everyone, the default;Support, only whoever reads the case from the support side; orNobody. They are kept either way.A responder of your own lists its calls and tokens by returning them on
SupportAnswer.CallsandSupportAnswer.Usage.What each tool returned can be kept too, as
SupportAssistantCall.Result, so a stored conversation shows what the assistant was told as well as what it asked. When an answer is wrong, that is what tells a tool that returned the wrong thing from a model that misread a right one. It is off by default, because a result can hold the tenant's own data:o.Assistant.StoreCallResults = true; o.Assistant.MaxStoredCallResultLength = 2000; // the default; a longer result is cut and ends with "… [cut]"With it off nothing is stored, whatever a responder of your own puts in
Result; with it on, the built-in responder fills it with the text the tool returned (a string as it is, anything else as JSON) and a responder of your own passes it on the call. The result is never shown in the panel and never part of the rated-conversation feedback, which names the tools and nothing they returned. A message kept before this existed reads back with an empty result.
What the assistant used, per team
Every time the assistant is asked, one SupportAssistantUsageRecord is kept: the team, the case, who asked, the
provider and model, the input, cached, output and total tokens, the service calls, whether it answered, how long it
took and when. Never what anybody wrote: not the question, not the answer, not a tool's arguments. A host that
lends its own AI account to teams bills from it.
builder.Services.AddThargaSupportCases();
builder.Services.AddThargaTeamRepository(...); // Tharga.Team.MongoDB keeps the records, in SupportAssistantUsage
@* For staff holding support:usage:read *@
<SupportAssistantUsageView />
- Declines are kept too. A decline spent the tokens all the same, and is the one a bill would otherwise miss.
- Written by the support service, not the responder, so a responder of your own is recorded by returning
SupportAnswer.Usage. An answer with no usage writes nothing. - Every
ISupportAssistantUsageSinkis told, so you can also forward the records to your own billing. The MongoDB store is one sink; a sink that throws is logged and never fails the answer, and the others are still told. ISupportAssistantUsageService.GetUsageAsync(from, to, teamKey)totals a period per team, provider and model: answers, declines, service calls and tokens.tois exclusive. It needs thesupport:usage:readsystem scope, which nobody holds by default; map it to a system role as you dosupport:all:read.SupportAssistantUsageViewshows the same for a period (this month by default) with a total, team names where the reader may read the team directory, and the team key where not.TeamKeynarrows it to one team.- Sorted, with a period and a cost. The view's column headings sort (click again to reverse), a line above the table adds up the period (answers, tokens in, cached and out, and the cost), and a Cost column shows what the priced answers cost. See What an answer cost below.
- A purged team's records go with it: each names who asked.
- Your own store implements
ISupportAssistantUsageStore(a sink that can also be totalled) and is registered before the repository; the toolkit's registration then leaves it in place.
What an answer cost
Each usage record keeps the price per million tokens it was given at: the model's input, cached input and output
price, the currency, and the cost worked out from them (SupportAssistantUsageRecord.PriceInput, PriceCachedInput,
PriceCacheWrite, PriceOutput, Currency, Cost). A later price change therefore never rewrites what an earlier
answer cost. Cached input is charged at its own price, or at the input price where none is given. Tokens written to
the provider's cache (CacheWriteTokens, reported by Anthropic as cache creation) are charged at the cache-write
price, or at the input price where none is given. The input count includes both cached reads and cache writes, so the
cost is the fresh input at the input price, plus the reads, plus the writes, plus the output, each at its own price.
Reasoning tokens are not added: the output count already includes them.
- Only the platform's catalogue prices an answer. A team on its own provider, a team that is off, answers from before prices were recorded, and a host with no catalogue are recorded without a cost, shown as a dash, never as zero.
- Totals add the cost up per team, provider, model and currency. The total row and the line above the table add it up only where the priced rows share a currency; across currencies a sum means nothing, so none is shown.
ISupportAssistantPricingis what the support service asks for the price.AddThargaSupportPlatformAiCatalogueregisters one reading the catalogue; register your own before it to price answers from somewhere else. A lookup that fails costs the record its price, never the answer.
The platform's AI catalogue
By default every team on the platform is answered by the one IChatClient the host registered. With the catalogue,
the platform's staff curate which providers the platform has accounts with and which models teams may choose from,
and each team chooses one in SupportAssistantConnectionView.
builder.Services.AddThargaSupportAiConnections();
builder.Services.AddThargaSupportPlatformAiCatalogue(); // opt-in; the store comes from AddThargaTeamRepository
builder.Services.AddThargaSupportAiProviders(); // or OpenAI: the kinds a provider can be
@* For staff holding support:aicatalogue:manage (Configuration) and support:usage:read (Usage) *@
<SupportAssistantAdminView />
- A provider is a name, a kind, an address and a key. The key is encrypted with Data Protection under a purpose of its own, never returned and never in a problem text or an audit entry; the service says only whether one is stored. A new key is checked against the provider (by listing its models, which spends no tokens) before anything is saved. Leaving the key out keeps the stored one only while the kind and the address are unchanged, so nobody allowed to edit the address can have the key sent to a server of their choosing.
- A model names its provider and the model's identifier there, and carries what a team should know before choosing it (where it is processed and stored, a link to the data processing agreement) and its prices per million tokens. A model that is not offered stays in the list for staff and cannot be chosen.
- One default. It answers a team that has not chosen one, and a team whose chosen model staff stopped offering. It must be an offered model.
- A provider cannot be removed while a model is reached through it, identifiers are unique, an agreement link must be https, and a price cannot be negative.
- No catalogue, no change. Without
AddThargaSupportPlatformAiCatalogue, or while it offers no model, the registeredIChatClientanswers as before. The catalogue is read on every answer, so a changed default, key or price reaches the next answer without a restart; a client is reused until the catalogue or the team's choice changes. IPlatformAiCatalogueServiceis the one place it is authorized (support:aicatalogue:manage, held by no level and no role by default; grant it to staff or a system key) and every change and every test is audited underassistant. Over REST,MapThargaSupportPlatformAiCatalogue()maps it under/api/support/assistant/catalogue:GET,PUT /provider,DELETE /provider/{id},GET /provider/{id}/models,PUT /modelsandPOST /models/{id}/test.- A team chooses with
ISupportAiConnectionService.UsePlatformModelAsync(teamKey, modelId)(over RESTPUT /platform?model=ID, over MCPsupport.ai.use_platform_modelwithmodelId); the offered models areSupportAiConnectionChoices.PlatformModels. A decorator of your own must forward the new overload. SupportAssistantAdminViewis the staff page around it: a Usage tab and a Configuration tab, the second only for a caller holding the catalogue scope and only where the catalogue is registered.?tab=configurationopens it.
A spend allowance per team
A host that lends the platform's AI to its teams can limit what each team spends on it each month. The limit is set in money, in the catalogue's currency, and a team is not shown money: it is shown how much of its allowance it has used, in a unit the host chooses. Nothing is limited until a limit is set.
builder.Services.AddThargaSupportCases(o =>
{
o.Assistant.Allowance.DefaultLimit = 25m; // per team per month, in the catalogue's currency; null (the default) limits nobody
o.Assistant.Allowance.Display = SupportAllowanceDisplay.Units; // Share, Units (default), Tokens or Money
o.Assistant.Allowance.UnitValue = 0.0001m; // what one unit is worth; the default is a hundredth of a cent
o.Assistant.Allowance.UnitLabel = "WU"; // "units" by default
o.Assistant.Allowance.WarnAt = 0.8m; // the share at which the bar turns to a warning
});
- What is counted. The cost of the month's answers, as each was priced when it was given (see What an answer cost). The period is a calendar month in UTC. A team on its own provider, a team that is off, and a model with no price cost the platform nothing and are never limited.
- What a team reads.
Displaychooses:Shareonly the percentage;Unitscost divided byUnitValue, calledUnitLabel;Tokensan estimate at the rate the team's own answers have cost;Moneythe amounts as they are, for a host that wants them shown. Members always see the share. A team's administrators (assistant:manage) also see the amounts, and an estimate of how many questions are left on the model they use, from what answers have cost over the lastAverageOverDays(30). - One limit for all, and one for a team. The default is
DefaultLimit, or what staff set at runtime, which beats it (ISupportAssistantLimitService.SetDefaultLimitAsync). A single team can have a limit of its own, higher, lower or none (SetLimitAsync), which beats the default; clearing it puts the team back on the default. Staff do both inSupportAssistantLimitView, which is a Limits tab onSupportAssistantAdminViewfor a caller holding thesupport:allowance:managesystem scope (held by nobody by default; grant it as you dosupport:aicatalogue:manage). Changes are audited underassistant, and a purged team's limit goes with it. The limits are kept byTharga.Team.MongoDBinSupportAssistantLimit(ThargaTeamOptions.SupportAssistantLimitCollectionName); the default is stored under a reserved key that is never a team. - When it is used up the assistant does not ask the model: no tokens are spent and no usage record is written for a
question never sent, and no new case is handed to it.
GetAssistantReadinessAsyncsaysSupportAssistantReadiness.AllowanceUsed. Support is unaffected. - Your own counter. The default source (
ISupportAssistantAllowanceSource) sums the usage store. A host that also spends on the model elsewhere registers its own beforeAddThargaSupportCases; it returns aSupportAssistantAllowancewith the full amounts, in the units the team reads, and the service takes them out for a member. A source that throws counts as not used up, and is logged: a broken counter must not take the assistant from every team.
The bar. SupportPanel shows a progress bar on the assistant tab, for a team that is limited: the share used, when it
starts again, and for administrators the amounts and the questions left. It turns to a warning at WarnAt and to danger when
used up. It is optional and on by default:
o.Blazor.Support.ShowAllowance = false; // hides the bar and nothing else
With the bar off the assistant still stops, and says when it starts again.
When the assistant cannot answer. The assistant tab stays, with a notice instead of a silent absence, and the message box is disabled; the support tab still works. Three reasons, each its own readiness:
| Readiness | Why | A member is told | An administrator is offered |
|---|---|---|---|
AllowanceUsed |
The team has spent its allowance | When it starts again | Connect their own subscription |
ProviderRefused |
The provider refused the account: a revoked key, billing, a usage or spend limit | To try again later | Another platform model, with what an answer costs and the questions left; connect their own subscription |
Held |
The host's own gate says so | The host's message | What the host places (below) |
Where the team has support, a line under the notice sends them to it. Where it has none, a member is told to ask one of the team's
administrators (text only; there is no request to send), and an administrator is shown the actions instead. Another model is
offered only when the provider refused the account: an allowance is money, so it is used up on any model and changing model
frees nothing. Connecting their own subscription, which nothing limits, is offered in both cases and opens
SupportAssistantConnectionView in a dialog. Choosing a model or connecting clears the remembered refusal, so the next
question is tried at once.
- What counts as a provider refusing the account. 401, 402 and 403 always. 400 and 429 only when the provider's words say
credit, quota, billing or a limit, because Anthropic reports an empty balance as a 400 and an exhausted quota as a 429, which
also carries ordinary rate limiting. 5xx and plain rate limits are not. The status is read from the exception by name
(
StatusCode,Status), so no provider's package is referenced. The words are English, matched as substrings. - Remembered per team, in memory, for
ProviderRefusalRetryAfter(10 minutes by default), so the assistant does not send a request that is bound to be refused with every question. It clears when an answer goes through.
Being told, and refusing for your own reasons.
builder.Services.AddScoped<ISupportAssistantRefusalSink, NotifyOurPeople>();
builder.Services.AddScoped<ISupportAssistantGate, PlanGate>();
<SupportPanel>
<AssistantTop Context="state">
@if (state is SupportAssistantReadiness.AllowanceUsed)
{
<a href="/billing">Buy more</a>
}
</AssistantTop>
</SupportPanel>
ISupportAssistantRefusalSinkis told when a question is refused: the team, the case, the reason, the time, and the allowance (forAllowanceUsed) or the gate's message (forHeld). Use it to notify yourself. It is told once per spell, not once per question: again only after the assistant has answered that team, or, for the allowance, in a new period. The memory is the process's, so a restart may repeat a message. It fires for a question actually refused, not when the panel is opened and not when an answer crosses the limit. A sink that throws is logged, never changes the refusal, and the others are still told.ISupportAssistantGatereturns aSupportAssistantHoldwith a message, or null to let the assistant answer. It is asked before every question and whenever readiness is read, so keep it quick. It comes before the allowance, the panel shows its message in place of the conversation, and the toolkit's own actions are not offered: the rule is yours whatever the team connects. A gate that throws holds nothing back.SupportPanel.AssistantTopis your own content at the top of the assistant tab, above the bar, told the readiness, for what only you can offer, such as buying more. It is not shown on the support tab.- Texts are in
SupportPanelText(the notice, the bar) andSupportRefusalActionsText(the actions), andSupportAssistantLimitViewText(the Limits tab), each with an English default.
Not covered here: REST endpoints and MCP tools for the allowance and the limits, as the connection and the catalogue have.
Settings
builder.Services.AddThargaSupportCases(o =>
{
o.Assistant.Instructions = "You answer support questions for Contoso Archive…";
o.Assistant.Timeout = TimeSpan.FromSeconds(60);
o.Assistant.TranscriptLimit = 20;
});
Configuring these does not turn an assistant on — registering an IChatClient or an
ISupportChatClientResolver does. There is deliberately no model, endpoint or key here.
Replace Instructions. The default says only what is true of every host: answer from the tools, and say
so rather than guess. A model that knows your product answers very differently from one that does not.
A model that times out, returns nothing, or cannot be reached declines, and a decline is an ordinary
outcome rather than an error: the case stays waiting for a person, which is what the customer would have had
anyway. A provider being down never stops somebody reporting a problem. <SupportCasesView /> tells the
customer the assistant could not answer, beside Talk to a person, rather than showing nothing.
Is anybody on support
@inject ISupportPresence Presence // registered with the support cases; GetService still reads as "say nothing"
GetAsync answers Online, Away or Unknown, from two sources, and is Online when either is:
- The support desk. Put
<SupportDeskStatus />on the page support works from. Each support person picks Automatic, Online, Away or Hidden there; it starts at Automatic the first time they open it, and keeps their choice in the browser after that. Automatic counts as online only while they are active: answering a case, writing an answer, or using the application, which the browser's one activity signal reports at most once a minute (see Last seen), so any page counts, not only this one. Aftero.StaffIdleAfterwith nothing done, ten minutes by default, they count as away until they act again. Online counts as online for as long as it stands, active or not, for somebody who is at the desk reading rather than clicking; so that it does not say support is there long after the person left, it too lapses to away aftero.StaffOnlineLapseAfterwithout activity, twenty minutes by default. Hidden answers as usual and is not counted at all. Support isAwaywhile somebody chose anything but Hidden and nobody counts as online, andUnknownotherwise: while nobody has opened the desk since the application started, and while everybody there chose Hidden. A choice remembered from before Automatic existed was called Online and comes back as Automatic, so nobody's behaviour changes on upgrade. - Slack, where a support channel is configured: who is active on that channel, so adding somebody to the channel is how they become support there, and there is no second list to keep in step.
Unknown must render as nothing, never as "offline". Telling a customer not to bother when support is in
fact there is worse than saying nothing, and unknown is what a rate limit, a network blip and an
unconfigured workspace all produce. In Slack, three separate paths preserve that distinction: an unreadable
channel keeps the previous roster rather than concluding support is empty, all-unknown presence stays unknown, and
a transport failure is unknown rather than an error.
Advisory, never a gate. Nothing that raises a case may wait on this or be refused by it.
Only the product's support staff are on the desk: SetMyStaffStatusAsync, GetMyStaffStatusAsync and
ReportStaffActivityAsync refuse anybody who may not answer across teams (support:all:manage) or the cases with no
team (support:unassigned:manage), and SupportDeskStatus shows them nothing. Nothing about it is stored or audited.
Changed is raised when somebody on the desk sets a status, goes idle or comes back, so a page showing presence
follows it.
The desk is in-process, as typing is. On several instances, each knows only the support people connected to it, so a member on another instance may read away while somebody could answer. That costs the member a notice, never a refused question.
What members see
The side panel's Support tab, and a conversation with a person on the support page, show Support is online or Support will reply later, and nothing while it is unknown or the assistant is answering.
When a member's message to a person has waited a minute with no answer, the conversation says nobody has answered
yet, and we will get back to you here; while support is away, it says so at once. It is not shown while somebody
from support is writing, goes when support answers, and is stored nowhere: it is worked out from the conversation and
the clock, so it comes back on a reload. NoAnswerAfter on SupportPanel and SupportCasesView changes the minute.
Slack presence
It is cached, and it has to be. Slack rate-limits users.getPresence, and it is per user — so asking
about a channelful of people on every render is how a deployment gets throttled. The channel roster is
trusted for ten minutes and presence for sixty seconds, because the two questions change at completely
different rates.
The cache is process-local. On several instances each keeps its own, so you make that many times the calls — still bounded by the interval, and a stale answer is already harmless because presence is advisory. This is deliberately unlike the inbound event ledger, where process-local state would be a correctness defect rather than a cost.
Knowing what needs attention
Two questions, two methods, two different checks — because they serve two audiences and one of them is privileged:
| Method | Answers | Requires |
|---|---|---|
GetMyUnreadCountAsync(teamKey) |
my own cases holding an answer I have not read | membership |
GetMyUnreadByCaseAsync(teamKey) |
the same, per case, with how many | membership |
GetMyOpenCountAsync(teamKey) |
my own open cases | membership |
GetMyAnsweredCountAsync(teamKey) |
my own open cases support answered last, read or not | membership |
GetAwaitingSupportCountAsync(teamKey) |
open cases whose newest entry came from the person who raised them | support:read |
GetAwaitingSupportCountAcrossTeamsAsync() |
the same, in every team | support:all:read |
GetAwaitingUnassignedCountAsync() |
the same, in the cases no team owns | support:unassigned:read |
MarkReadAsync(teamKey, caseId) |
records that I have read up to the newest entry | the same check as reading that case |
Not one result carrying both numbers. That would either show an ordinary member the support-wide figure or arrive half-populated — and a half-populated result is what a component renders as a zero.
These are public API on purpose. A count chip or a dashboard panel is something you can build yourself against exactly this; nothing about it is reserved for a component the toolkit ships.
How the two behave
Support's side needs no read state. A case is awaiting an answer while its newest entry came from its author, so the count is correct however many support people look at it, and closing a case removes it from the count.
A user's side does. Opening a case marks it read; a reply arriving afterwards makes it unread again. Two people on one case have independent state, and the marker never moves backwards — a second tab showing an older page cannot relight the indicator. Replying counts as reading, so writing a message does not light your own chip.
Only an answer is unread — an entry by somebody else, or by support. A note that the case closed or reopened is not, so closing a case never leaves a light on for a case the list no longer shows. The open and answered counts are what a host shows once nothing is unread: the cases still going on, and those waiting on the customer to reply or close them. All of them leave conversations with the assistant aside.
var unread = await support.GetMyUnreadCountAsync(teamKey);
// Gate rendering on the scope with TeamScopeGate; the service checks it again on the call itself.
if (TeamScopeGate.HasTeamScope(principal, SupportScopes.Read, teamKey))
{
var awaiting = await support.GetAwaitingSupportCountAsync(teamKey);
}
A chip does not update itself across instances on its own.
ISupportCaseNotifieris in-process, so on a multi-instance deployment a Slack reply raises the notification on whichever instance handled it — not necessarily the one holding the viewer's circuit. Re-reading the count on navigation always works; to live-update everywhere, relay the notifier between instances (Knowing when something changed).
Escalating from your own worker
The counts above answer "how many, in this team". A worker that escalates needs a different question answered: which cases, in any team, have waited too long? Two store queries answer it (3.24, Tharga/Team#293):
Method on ISupportCaseStore |
Returns open cases, across every team, where… |
|---|---|
GetCasesAwaitingSupportSinceAsync(waitingSince, limit) |
the newest entry is from the person who raised the case, and older than waitingSince |
GetCasesWithUnreadAnswerSinceAsync(answeredBefore, limit) |
the newest entry is an answer, older than answeredBefore, and its author has not read it |
An answer is an entry by a person other than the author, or by the assistant. A toolkit note (a reopen or an assignment) is never an answer, and a case whose newest entry is one is not returned. Unassigned cases are included in both queries.
public class SupportEscalationWorker(ISupportCaseStore store, ISupportEventLedger ledger, IMyMailer mail)
{
public async Task RunOnceAsync(CancellationToken cancellationToken)
{
var unanswered = await store.GetCasesAwaitingSupportSinceAsync(DateTime.UtcNow.AddMinutes(-1), 50, cancellationToken);
foreach (var supportCase in unanswered)
{
// One escalation per newest entry: the pair names exactly one, so a later message escalates again.
if (!await ledger.TryRecordAsync("escalation", $"{supportCase.Id}:{supportCase.MessageCount}", cancellationToken)) continue;
await mail.NotifySupportAsync(supportCase);
}
}
}
A matching case keeps matching, so deduplication is yours. Neither query changes what it reads. Key
"already handled" on Id plus MessageCount, as above. ISupportEventLedger already does this atomically
across instances.
Results are newest first. A case you have already handled stays in the results, so with a limit and
no ordering a pass could return the same handled cases every time. Newest first puts the cases that have
only just crossed the window on top.
These are framework reads, not user-facing ones. They name no team and check no scope, like the inactivity sweep. Call them from a background worker and never from a page, controller or MCP provider. A custom store that does not implement them returns nothing, so the worker simply never escalates.
What happens when things are deleted
| Event | Effect on cases |
|---|---|
| The author is deleted, or leaves the team | Cases and transcripts are kept, and stay readable with the name they were written with. Nobody then satisfies the authorship check, so such a case is reachable through support:read / support:manage |
| The team is soft-deleted | Cases remain readable to a caller whose team claim still names it. See the limitation below. Restoring the team is unaffected |
| The team is purged | Cases are destroyed with it, by a purge participant — their files first |
One known limitation. A soft-deleted team's cases are still readable to a caller whose
TeamKeyclaim still names it, which is inconsistent with every other team read — all of which exclude soft-deleted teams. Purge is unaffected: it destroys the cases either way.
Over REST
The toolkit ships no REST endpoints for support cases; a host with its own surface calls ISupportCaseService and
nothing else. Since 4.2 that surface needs a few more endpoints to keep up with the components: answering and
replying with files and an optional bodyHtml, downloading a file, sending an answer again, and where an answer
goes and what it will look like.
[HttpPost("{teamKey}/cases/{caseId}/answers")]
public async Task AnswerAsync(string teamKey, string caseId, [FromForm] string body, [FromForm] string bodyHtml, [FromForm] IFormFileCollection files)
{
var uploads = files.Select(f => new SupportAttachmentUpload { FileName = f.FileName, ContentType = f.ContentType, Content = f.OpenReadStream() }).ToArray();
try
{
await cases.AnswerCaseAsync(teamKey, caseId, body, bodyHtml, uploads, HttpContext.RequestAborted);
}
finally
{
foreach (var upload in uploads) await upload.Content.DisposeAsync();
}
}
[HttpGet("{teamKey}/cases/{caseId}/messages/{sequence:int}/attachments/{attachmentId}")]
public async Task<IActionResult> AttachmentAsync(string teamKey, string caseId, int sequence, string attachmentId)
{
var file = await cases.OpenAttachmentAsync(teamKey, caseId, sequence, attachmentId, HttpContext.RequestAborted);
if (file == null) return NotFound();
Response.Headers["X-Content-Type-Options"] = "nosniff";
var type = SupportAttachmentContentTypes.ServedAs(file.Attachment.ContentType);
return SupportAttachmentContentTypes.OpensInBrowser(file.Attachment.ContentType)
? File(file.Content, type)
: File(file.Content, type, file.Attachment.FileName);
}
[HttpPost("{teamKey}/cases/{caseId}/messages/{sequence:int}/resend")]
public Task<SupportMessageDelivery> ResendAsync(string teamKey, string caseId, int sequence)
=> cases.ResendAsync(teamKey, caseId, sequence, HttpContext.RequestAborted);
[HttpGet("{teamKey}/cases/{caseId}/answer-route")]
public Task<SupportAnswerRoute> AnswerRouteAsync(string teamKey, string caseId)
=> cases.GetAnswerRouteAsync(teamKey, caseId, HttpContext.RequestAborted);
[HttpPost("{teamKey}/cases/{caseId}/answers/preview")]
public Task<MailPreview> PreviewAnswerAsync(string teamKey, string caseId, [FromForm] string body, [FromForm] string bodyHtml)
=> cases.PreviewAnswerAsync(teamKey, caseId, body, bodyHtml, HttpContext.RequestAborted);
A client showing MailPreview.Html shows it isolated — a sandboxed frame without scripts — never as markup in its
own page: it carries the host template's styles.
A case's SuggestedTeams, SuggestionReason and its bindings' MailboxAddress, and a message's BodyHtml,
Attachments and DeliveryError, are worth exposing in what you return. BodyHtml is sanitized already; a client
showing it should still sanitize it again, as RichTextView does.
Moving to 4.2
Coming from 3.x, follow Migrating to 4.0 in the implementation guide first.
Important
Mail from a known sender can now open in their team. Before 4.2 every mail opened unassigned. Now a mail
whose DKIM-verified sender is the one account holding the address, active in exactly one team, opens in that
team with that user as its author, and anything short of that opens unassigned with suggestions. To keep the
old behaviour, register an ISupportSenderDirectory that finds nobody before AddThargaTeamRepository.
Reading mail now looks up DKIM keys in DNS, so the host needs outbound DNS; without it nothing is verified.
Important
Mail attachments are now stored, in the GridFS bucket SupportAttachment in your database, up to 25 MB a
file, 50 MB and 20 files a mail. Lower the limits on MailOptions, or register your own
ISupportAttachmentStore before AddThargaTeamRepository to keep files elsewhere.
For implementers and decorators:
ISupportCaseServicegained nine members:ReplyToCaseAsyncandAnswerCaseAsyncwith files, and with HTML and files;OpenAttachmentAsync,GetAttachmentLimitsAsync,ResendAsync,GetAnswerRouteAsyncandPreviewAnswerAsync. A host implementing or decorating it adds them; the last two are authorized as answering.ISupportCaseStore.SetMessageDeliveryAsyncgainedstring error = nullbefore the cancellation token. A host's own store changes its signature and keeps the error only withFailed; a caller passing the token positionally names it.ISupportChannel.PostWithResultAsyncis a default member; a channel of your own keeps compiling and may override it to say why a post failed.SupportCaseChange.DeliveryChangedis new, so a switch over changes handles it.
For hosts with their own store or REST surface:
SupportMessagegainedBodyHtml,DeliveryErrorandAttachments;SupportCasegainedSuggestedTeamsandSuggestionReason;SupportChannelBindinggainedMessageSequence,MailboxandMailboxAddress. A store of your own persists them. The built-in store reads documents without them as before; nothing to migrate.SupportMessageandSupportCasenow hold arrays, so record equality between two of them compares the arrays by reference. Compare fields instead.- Add the endpoints above — files,
bodyHtml, download, resend, the answer's route and its preview — to keep up with the components.SupportAnswerRoute,MailPolicyEffectandMailPrevieware new contracts inTharga.Team.
Behaviour:
- A formatted answer is mailed as HTML beside the same text, and a mail's HTML is kept, sanitized; the shipped answer boxes call the HTML overloads, so a test verifying their calls updates them.
- An answer carries the whole thread and quotes the conversation; every message id is recorded.
- A bounce marks the answer it names as not delivered; one naming no answer goes to the registered
IMailBounceHandlers. - With a mail template registered, every answer is framed in it, a plain one
included — in
SupportHtmlwhen that is set. Without one, answers are mailed as before. - An answer names no staff member. It no longer starts with "{author}:", earlier support entries it quotes are
attributed to
SupportCaseOptions.Answers.SupportName, and each quote is introduced by "On {date}, {name} wrote:" instead of "{date} UTC, {name}:"; the host's signature follows the answer. See How an answer speaks for support. A test matching the old text updates. - The support answer boxes — in
SupportUnassignedView,SupportAcrossTeamsViewandSupportQueueView— show where the answer goes and offer a Preview; they callGetAnswerRouteAsyncwhen a case opens andPreviewAnswerAsyncon Preview, so a test verifying their calls expects them. A member's own reply box inSupportCasesViewshows neither. SupportUnassignedViewcarries no heading — add your own fromSupportUnassignedViewText.Title— and reads every page rather than the first twenty. Pass it the sameTimeTemplateyou giveSupportAcrossTeamsView.SupportTranscriptinjectsISupportCaseService, to open files; a page using it directly has support cases registered already.- The registration's refusal of a sending address its own filter rejects now names the mailbox.
New text keys, all in ThargaTextKeys.All: team.support.filter.search;
team.support.transcript.notSentYet|notDelivered|sendAgain;
team.support.unassigned.noneMatch|awaiting|needsAnswer|suggested|suggested.assign|reason.severalTeams|reason.notVerified|reason.sharedAddress;
team.support.mailbox.cameInTo ("to {0}");
team.support.mail.wrote ("On {0}, {1} wrote:") and team.support.mail.supportName ("Support"), in
SupportMailText, resolved through ITextResolver when an answer is mailed;
team.support.answerRoute.mailed|mailedTo|site|redirected|withheld;
team.mailPreview.open|title|from|replyTo|to|toMany|subject|files|textOnly|frame|close|failed;
team.support.attachments.* (attach, remove, chosen, attached, open, save, notAvailable, tooMany, tooLarge,
tooLargeTogether, unreadable); and team.richText.* (bold, italic, underline, bulletedList, numberedList, link,
linkAddress, linkText, linkNewWindow, linkOk, linkCancel, removeFormatting, undo, redo). No key was removed.