File size: 6,944 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Chat ("Ask the co-worker") client. One turn = one POST answered as Server-Sent Events:
// intent {tool,args} 路 tool {name,ok,summary} 路 delta {text} 路 result {cards,links,sources} 路 action {...} 路 done {message_id}.
// Text from the server is always rendered as plain text; links and cards come only from the structured `result`.
import { ApiError, csrfToken } from '../api/client';
import type { ProcessStep, Scenario } from '../api/types';

export interface ChatLink { label: string; to: string }
export interface ChatSource { label: string; to?: string }
export interface ChatItem { label: string; value: string; id?: string; decision?: 'approve' | 'skip' }
export interface ChatAction {
  action_id: string; tool: 'start_run' | 'approve_scenarios' | 'cancel_run' | 'add_note'; status: 'proposed' | 'confirmed' | 'cancelled' | 'expired' | 'failed';
  title: string; verb: string; items: ChatItem[]; counts?: { approve: number; skip: number } | null; review?: ChatLink | null;
  preview: { method: string; path: string; body: unknown }; expires_at: string; executed_at?: string | null;
  result?: { run_id?: string; status?: string; approved?: number; skipped?: number; by?: string; at?: string; to?: string; code?: string; detail?: string } | null;
}
export type ChatCard =
  | { type: 'readiness'; module: string; name: string; verdict: string; run_id: string | null; counts: Record<string, number>; steps: ProcessStep[] }
  | { type: 'run'; run_id: string; title: string; status: string; status_words: string; pending_gate: string | null; mode: string; counts: { scenarios: number; tested: number; failing: number; waiting: number } }
  | { type: 'failures'; run_id: string; items: { case_id: string; title: string | null; step: string | null; outcome: string; expected: string | null; actual: string | null; suggestion: string; priority_words?: string }[] }
  | { type: 'scenario'; scenario: Scenario }
  | { type: 'changes'; module: string; items: { id: string; area: string; summary: string; affected_steps: string[]; gap: boolean; covering: number; verification: string }[] }
  | { type: 'runs'; items: { run_id: string; title: string; status: string; status_words: string; pending_gate: string | null }[] }
  | { type: 'pods'; items: { id: number; name: string; kind: string; runnable: boolean; reason: string | null }[] };
export interface ChatResult { cards: ChatCard[]; links: ChatLink[]; sources: ChatSource[]; no_source?: boolean }
export interface ChatContext { run_id?: string | null; pod_id?: number | null; module?: string | null }
export interface ChatMessage {
  key: string; role: 'user' | 'assistant'; text: string; tool?: string | null; result?: ChatResult; action?: ChatAction | null; pending?: boolean; error?: string;
  /** Who answered: the built-in assistant (cards and sources from the app's data) or the Hermes assistant (plain text). */
  by?: 'builtin' | 'hermes'; model?: string;
}

async function call<T>(path: string, method: string, body?: unknown): Promise<T> {
  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  const t = csrfToken();
  if (t && method !== 'GET') headers['X-CSRF-Token'] = t;
  const r = await fetch(path, { method, headers, credentials: 'same-origin', body: body === undefined ? undefined : JSON.stringify(body) });
  if (r.status === 204) return undefined as T;
  const j = await r.json().catch(() => ({}));
  if (!r.ok) throw new ApiError(r.status, j.code ?? 'HTTP_ERROR', typeof j.detail === 'string' ? j.detail : `HTTP ${r.status}`, j, j.request_id);
  return j as T;
}

/** The person's conversations, most recent first (at most 50). */
export interface ConversationSummary { id: string; run_id: string | null; pod_id: number | null; title: string | null; created_at: string; last_at: string }
export const listConversations = () => call<{ items: ConversationSummary[] }>('/api/chat/conversations', 'GET');
export const createConversation = (run_id?: string | null) => call<{ id: string }>('/api/chat/conversations', 'POST', run_id ? { run_id } : {});
export const getConversation = (id: string) =>
  call<{ id: string; messages: { id: number; role: 'user' | 'assistant'; text: string; tool: string | null; action: ChatAction | null }[] }>(`/api/chat/conversations/${encodeURIComponent(id)}`, 'GET');
export const deleteConversation = (id: string) => call<unknown>(`/api/chat/conversations/${encodeURIComponent(id)}`, 'DELETE');
export const confirmAction = (id: string) => call<{ status: string; result: NonNullable<ChatAction['result']> }>(`/api/chat/actions/${encodeURIComponent(id)}/confirm`, 'POST', {});
export const cancelAction = (id: string) => call<{ status: string }>(`/api/chat/actions/${encodeURIComponent(id)}/cancel`, 'POST', {});

/** Parses a text/event-stream body into (event, data) pairs. */
export function parseSse(buffer: string): { events: [string, unknown][]; rest: string } {
  const events: [string, unknown][] = [];
  const blocks = buffer.split('\n\n');
  const rest = blocks.pop() ?? '';
  for (const b of blocks) {
    let ev = 'message';
    let data = '';
    for (const line of b.split('\n')) {
      if (line.startsWith('event: ')) ev = line.slice(7).trim();
      else if (line.startsWith('data: ')) data += line.slice(6);
    }
    if (data) { try { events.push([ev, JSON.parse(data)]); } catch { /* ignore a broken frame */ } }
  }
  return { events, rest };
}

/** Sends one message and reports each event as it arrives. Resolves when the turn is done. */
export async function sendMessage(convId: string, text: string, context: ChatContext, onEvent: (event: string, data: unknown) => void): Promise<void> {
  const headers: Record<string, string> = { 'Content-Type': 'application/json', Accept: 'text/event-stream' };
  const t = csrfToken();
  if (t) headers['X-CSRF-Token'] = t;
  const ctx = { ...Object.fromEntries(Object.entries(context).filter(([, v]) => v !== undefined)), tz_offset: -new Date().getTimezoneOffset() };
  const r = await fetch(`/api/chat/conversations/${encodeURIComponent(convId)}/messages`, { method: 'POST', headers, credentials: 'same-origin', body: JSON.stringify({ text, context: ctx }) });
  if (!r.ok) {
    const j = await r.json().catch(() => ({}));
    throw new ApiError(r.status, j.code ?? 'HTTP_ERROR', typeof j.detail === 'string' ? j.detail : `HTTP ${r.status}`, j, j.request_id);
  }
  if (!r.body) {
    for (const [e, d] of parseSse(`${await r.text()}\n\n`).events) onEvent(e, d);
    return;
  }
  const reader = r.body.getReader();
  const dec = new TextDecoder();
  let buf = '';
  for (;;) {
    const { done, value } = await reader.read();
    if (value) buf += dec.decode(value, { stream: true });
    const p = parseSse(done ? `${buf}\n\n` : buf);
    buf = done ? '' : p.rest;
    for (const [e, d] of p.events) onEvent(e, d);
    if (done) return;
  }
}