All files / src/entities/duo sessions.ts

100% Statements 126/126
100% Branches 107/107
100% Functions 17/17
100% Lines 107/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 25821x   21x 21x 21x               21x 21x                       21x         21x   21x 166x 4x     21x 131x 131x 131x 130x 131x                                 145x 144x 144x 143x             133x 133x   22x 20x                 11x 11x 11x 11x 133x 133x 8x 3x 3x   6x 6x       21x       17x 17x 1x 16x 16x 16x           16x 5x 5x 5x   11x 11x 140x 11x 6x 113x 113x 2x 2x   111x   6x                                                 18x       15x 15x     3x     2x     2x         43x             15x 15x 9x 9x 1x 8x 1x 7x 7x     5x 5x 4x 4x 3x 3x 2x 1x   3x             21x 30x 30x 30x 26x 21x 1x   20x 20x     18x 17x   18x 17x   3x 3x 3x           17x 1x 16x 16x 1x 15x 15x 15x                                  
import { graphqlSupports } from '../instance-version';
import type { EffectivePolicy } from '../../configuration/policy';
import { extractSimpleId } from '../../utils/idConversion';
import { ResponseLimitError } from '../../utils/bounded-json';
import {
  assertWorkflowProject,
  permitsDuoProject,
  readDuoProject,
  workflowProject,
  UnverifiableDuoProjectError,
  type DuoProject,
} from './access';
import { preview, isDuoChat } from './discovery';
import {
  DETAILS,
  HISTORY,
  readWorkflow,
  requestDuo,
  workflowGid,
  workflowPage,
  type Workflow,
  type Message,
} from './queries';
import type { BrowseDuoSessionsInput } from './schema';
 
export const WAITING = new Set([
  'input_required',
  'plan_approval_required',
  'tool_call_approval_required',
]);
const TERMINAL = new Set(['finished', 'failed', 'stopped']);
 
export function statusCode(row: Workflow): string | null {
  if (typeof row.statusName === 'string') return row.statusName;
  return typeof row.status === 'string' ? row.status.toLowerCase() : null;
}
 
export function sessionMetadata(row: Workflow): Record<string, unknown> {
  const status = statusCode(row);
  let pollAfter: number | null = null;
  if (status === 'created') pollAfter = 120;
  else if (status === 'running') pollAfter = 30;
  return {
    workflow_id: extractSimpleId(row.id),
    project_id: row.projectId === null ? null : extractSimpleId(row.projectId),
    status,
    status_label: row.humanStatus,
    flow: row.workflowDefinition ?? null,
    web_url: row.webUrl ?? null,
    created_at: row.createdAt,
    poll_after_seconds: pollAfter,
  };
}
 
function listedSession(
  row: Workflow,
  selected: DuoProject | null,
  policy: EffectivePolicy,
): boolean {
  if (isDuoChat(row.workflowDefinition)) return false;
  const id = row.projectId === null ? null : extractSimpleId(row.projectId);
  if (selected && id !== selected.id) return false;
  return !policy.operatorProjectIds || (id !== null && policy.operatorProjectIds.has(id));
}
 
async function listedProject(
  row: Workflow,
  projectReads: Map<string, Promise<DuoProject>>,
): Promise<DuoProject | null> {
  try {
    return await workflowProject(row, projectReads);
  } catch (error) {
    if (error instanceof UnverifiableDuoProjectError) return null;
    throw error;
  }
}
 
/** Bound simultaneous project responses, counting cache misses rather than session rows. */
async function listedProjects(
  rows: Workflow[],
  projectReads: Map<string, Promise<DuoProject>>,
): Promise<Array<DuoProject | null>> {
  const projects: Array<DuoProject | null> = [];
  const pending: Array<Promise<DuoProject | null>> = [];
  let started = projectReads.size;
  for (const row of rows) {
    pending.push(listedProject(row, projectReads));
    if (projectReads.size - started < 4) continue;
    projects.push(...(await Promise.all(pending)));
    pending.length = 0;
    started = projectReads.size;
  }
  projects.push(...(await Promise.all(pending)));
  return projects;
}
 
/** Metadata-only pagination: detailed messages from disallowed projects are never requested. */
export async function listDuoSessions(
  input: Extract<BrowseDuoSessionsInput, { action: 'list' }>,
  policy: EffectivePolicy,
): Promise<unknown> {
  const selected = input.project_id === undefined ? null : await readDuoProject(input.project_id);
  if (selected && !permitsDuoProject(selected, policy))
    throw new Error('Duo project is outside the working scope');
  const page = await workflowPage(input.first, input.after);
  const sessions: Record<string, unknown>[] = [];
  const result = {
    sessions,
    pageInfo: page.pageInfo,
    filtered: true,
    skipped_unverifiable_sessions: 0,
  };
  if (!policy.scopeEnforcer) {
    for (const row of page.nodes)
      if (listedSession(row, selected, policy)) sessions.push(sessionMetadata(row));
    return result;
  }
  const projectReads = new Map<string, Promise<DuoProject>>();
  if (selected) projectReads.set(selected.id, Promise.resolve(selected));
  const rows = page.nodes.filter((row) => listedSession(row, selected, policy));
  const projects = await listedProjects(rows, projectReads);
  for (let index = 0; index < rows.length; index++) {
    const project = projects[index];
    if (!project) {
      result.skipped_unverifiable_sessions++;
      continue;
    }
    if (permitsDuoProject(project, policy)) sessions.push(sessionMetadata(rows[index]));
  }
  return result;
}
 
interface LinkConnection<T> {
  nodes: Array<T | null>;
  pageInfo: { hasNextPage: boolean };
}
interface ObjectLink {
  id: string;
  title: string;
  webUrl: string;
}
interface Details extends Workflow {
  latestCheckpoint?: { lastDuoMessage?: Message | null } | null;
  mergeRequestLinks?: LinkConnection<{ mergeRequest: ObjectLink | null }> | null;
  workItemLinks?: LinkConnection<{ workItem: ObjectLink | null }> | null;
  noteLinks?: LinkConnection<{ note: { id: string; url: string; body: string } | null }> | null;
}
interface History extends Workflow {
  latestCheckpoint: { duoMessages: Message[] } | null;
}
 
function agentMessage(
  message: Message | null | undefined,
): message is Message & { content: string } {
  return !!message?.content && (message.role === 'assistant' || message.messageType === 'agent');
}
 
function createdObjects(row: Details): Record<string, unknown> {
  const connections = [row.mergeRequestLinks, row.workItemLinks, row.noteLinks];
  return {
    merge_requests:
      row.mergeRequestLinks?.nodes.flatMap((link) =>
        link?.mergeRequest ? [link.mergeRequest] : [],
      ) ?? null,
    work_items:
      row.workItemLinks?.nodes.flatMap((link) => (link?.workItem ? [link.workItem] : [])) ?? null,
    notes:
      row.noteLinks?.nodes.flatMap((link) =>
        link?.note
          ? [{ id: link.note.id, url: link.note.url, body: preview(link.note.body, 160) }]
          : [],
      ) ?? null,
    limit: 20,
    truncated: connections.some((connection) => connection?.pageInfo.hasNextPage),
  };
}
 
async function latestAnswer(
  row: Details,
): Promise<{ answer: ReturnType<typeof preview>; history: string }> {
  const last = row.latestCheckpoint?.lastDuoMessage;
  if (agentMessage(last)) return { answer: preview(last.content, 4000), history: 'available' };
  const status = statusCode(row);
  if (status === null || (!WAITING.has(status) && !TERMINAL.has(status)))
    return { answer: preview(null, 4000), history: 'not_requested' };
  if (!graphqlSupports('DuoWorkflowEvent', 'duoMessages'))
    return { answer: preview(null, 4000), history: 'unsupported' };
  try {
    const result = await requestDuo<{ duoWorkflowWorkflows: { nodes: History[] } }>(HISTORY, {
      id: workflowGid(row.id),
    });
    const workflow = result.duoWorkflowWorkflows.nodes.find((entry) => entry.id === row.id);
    if (workflow?.projectId !== row.projectId) throw new Error('Duo provenance changed');
    const messages = workflow.latestCheckpoint?.duoMessages;
    if (!messages) return { answer: preview(null, 4000), history: 'missing_checkpoint' };
    for (let index = messages.length - 1; index >= 0; index--)
      if (agentMessage(messages[index]))
        return { answer: preview(messages[index].content, 4000), history: 'available' };
    return { answer: preview(null, 4000), history: 'no_agent_answer' };
  } catch (error) {
    return {
      answer: preview(null, 4000),
      history: error instanceof ResponseLimitError ? 'too_large' : 'unreadable',
    };
  }
}
 
export async function getDuoSession(id: string, policy: EffectivePolicy): Promise<unknown> {
  const restricted = !!(policy.scopeEnforcer ?? policy.operatorProjectIds);
  const targeted = graphqlSupports('Query', 'duoWorkflowWorkflows', 'workflowId');
  const initial = restricted || !targeted ? await readWorkflow(id) : null;
  if (initial) await assertWorkflowProject(initial, policy);
  if (!targeted && initial !== null)
    return { ...sessionMetadata(initial), details_available: false, history: 'unsupported' };
  let row: Details;
  try {
    const result = await requestDuo<{ duoWorkflowWorkflows: { nodes: Details[] } }>(DETAILS, {
      id: workflowGid(id),
    });
    const found = result.duoWorkflowWorkflows.nodes.find(
      (entry) => extractSimpleId(entry.id) === extractSimpleId(id),
    );
    if (!found) throw new Error('Duo session is unavailable');
    row = found;
  } catch (error) {
    const metadata = initial ?? (await readWorkflow(id));
    await assertWorkflowProject(metadata, policy);
    return {
      ...sessionMetadata(metadata),
      details_available: false,
      history: error instanceof ResponseLimitError ? 'too_large' : 'unreadable',
    };
  }
  if (initial && initial.projectId !== row.projectId)
    throw new Error('Duo session project changed during lookup');
  await assertWorkflowProject(row, policy);
  if (isDuoChat(row.workflowDefinition))
    throw new Error('General Duo Chat is outside Duo session tools');
  const answer = await latestAnswer(row);
  const status = statusCode(row);
  return {
    ...sessionMetadata(row),
    details_available: true,
    summary: preview(row.summary, 1000),
    ...answer,
    created_objects: createdObjects(row),
    pending_input:
      status !== null && WAITING.has(status)
        ? {
            state: status,
            can_send: row.userPermissions?.resumeDuoWorkflow ?? null,
            guidance:
              'Send input only after the preceding CI job finishes. GitLab remains authoritative for authorization and concurrent state changes.',
          }
        : null,
  };
}