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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 38 additions & 10 deletions src/services/psa/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = 5;
export const CAPABILITIES_VERSION = 6;

export interface ObjectFieldShape {
/** 'leaf' needs no sub-selection; 'object' does; 'missing' means absent. */
Expand Down Expand Up @@ -85,6 +85,8 @@ export interface PsaCapabilities {
conversationResultField: string | null;
conversationContentField: string | null;
conversationTimeField: string | null;
/** Why no conversation query could be used, for the operator. Null when one was, or none exists. */
conversationNote: string | null;

/** Root query listing the MSP's clients, so the UI can offer a picker. */
clientListQuery: string | null;
Expand Down Expand Up @@ -272,6 +274,7 @@ export async function probeCapabilities(
conversationResultField: null,
conversationContentField: null,
conversationTimeField: null,
conversationNote: null,
clientListQuery: null,
clientListArgName: null,
clientListResultField: null,
Expand Down Expand Up @@ -401,8 +404,12 @@ export async function probeCapabilities(

if (!caps.bodyField && !caps.conversationQuery) {
const seen = caps.ticketFields.length ? ` Ticket fields: ${caps.ticketFields.join(', ')}.` : '';
const ticketQueries = queryFields.map((f) => f.name).filter((n) => /ticket/i.test(n));
const conversation =
caps.conversationNote ??
`no conversation query (looked for: ${CONVERSATION_QUERY_CANDIDATES.slice(0, 2).join(', ')}; ticket queries on this schema: ${ticketQueries.join(', ') || 'none'})`;
warnings.push(
`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}`,
`No ticket body found — no body field on the ticket (looked for: ${BODY_CANDIDATES.slice(0, 5).join(', ')}) and ${conversation}. Classification will use the subject line only, which measurably reduces accuracy.${seen}`,
);
}

Expand Down Expand Up @@ -536,7 +543,14 @@ async function assignBodyField(
}
}

/** Finds a per-ticket conversation query and the text and time fields on its entries. */
/**
* Finds a per-ticket conversation query and the text and time fields on its
* entries. SuperOps documents it as
* `getTicketConversationList(input: TicketIdentifierInput!): [TicketConversation]`
* with `content` and `time` strings; when introspection cannot confirm part of
* that for the documented query, the documented shape is used rather than
* giving up, and anything else unresolved is recorded in `conversationNote`.
*/
async function resolveConversation(
caps: PsaCapabilities,
queryFields: FieldInfo[],
Expand All @@ -547,16 +561,21 @@ async function resolveConversation(
queryFields.find((f) => /^get\w*ticket\w*(conversation|thread)\w*$/i.test(f.name)) ??
null;
if (!field) return;
const documented = field.name === 'getTicketConversationList';
const fail = (why: string) => {
caps.conversationNote = `found ${field.name} but ${why}`;
};

const arg = field.args?.[0];
if (!arg) return;
if (!arg) return fail('it takes no argument to name the ticket');

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;
argIdField = pickField(argFields, ID_CANDIDATES) ?? (documented && argFields.length === 0 ? 'ticketId' : null);
if (!argIdField) return fail(`its input ${argTypeName ?? '(unnamed)'} has no ticket id field (has: ${argFields.join(', ') || 'nothing readable'})`);
}

// Either the query returns the entries directly, or a wrapper holding them.
Expand All @@ -568,21 +587,30 @@ async function resolveConversation(
const arrayField =
wrapperFields.find((f) => CONVERSATION_RESULT_CANDIDATES.includes(f.name)) ??
wrapperFields.find((f) => !isLeafType(f.type) && isListType(f.type));
if (!arrayField) return;
if (!arrayField) return fail(`its result ${entryTypeName} holds no list of entries`);
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;
let content = pickField(scalars, CONVERSATION_CONTENT_CANDIDATES);
let time = pickField(scalars, CONVERSATION_TIME_CANDIDATES);
if (!content && documented && scalars.length === 0) {
// The entry type could not be read at all; trust the documented shape.
content = 'content';
time = 'time';
}
if (!content) {
return fail(`its entries (${entryTypeName ?? 'unreadable type'}) have no text field (scalars: ${scalars.join(', ') || 'none readable'})`);
}

caps.conversationQuery = field.name;
caps.conversationArgName = arg.name;
caps.conversationArgIdField = argIdField;
caps.conversationResultField = resultField;
caps.conversationContentField = content;
caps.conversationTimeField = pickField(scalars, CONVERSATION_TIME_CANDIDATES);
caps.conversationTimeField = time;
caps.conversationNote = null;
}

/** Where the ticket text comes from, for the UI. Null when nowhere. */
Expand Down
2 changes: 2 additions & 0 deletions src/services/psa/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export interface ConnectionTestResult {
error?: string;
/** Present when the probe ran, so the UI can show what was discovered. */
capabilities?: PsaCapabilities;
/** The body read from the newest ticket, proving the body source works on real data. */
bodyCheck?: { ticket: string; characters: number; preview: string } | { ticket: string | null; error: string };
}

/** A client (company) as the PSA knows it, for the allowlist picker. */
Expand Down
14 changes: 13 additions & 1 deletion src/services/psa/introspection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,19 @@ export const TYPE_REF_FRAGMENT = `
ofType {
kind
name
ofType { kind name }
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType { kind name }
}
}
}
}
}
}
Expand Down
33 changes: 26 additions & 7 deletions src/services/psa/superops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,19 +194,37 @@ export class SuperOpsClient implements PSAClient {
const caps = await this.ensureCapabilities();
if (ticket.body) return ticket;
try {
const body =
caps.bodyField && caps.detailQuery && caps.detailArgName
? await this.fetchBodyField(caps, ticket.ticketId)
: caps.conversationQuery
? await this.fetchFirstConversation(caps, ticket.ticketId)
: null;
const body = await this.fetchBody(caps, ticket.ticketId);
if (body) return { ...ticket, body };
} catch (err) {
log.warn(`Could not fetch the body for ticket ${ticket.ticketId}: ${describeError(err)}`);
}
return ticket;
}

private async fetchBody(caps: PsaCapabilities, ticketId: string): Promise<string | null> {
if (caps.bodyField && caps.detailQuery && caps.detailArgName) return this.fetchBodyField(caps, ticketId);
if (caps.conversationQuery) return this.fetchFirstConversation(caps, ticketId);
return null;
}

/** Reads the newest ticket's body, so the connection test proves it on real data. */
private async checkBody(caps: PsaCapabilities): Promise<ConnectionTestResult['bodyCheck']> {
if (!caps.listQuery || !caps.listResultField || !caps.listArgName) return undefined;
if (!(caps.bodyField || caps.conversationQuery)) return undefined;
let label: string | null = null;
try {
const [ticket] = await this.fetchTicketPage(caps, 1);
if (!ticket) return undefined;
label = ticket.displayId ? `#${ticket.displayId}` : ticket.ticketId;
const body = await this.fetchBody(caps, ticket.ticketId);
if (!body) return { ticket: label, error: 'The query ran but returned no text for this ticket.' };
return { ticket: label, characters: body.length, preview: body.slice(0, 160) };
} catch (err) {
return { ticket: label, error: describeError(err) };
}
}

private async fetchBodyField(caps: PsaCapabilities, ticketId: string): Promise<string | null> {
const bodySelection = caps.bodySubField ? `${caps.bodyField} { ${caps.bodySubField} }` : caps.bodyField;
const argValue = caps.detailArgIdField ? { [caps.detailArgIdField]: ticketId } : ticketId;
Expand Down Expand Up @@ -381,7 +399,8 @@ export class SuperOpsClient implements PSAClient {
async testConnection(): Promise<ConnectionTestResult> {
try {
const capabilities = await this.ensureCapabilities(true);
return { ok: true, endpoint: this.endpoint, capabilities };
const bodyCheck = await this.checkBody(capabilities);
return { ok: true, endpoint: this.endpoint, capabilities, ...(bodyCheck ? { bodyCheck } : {}) };
} catch (err) {
return { ok: false, endpoint: this.endpoint, error: describeError(err) };
}
Expand Down
64 changes: 64 additions & 0 deletions tests/capabilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,33 @@ describe('probeCapabilities', () => {
}
});

it('reads a fully wrapped list return type', async () => {
const caps = await probe({ bodyField: null, conversations: 'deep' });
expect(caps).toMatchObject({ conversationQuery: 'getTicketConversationList', conversationContentField: 'content' });
});

it('uses the documented shape when the entry type cannot be introspected', async () => {
const caps = await probe({ bodyField: null, conversations: 'opaque' });
expect(caps).toMatchObject({
conversationQuery: 'getTicketConversationList',
conversationArgIdField: 'ticketId',
conversationContentField: 'content',
conversationTimeField: 'time',
});
expect(caps.warnings.join(' ')).not.toMatch(/subject line only/i);
});

it('says why a conversation query it found could not be used', async () => {
const caps = await probe({ bodyField: null, conversations: 'textless' });
expect(caps.conversationQuery).toBeNull();
expect(caps.warnings.join(' ')).toMatch(/found getTicketConversationList but its entries \(BareConversation\) have no text field/);
});

it('lists the schema’s ticket queries when it finds no conversation query', async () => {
const caps = await probe({ bodyField: null });
expect(caps.warnings.join(' ')).toMatch(/ticket queries on this schema: getTicketList, getTicket/);
});

it('prefers a body on the ticket over the conversation thread', async () => {
const caps = await probe({ conversations: 'list' });
expect(caps.bodyField).toBe('description');
Expand Down Expand Up @@ -367,4 +394,41 @@ describe('reading the ticket body', () => {
});
expect((await client.enrichTicket({ ...bare })).body).toBe('');
});

it('proves the body source on the newest ticket during the connection test', async () => {
const { SuperOpsClient } = await import('../src/services/psa/superops');
const introspection = fakeGraphQLClient(buildFakeSchema({ bodyField: null, conversations: 'list' }));
const client = new SuperOpsClient({ subdomain: 'msp', apiKey: 'k' });
(client as unknown as { client: { request: (req: unknown, vars?: Record<string, unknown>) => Promise<unknown> } }).client = {
// The probe calls request(document, variables); reads call request({ document, variables }).
request: async (req, vars) => {
const { document, variables } = typeof req === 'string' ? { document: req, variables: vars } : (req as { document: string; variables?: Record<string, unknown> });
if (document.includes('SwoopTicketList')) return { getTicketList: { tickets: [{ ticketId: 'T-9', displayId: '1009', subject: 'VPN down' }] } };
if (document.includes('SwoopTicketConversations')) {
expect(document).toContain('ticketId: "T-9"');
return { getTicketConversationList: [{ content: '<p>The VPN will not connect since this morning.</p>', time: '2026-09-23T08:00:00Z' }] };
}
return introspection.request(document, variables);
},
};
const result = await client.testConnection();
expect(result.bodyCheck).toEqual({ ticket: '#1009', characters: 44, preview: 'The VPN will not connect since this morning.' });
});

it('reports a body source that fails on real data', async () => {
const { SuperOpsClient } = await import('../src/services/psa/superops');
const introspection = fakeGraphQLClient(buildFakeSchema({ bodyField: null, conversations: 'list' }));
const client = new SuperOpsClient({ subdomain: 'msp', apiKey: 'k' });
(client as unknown as { client: { request: (req: unknown, vars?: Record<string, unknown>) => Promise<unknown> } }).client = {
// The probe calls request(document, variables); reads call request({ document, variables }).
request: async (req, vars) => {
const { document, variables } = typeof req === 'string' ? { document: req, variables: vars } : (req as { document: string; variables?: Record<string, unknown> });
if (document.includes('SwoopTicketList')) return { getTicketList: { tickets: [{ ticketId: 'T-9', displayId: '1009' }] } };
if (document.includes('SwoopTicketConversations')) throw new Error('Not authorised to read conversations');
return introspection.request(document, variables);
},
};
const result = await client.testConnection();
expect(result.bodyCheck).toMatchObject({ ticket: '#1009', error: expect.stringMatching(/Not authorised/) });
});
});
22 changes: 20 additions & 2 deletions tests/fixtures/superops-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export interface SchemaOptions {
* 'list' returns [TicketConversation] directly, 'wrapped' returns
* { conversations { ... } }, 'none' omits it.
*/
conversations?: 'list' | 'wrapped' | 'none';
conversations?: 'list' | 'wrapped' | 'none' | 'deep' | 'opaque' | 'textless';
/** Put the body inside an object, as description { content }. */
bodyObject?: boolean;
}
Expand Down Expand Up @@ -234,11 +234,29 @@ export function buildFakeSchema(options: SchemaOptions = {}): FakeSchema {
}

if (conversations !== 'none') {
// 'deep' is the fully wrapped [TicketConversation!]! a strict schema returns;
// 'opaque' names an entry type introspection cannot read; 'textless' has
// entries with no text field.
const entry =
conversations === 'opaque' ? 'HiddenConversation' : conversations === 'textless' ? 'BareConversation' : 'TicketConversation';
queryFields.push({
name: 'getTicketConversationList',
type: conversations === 'list' ? list(object('TicketConversation')) : object('TicketConversationList'),
type:
conversations === 'wrapped'
? object('TicketConversationList')
: conversations === 'deep'
? nonNull(list(nonNull(object(entry))))
: list(object(entry)),
args: [{ name: 'input', type: nonNull(input('TicketIdentifierInput')) }],
});
types.BareConversation = {
name: 'BareConversation',
kind: 'OBJECT',
fields: [
{ name: 'conversationId', type: scalar('ID') },
{ name: 'attachments', type: list(object('User')) },
],
};
}

const mutationFields: FakeField[] = [];
Expand Down
1 change: 1 addition & 0 deletions web/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,7 @@ export interface ConnectionTestResult {
endpoint?: string;
error?: string;
capabilities?: PsaCapabilities;
bodyCheck?: { ticket: string; characters: number; preview: string } | { ticket: string | null; error: string };
}

export interface PollSummary {
Expand Down
13 changes: 13 additions & 0 deletions web/src/pages/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,19 @@ function ConnectionResult({ result }: { result: ConnectionTestResult }) {
<li>
Ticket body:{' '}
{bodySource(caps) ? <code>{bodySource(caps)}</code> : <span className="font-medium">not found</span>}
{result.bodyCheck && 'characters' in result.bodyCheck && (
<span>
{' '}
— read {result.bodyCheck.characters} characters from ticket {result.bodyCheck.ticket}: “{result.bodyCheck.preview}
{result.bodyCheck.characters > result.bodyCheck.preview.length ? '…' : ''}”
</span>
)}
{result.bodyCheck && 'error' in result.bodyCheck && (
<span className="font-medium">
{' '}
— but reading it{result.bodyCheck.ticket ? ` from ticket ${result.bodyCheck.ticket}` : ''} failed: {result.bodyCheck.error}
</span>
)}
</li>
<li>
Note mutation:{' '}
Expand Down
Loading