diff --git a/src/routes/api/system.ts b/src/routes/api/system.ts index bad4c72..ab0a578 100644 --- a/src/routes/api/system.ts +++ b/src/routes/api/system.ts @@ -43,7 +43,7 @@ router.get('/status', async (_req, res) => { } if (!capabilities) { warnings.push(`${tenant.name}: the SuperOps schema has not been probed yet. Run the connection test in Settings.`); - } else if (!capabilities.bodyField) { + } else if (!capabilities.bodyField && !capabilities.conversationQuery) { warnings.push( `${tenant.name}: no ticket body field was found on this SuperOps schema, so classification uses the subject line only.`, ); diff --git a/src/services/psa/capabilities.ts b/src/services/psa/capabilities.ts index 7f1aada..5dfa9de 100644 --- a/src/services/psa/capabilities.ts +++ b/src/services/psa/capabilities.ts @@ -13,7 +13,7 @@ import { createLogger, describeError } from '../../lib/logger'; const log = createLogger('SuperOps:probe'); /** Version stamp — bump to force a re-probe after changing the probe logic. */ -export const CAPABILITIES_VERSION = 4; +export const CAPABILITIES_VERSION = 5; export interface ObjectFieldShape { /** 'leaf' needs no sub-selection; 'object' does; 'missing' means absent. */ @@ -56,6 +56,8 @@ export interface PsaCapabilities { subjectField: string | null; /** Long-form ticket text — the thing the classifier actually needs. */ bodyField: string | null; + /** When the body field is an object, the scalar inside it holding the text. */ + bodySubField: string | null; statusField: string | null; priorityField: string | null; createdField: string | null; @@ -70,6 +72,20 @@ export interface PsaCapabilities { /** Ticket fields only available on the detail query. */ detailOnlyFields: string[]; + /** + * Where the ticket text lives when the ticket itself has no body field. + * SuperOps keeps the requester's original message as the first entry of the + * ticket's conversation thread rather than on the ticket. + */ + conversationQuery: string | null; + conversationArgName: string | null; + /** When the argument is an input object, the field inside it holding the ticket id. */ + conversationArgIdField: string | null; + /** Field on the payload holding the array; null when the query returns the array itself. */ + conversationResultField: string | null; + conversationContentField: string | null; + conversationTimeField: string | null; + /** Root query listing the MSP's clients, so the UI can offer a picker. */ clientListQuery: string | null; clientListArgName: string | null; @@ -150,6 +166,17 @@ const BODY_CANDIDATES = [ 'message', 'note', ]; +const CONVERSATION_QUERY_CANDIDATES = [ + 'getTicketConversationList', + 'getTicketConversations', + 'getConversationList', + 'getTicketThreadList', + 'getTicketThreads', + 'ticketConversations', +]; +const CONVERSATION_RESULT_CANDIDATES = ['conversations', 'conversationList', 'threads', 'items', 'data', 'results']; +const CONVERSATION_CONTENT_CANDIDATES = ['content', 'body', 'message', 'text', 'description', 'html', 'htmlContent']; +const CONVERSATION_TIME_CANDIDATES = ['time', 'createdTime', 'createdAt', 'sentTime', 'date', 'timestamp']; const STATUS_CANDIDATES = ['status', 'ticketStatus', 'state']; const PRIORITY_CANDIDATES = ['priority', 'ticketPriority', 'urgency']; const CREATED_CANDIDATES = ['createdTime', 'createdAt', 'createdDate', 'creationTime']; @@ -229,6 +256,7 @@ export async function probeCapabilities( displayIdField: null, subjectField: null, bodyField: null, + bodySubField: null, statusField: null, priorityField: null, createdField: null, @@ -238,6 +266,12 @@ export async function probeCapabilities( detailArgName: null, detailArgIdField: null, detailOnlyFields: [], + conversationQuery: null, + conversationArgName: null, + conversationArgIdField: null, + conversationResultField: null, + conversationContentField: null, + conversationTimeField: null, clientListQuery: null, clientListArgName: null, clientListResultField: null, @@ -355,14 +389,20 @@ export async function probeCapabilities( const detailFields = (detailType?.fields ?? []).map((f) => f.name); caps.detailOnlyFields = detailFields.filter((f) => !caps.ticketFields.includes(f)); if (!caps.bodyField) { - caps.bodyField = pickField(detailFields, BODY_CANDIDATES); + await assignBodyField(caps, detailType?.fields ?? [], describeType); } } } + // ─── Conversation thread, where SuperOps keeps the original message ───────── if (!caps.bodyField) { + await resolveConversation(caps, queryFields, describeType); + } + + if (!caps.bodyField && !caps.conversationQuery) { + const seen = caps.ticketFields.length ? ` Ticket fields: ${caps.ticketFields.join(', ')}.` : ''; warnings.push( - `No ticket body field found (looked for: ${BODY_CANDIDATES.slice(0, 5).join(', ')}). Classification will use the subject line only, which measurably reduces accuracy.`, + `No ticket body found — no body field on the ticket (looked for: ${BODY_CANDIDATES.slice(0, 5).join(', ')}) and no conversation query (looked for: ${CONVERSATION_QUERY_CANDIDATES.slice(0, 2).join(', ')}). Classification will use the subject line only, which measurably reduces accuracy.${seen}`, ); } @@ -463,6 +503,95 @@ export async function probeCapabilities( return caps; } +/** + * Picks the ticket body: a scalar by a known name, else any scalar whose name + * says description or body, else an object by a known name with a text field + * inside it (selected as `description { content }`). + */ +async function assignBodyField( + caps: PsaCapabilities, + fields: FieldInfo[], + describeType: (name: string) => Promise, +): Promise { + const leaves = fields.filter((f) => isLeafType(f.type)).map((f) => f.name); + const exact = pickField(leaves, BODY_CANDIDATES); + const fuzzy = leaves.find((n) => /description|body/i.test(n) && !/(id|type|format|count)$/i.test(n)); + if (exact || fuzzy) { + caps.bodyField = (exact ?? fuzzy)!; + caps.bodySubField = null; + return; + } + const objects = fields.filter((f) => !isLeafType(f.type)); + const objectName = pickField(objects.map((f) => f.name), BODY_CANDIDATES); + if (!objectName) return; + const typeName = namedType(objects.find((f) => f.name === objectName)!.type).name; + const type = typeName ? await describeType(typeName) : null; + const inner = pickField( + (type?.fields ?? []).filter((f) => isLeafType(f.type)).map((f) => f.name), + CONVERSATION_CONTENT_CANDIDATES, + ); + if (inner) { + caps.bodyField = objectName; + caps.bodySubField = inner; + } +} + +/** Finds a per-ticket conversation query and the text and time fields on its entries. */ +async function resolveConversation( + caps: PsaCapabilities, + queryFields: FieldInfo[], + describeType: (name: string) => Promise, +): Promise { + const field = + findRootField(queryFields, CONVERSATION_QUERY_CANDIDATES) ?? + queryFields.find((f) => /^get\w*ticket\w*(conversation|thread)\w*$/i.test(f.name)) ?? + null; + if (!field) return; + const arg = field.args?.[0]; + if (!arg) return; + + let argIdField: string | null = null; + if (namedType(arg.type).kind === 'INPUT_OBJECT') { + const argTypeName = namedType(arg.type).name; + const argType = argTypeName ? await describeType(argTypeName) : null; + const argFields = (argType?.inputFields ?? []).map((f) => f.name); + argIdField = pickField(argFields, ID_CANDIDATES); + if (!argIdField) return; + } + + // Either the query returns the entries directly, or a wrapper holding them. + let resultField: string | null = null; + let entryTypeName = namedType(field.type).name; + if (!isListType(field.type) && entryTypeName) { + const wrapper = await describeType(entryTypeName); + const wrapperFields = wrapper?.fields ?? []; + const arrayField = + wrapperFields.find((f) => CONVERSATION_RESULT_CANDIDATES.includes(f.name)) ?? + wrapperFields.find((f) => !isLeafType(f.type) && isListType(f.type)); + if (!arrayField) return; + resultField = arrayField.name; + entryTypeName = namedType(arrayField.type).name; + } + const entryType = entryTypeName ? await describeType(entryTypeName) : null; + const scalars = (entryType?.fields ?? []).filter((f) => isLeafType(f.type)).map((f) => f.name); + const content = pickField(scalars, CONVERSATION_CONTENT_CANDIDATES); + if (!content) return; + + caps.conversationQuery = field.name; + caps.conversationArgName = arg.name; + caps.conversationArgIdField = argIdField; + caps.conversationResultField = resultField; + caps.conversationContentField = content; + caps.conversationTimeField = pickField(scalars, CONVERSATION_TIME_CANDIDATES); +} + +/** Where the ticket text comes from, for the UI. Null when nowhere. */ +export function describeBodySource(caps: Pick): string | null { + if (caps.bodyField) return caps.bodySubField ? `${caps.bodyField}.${caps.bodySubField}` : caps.bodyField; + if (caps.conversationQuery) return `${caps.conversationQuery} (first message)`; + return null; +} + function findRootField(fields: FieldInfo[], candidates: readonly string[]): FieldInfo | null { const byLower = new Map(fields.map((f) => [f.name.toLowerCase(), f])); for (const candidate of candidates) { @@ -486,17 +615,7 @@ async function assignTicketFields( caps.priorityField = pickField(names, PRIORITY_CANDIDATES); caps.createdField = pickField(names, CREATED_CANDIDATES); - // Only accept a body field whose type is a leaf — a nested object here would - // need a sub-selection we cannot guess, and the AI wants plain text anyway. - const bodyName = pickField(names, BODY_CANDIDATES); - if (bodyName) { - const field = fields.find((f) => f.name === bodyName); - if (field && isLeafType(field.type)) { - caps.bodyField = bodyName; - } else { - warnings.push(`Ticket.${bodyName} is not a scalar, so it cannot be read as the ticket body.`); - } - } + await assignBodyField(caps, fields, describeType); if (!caps.createdField) { warnings.push('No ticket creation timestamp field found; the poll window cannot be narrowed by age.'); diff --git a/src/services/psa/superops.ts b/src/services/psa/superops.ts index 85bbcc6..3432a0f 100644 --- a/src/services/psa/superops.ts +++ b/src/services/psa/superops.ts @@ -193,35 +193,75 @@ export class SuperOpsClient implements PSAClient { async enrichTicket(ticket: PsaTicket): Promise { const caps = await this.ensureCapabilities(); if (ticket.body) return ticket; - if (!caps.detailQuery || !caps.detailArgName || !caps.bodyField) return ticket; - - const selection = [caps.idField, caps.bodyField].filter(Boolean).join('\n '); - const argValue = caps.detailArgIdField - ? { [caps.detailArgIdField]: ticket.ticketId } - : ticket.ticketId; + try { + const body = + caps.bodyField && caps.detailQuery && caps.detailArgName + ? await this.fetchBodyField(caps, ticket.ticketId) + : caps.conversationQuery + ? await this.fetchFirstConversation(caps, ticket.ticketId) + : null; + if (body) return { ...ticket, body }; + } catch (err) { + log.warn(`Could not fetch the body for ticket ${ticket.ticketId}: ${describeError(err)}`); + } + return ticket; + } + private async fetchBodyField(caps: PsaCapabilities, ticketId: string): Promise { + const bodySelection = caps.bodySubField ? `${caps.bodyField} { ${caps.bodySubField} }` : caps.bodyField; + const argValue = caps.detailArgIdField ? { [caps.detailArgIdField]: ticketId } : ticketId; // The argument is inlined as a literal rather than declared as a variable: // a `$var` declaration must name its type exactly, and that type is only // known from introspection. `literal()` JSON-escapes every string. const query = ` query SwoopTicketDetail { ${caps.detailQuery}(${caps.detailArgName}: ${literal(argValue)}) { - ${selection} + ${caps.idField} + ${bodySelection} } } `; + const data = await this.request>(query); + const node = data[caps.detailQuery!] as Record | null; + let raw = node?.[caps.bodyField!]; + if (caps.bodySubField && raw && typeof raw === 'object') raw = (raw as Record)[caps.bodySubField]; + return typeof raw === 'string' && raw.trim() ? htmlToText(raw) : null; + } - try { - const data = await this.request>(query); - const node = data[caps.detailQuery] as Record | null; - const rawBody = node?.[caps.bodyField]; - if (typeof rawBody === 'string' && rawBody.trim()) { - return { ...ticket, body: htmlToText(rawBody) }; + /** + * The requester's original message, from the ticket's conversation thread — + * where SuperOps keeps it. The earliest entry is the one that opened the + * ticket; later replies are left out so a long thread cannot drown it. + */ + private async fetchFirstConversation(caps: PsaCapabilities, ticketId: string): Promise { + const argValue = caps.conversationArgIdField ? { [caps.conversationArgIdField]: ticketId } : ticketId; + const entry = [caps.conversationContentField, caps.conversationTimeField].filter(Boolean).join(' '); + const selection = caps.conversationResultField ? `${caps.conversationResultField} { ${entry} }` : entry; + const query = ` + query SwoopTicketConversations { + ${caps.conversationQuery}(${caps.conversationArgName}: ${literal(argValue)}) { + ${selection} + } } - } catch (err) { - log.warn(`Could not fetch the body for ticket ${ticket.ticketId}: ${describeError(err)}`); - } - return ticket; + `; + const data = await this.request>(query); + const root = data[caps.conversationQuery!]; + const rows = caps.conversationResultField + ? (root as Record | null)?.[caps.conversationResultField] + : root; + if (!Array.isArray(rows)) return null; + const entries = rows + .filter((r): r is Record => Boolean(r) && typeof r === 'object') + .map((r, index) => ({ + text: typeof r[caps.conversationContentField!] === 'string' ? htmlToText(r[caps.conversationContentField!] as string) : '', + at: caps.conversationTimeField ? parseTimestamp(r[caps.conversationTimeField]) : null, + index, + })) + .filter((e) => e.text.trim()); + if (entries.length === 0) return null; + // Order by time when every entry has one; otherwise trust the API's order. + if (entries.every((e) => e.at !== null)) entries.sort((a, b) => a.at! - b.at! || a.index - b.index); + return entries[0].text; } /** diff --git a/tests/capabilities.test.ts b/tests/capabilities.test.ts index d559d42..a356e7b 100644 --- a/tests/capabilities.test.ts +++ b/tests/capabilities.test.ts @@ -41,10 +41,45 @@ describe('probeCapabilities', () => { } }); - it('warns loudly when no body field exists at all', async () => { + it('warns loudly when no body field exists at all, listing the fields it saw', async () => { const caps = await probe({ bodyField: null }); expect(caps.bodyField).toBeNull(); expect(caps.warnings.join(' ')).toMatch(/subject line only/i); + expect(caps.warnings.join(' ')).toMatch(/Ticket fields: ticketId, displayId, subject/); + }); + + it('finds a body field by meaning when its name is not on the list', async () => { + const caps = await probe({ bodyField: 'problemDescription' }); + expect(caps.bodyField).toBe('problemDescription'); + }); + + it('reads a body held inside an object', async () => { + const caps = await probe({ bodyField: 'description', bodyObject: true }); + expect(caps).toMatchObject({ bodyField: 'description', bodySubField: 'content' }); + }); + + // SuperOps keeps the requester's message in the ticket's conversations, not + // on the ticket, so a schema with no body field must not mean no body. + it('falls back to the ticket conversation thread when the ticket has no body', async () => { + for (const shape of ['list', 'wrapped'] as const) { + const caps = await probe({ bodyField: null, conversations: shape }); + expect(caps.bodyField, shape).toBeNull(); + expect(caps, shape).toMatchObject({ + conversationQuery: 'getTicketConversationList', + conversationArgName: 'input', + conversationArgIdField: 'ticketId', + conversationResultField: shape === 'wrapped' ? 'conversations' : null, + conversationContentField: 'content', + conversationTimeField: 'time', + }); + expect(caps.warnings.join(' '), shape).not.toMatch(/subject line only/i); + } + }); + + it('prefers a body on the ticket over the conversation thread', async () => { + const caps = await probe({ conversations: 'list' }); + expect(caps.bodyField).toBe('description'); + expect(caps.conversationQuery).toBeNull(); }); it('resolves an object-shaped client into id and label sub-fields', async () => { @@ -283,3 +318,53 @@ describe('literal', () => { expect(literal({ a: 1, b: undefined })).toBe('{a: 1}'); }); }); + +describe('reading the ticket body', () => { + // graphql-request brings its own fetch, so the transport is replaced on the + // client itself rather than stubbed globally. + async function clientFor(options: Parameters[0], respond: (query: string) => unknown) { + const { SuperOpsClient } = await import('../src/services/psa/superops'); + const capabilities = await probe(options); + const sent: string[] = []; + const client = new SuperOpsClient({ subdomain: 'msp', apiKey: 'k', capabilities }); + (client as unknown as { client: { request: (req: { document: string }) => Promise } }).client = { + request: async ({ document }) => { + sent.push(document); + return respond(document); + }, + }; + return { client, sent }; + } + + const bare = { ticketId: 'T-1', displayId: '1', subject: 'Locked out', body: '', status: null, priority: null, createdAt: null, clientId: null, clientName: null, requesterEmail: null, requesterName: null }; + + it('takes the earliest conversation entry, as text', async () => { + const { client, sent } = await clientFor({ bodyField: null, conversations: 'wrapped' }, () => ({ + getTicketConversationList: { + conversations: [ + { content: '

Thanks, trying now

', time: '2026-09-23T10:05:00Z' }, + { content: '

I am locked out of Outlook

', time: '2026-09-23T09:00:00Z' }, + ], + }, + })); + const enriched = await client.enrichTicket({ ...bare }); + expect(enriched.body).toBe('I am locked out of Outlook'); + expect(sent[0]).toContain('getTicketConversationList(input: {ticketId: "T-1"})'); + expect(sent[0]).toContain('conversations { content time }'); + }); + + it('reads a body nested in an object', async () => { + const { client, sent } = await clientFor({ bodyObject: true }, () => ({ + getTicket: { ticketId: 'T-1', description: { content: '
Printer offline
' } }, + })); + expect((await client.enrichTicket({ ...bare })).body).toBe('Printer offline'); + expect(sent[0]).toContain('description { content }'); + }); + + it('leaves the ticket alone when the conversation query fails', async () => { + const { client } = await clientFor({ bodyField: null, conversations: 'list' }, () => { + throw new Error('Field required: listInfo'); + }); + expect((await client.enrichTicket({ ...bare })).body).toBe(''); + }); +}); diff --git a/tests/fixtures/superops-schema.ts b/tests/fixtures/superops-schema.ts index 81dcbbf..4aabae3 100644 --- a/tests/fixtures/superops-schema.ts +++ b/tests/fixtures/superops-schema.ts @@ -56,6 +56,14 @@ export interface SchemaOptions { * 'absent' omits the query entirely. */ clientList?: 'wrapped' | 'unusable' | 'absent'; + /** + * A per-ticket conversation query, where SuperOps keeps the original message: + * 'list' returns [TicketConversation] directly, 'wrapped' returns + * { conversations { ... } }, 'none' omits it. + */ + conversations?: 'list' | 'wrapped' | 'none'; + /** Put the body inside an object, as description { content }. */ + bodyObject?: boolean; } export function buildFakeSchema(options: SchemaOptions = {}): FakeSchema { @@ -66,6 +74,8 @@ export function buildFakeSchema(options: SchemaOptions = {}): FakeSchema { sort = 'supported', detailQuery = true, clientList = 'wrapped', + conversations = 'none', + bodyObject = false, } = options; const ticketFields: FakeField[] = [ @@ -79,7 +89,7 @@ export function buildFakeSchema(options: SchemaOptions = {}): FakeSchema { { name: 'technician', type: object('User') }, ]; - if (bodyField) ticketFields.push({ name: bodyField, type: scalar() }); + if (bodyField) ticketFields.push({ name: bodyField, type: bodyObject ? object('RichText') : scalar() }); if (clientShape === 'object') { ticketFields.push({ name: 'client', type: object('Client') }); @@ -137,6 +147,30 @@ export function buildFakeSchema(options: SchemaOptions = {}): FakeSchema { }, }; + types.RichText = { + name: 'RichText', + kind: 'OBJECT', + fields: [ + { name: 'content', type: scalar() }, + { name: 'format', type: scalar() }, + ], + }; + types.TicketConversation = { + name: 'TicketConversation', + kind: 'OBJECT', + fields: [ + { name: 'conversationId', type: scalar('ID') }, + { name: 'content', type: scalar() }, + { name: 'time', type: scalar() }, + { name: 'user', type: scalar('JSON') }, + ], + }; + types.TicketConversationList = { + name: 'TicketConversationList', + kind: 'OBJECT', + fields: [{ name: 'conversations', type: list(object('TicketConversation')) }], + }; + const listInputFields: FakeField[] = [ { name: 'page', type: scalar('Int') }, { name: 'pageSize', type: scalar('Int') }, @@ -199,6 +233,14 @@ export function buildFakeSchema(options: SchemaOptions = {}): FakeSchema { }); } + if (conversations !== 'none') { + queryFields.push({ + name: 'getTicketConversationList', + type: conversations === 'list' ? list(object('TicketConversation')) : object('TicketConversationList'), + args: [{ name: 'input', type: nonNull(input('TicketIdentifierInput')) }], + }); + } + const mutationFields: FakeField[] = []; if (noteStyle === 'createNote') { mutationFields.push({ diff --git a/web/src/api.ts b/web/src/api.ts index 6bc95d3..e78defe 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -601,6 +601,9 @@ export interface PsaCapabilities { displayIdField: string | null; subjectField: string | null; bodyField: string | null; + bodySubField?: string | null; + conversationQuery?: string | null; + ticketFields?: string[]; createdField: string | null; detailQuery: string | null; noteMutation: string | null; @@ -963,3 +966,11 @@ export async function downloadCsv(params: ActionQuery = {}): Promise { // ─── System ─────────────────────────────────────────────────────────────────── export const getSystemStatus = () => api.get('/system/status'); + +/** Where Swoop reads the ticket text from, or null when it found nowhere. */ +export function bodySource(caps: Pick | null | undefined): string | null { + if (!caps) return null; + if (caps.bodyField) return caps.bodySubField ? `${caps.bodyField}.${caps.bodySubField}` : caps.bodyField; + if (caps.conversationQuery) return `${caps.conversationQuery} (first message)`; + return null; +} diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx index 1ed6225..8479998 100644 --- a/web/src/pages/Settings.tsx +++ b/web/src/pages/Settings.tsx @@ -12,6 +12,7 @@ import { getNotePreview, getSystemStatus, getTenants, + bodySource, pruneLogs, testAi, testSuperOps, @@ -299,7 +300,7 @@ function ConnectionResult({ result }: { result: ConnectionTestResult }) {
  • Ticket body:{' '} - {caps.bodyField ? {caps.bodyField} : not found} + {bodySource(caps) ? {bodySource(caps)} : not found}
  • Note mutation:{' '} @@ -977,9 +978,14 @@ function CapabilityTable({ caps, probedAt }: { caps: PsaCapabilities; probedAt?: - - + + + {caps.ticketFields && caps.ticketFields.length > 0 && ( + + {caps.ticketFields.join(', ')} + + )} diff --git a/web/src/pages/Setup.tsx b/web/src/pages/Setup.tsx index 306f24f..4fd0369 100644 --- a/web/src/pages/Setup.tsx +++ b/web/src/pages/Setup.tsx @@ -9,6 +9,7 @@ import { testAi, testSuperOps, type ConnectionTestResult, + bodySource, } from '../api'; import { Alert, Spinner, Toggle } from '../components/ui'; import { CheckIcon, SwoopLogo } from '../components/Icons'; @@ -526,12 +527,12 @@ function SuperOpsTestResult({ result }: { result: ConnectionTestResult }) { } const caps = result.capabilities; return ( - +

    Swoop inspected your GraphQL schema and will read tickets via {caps?.listQuery} - {caps?.bodyField ? ( + {bodySource(caps) ? ( <> - , using {caps.bodyField} as the ticket body + , reading the ticket text from {bodySource(caps)} ) : ( ' — but found no ticket body field, so it will classify on the subject line alone'