okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-int (a3024ed10) into f-split-qa1: qa2's s3237-s3238 kept, my 21 strings renumbered s3260-s32808667a3dbf

main
8.2 KiB156 linesraw
1import { useEffect, useSyncExternalStore } from 'react';
2import { api, ApiError } from './client';
3
4/**
5 * A chat's /plan and its queued messages as the host reports them (notes-split-agent6.md, "Backend contract for the ui5 worker"). The plan
6 * arrives whole every time it changes, in the chat stream as {type:'plan', event, plan} and as the SSE event 'plan' {chatId, event, plan}; the
7 * queue as {type:'queued-message', queue} and the SSE event 'queue' {chatId, queue}. A snapshot replaces what was there; null or an empty
8 * list clears it. The host owns both; every button asks it and draws the answer.
9 */
10export type PlanState = 'proposed' | 'approved' | 'rejected' | 'running' | 'paused' | 'done' | 'stopped';
11export type StepState = 'pending' | 'running' | 'done' | 'failed' | 'skipped';
12export interface PlanStep { id: string; text: string; detail?: string; summary?: string; state: StepState }
13export interface Plan { id: string; title: string; source: 'plan' | 'goal'; state: PlanState; steps: PlanStep[]; /** A plain sentence (an interface string) when the app stopped the planning turn early. */ caution?: string }
14export interface QueuedMessage { id: string; text: string; deliverAt: 'step' | 'end' }
15
16const PLAN_STATES = ['proposed', 'approved', 'rejected', 'running', 'paused', 'done', 'stopped'];
17const STEP_STATES = ['pending', 'running', 'done', 'failed', 'skipped'];
18
19export function readPlan(raw: unknown): Plan | null {
20  if (!raw || typeof raw !== 'object') return null;
21  const p = raw as Record<string, unknown>;
22  if (typeof p.id !== 'string' || !p.id || !PLAN_STATES.includes(String(p.state)) || !Array.isArray(p.steps)) return null;
23  const steps: PlanStep[] = [];
24  p.steps.forEach((s, i) => {
25    if (!s || typeof s !== 'object') return;
26    const r = s as Record<string, unknown>;
27    if (typeof r.text !== 'string' || !r.text.trim()) return;
28    steps.push({
29      id: typeof r.id === 'string' && r.id ? r.id : `s${i + 1}`, text: r.text,
30      state: STEP_STATES.includes(String(r.state)) ? r.state as StepState : 'pending',
31      ...(typeof r.detail === 'string' && r.detail ? { detail: r.detail } : {}),
32      ...(typeof r.summary === 'string' && r.summary ? { summary: r.summary } : {}),
33    });
34  });
35  if (!steps.length) return null;
36  return { id: p.id, title: typeof p.title === 'string' ? p.title : '', source: p.source === 'goal' ? 'goal' : 'plan', state: p.state as PlanState, steps };
37}
38
39export function readQueue(raw: unknown): QueuedMessage[] {
40  if (!Array.isArray(raw)) return [];
41  return raw.flatMap((q): QueuedMessage[] => {
42    if (!q || typeof q !== 'object') return [];
43    const r = q as Record<string, unknown>;
44    return typeof r.id === 'string' && r.id && typeof r.text === 'string' && r.text
45      ? [{ id: r.id, text: r.text, deliverAt: r.deliverAt === 'end' ? 'end' : 'step' }] : [];
46  });
47}
48
49const plans = new Map<string, Plan>();
50const queues = new Map<string, QueuedMessage[]>();
51const listeners = new Set<() => void>();
52const emit = () => listeners.forEach(fn => fn());
53const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
54
55export function applyPlanFrame(chatId: string, raw: unknown) {
56  const plan = readPlan(raw), before = plans.get(chatId);
57  if (!plan) { if (plans.delete(chatId)) emit(); return; }
58  if (before && JSON.stringify(before) === JSON.stringify(plan)) return;
59  plans.set(chatId, plan);
60  emit();
61}
62
63export function applyQueueFrame(chatId: string, raw: unknown) {
64  const items = readQueue(raw), before = queues.get(chatId) ?? [];
65  if (JSON.stringify(before) === JSON.stringify(items)) return;
66  if (items.length) queues.set(chatId, items); else queues.delete(chatId);
67  emit();
68}
69
70const NONE: QueuedMessage[] = [];
71export const planOf = (chatId: string | null | undefined): Plan | null => (chatId ? plans.get(chatId) ?? null : null);
72export const queueOf = (chatId: string | null | undefined): QueuedMessage[] => (chatId ? queues.get(chatId) ?? NONE : NONE);
73
74export function usePlan(chatId: string | null | undefined): Plan | null {
75  const plan = useSyncExternalStore(subscribe, () => planOf(chatId), () => null);
76  useEffect(() => { if (chatId) void loadPlan(chatId); }, [chatId]);
77  return plan;
78}
79
80export function useQueue(chatId: string | null | undefined): QueuedMessage[] {
81  const items = useSyncExternalStore(subscribe, () => queueOf(chatId), () => NONE);
82  useEffect(() => { if (chatId) void loadQueue(chatId); }, [chatId]);
83  return items;
84}
85
86export async function loadPlan(chatId: string) {
87  try { applyPlanFrame(chatId, (await api.get<{ plan: unknown }>(`/api/plan?sessionId=${encodeURIComponent(chatId)}`)).plan); }
88  catch { /* an older host has no plan route: no plan */ }
89}
90
91/** The waiting messages. Without `release` this only reads; the host never sends them from here. */
92export async function loadQueue(chatId: string) {
93  try { applyQueueFrame(chatId, (await api.get<{ queue: unknown }>(`/api/chat/queue?sessionId=${encodeURIComponent(chatId)}`)).queue); }
94  catch { /* an older host has no queue route: nothing queued */ }
95}
96
97/** Save the edited steps. Each step keeps its grey detail line when its words did not change. */
98export async function planEdit(chatId: string, plan: Plan, texts: string[]) {
99  const steps = texts.map((text, i) => { const was = plan.steps[i]; return was && was.text === text && was.detail ? { text, detail: was.detail } : text; });
100  const result = await api.post<{ plan: unknown }>('/api/plan/edit', { sessionId: chatId, planId: plan.id, steps });
101  applyPlanFrame(chatId, result.plan);
102}
103
104export async function planReject(chatId: string, planId: string) {
105  const result = await api.post<{ plan: unknown }>('/api/plan/reject', { sessionId: chatId, planId });
106  applyPlanFrame(chatId, result.plan);
107}
108
109/** Approve: the host answers with the plan and the message that carries it out; the caller sends that message as an ordinary turn. */
110export async function planApprove(chatId: string, planId: string): Promise<{ prompt: string }> {
111  const result = await api.post<{ plan: unknown; prompt: string }>('/api/plan/approve', { sessionId: chatId, planId });
112  applyPlanFrame(chatId, result.plan);
113  return { prompt: String(result.prompt ?? '') };
114}
115
116/** Put a message behind the running goal. Returns false when no goal is running (409), so the caller can send it the normal way. */
117export async function queueMessage(chatId: string, message: string): Promise<boolean> {
118  try {
119    const result = await api.post<{ queue: unknown }>('/api/chat/queue', { sessionId: chatId, message });
120    applyQueueFrame(chatId, result.queue);
121    return true;
122  } catch (e) {
123    if (e instanceof ApiError && e.status === 409) return false;
124    throw e;
125  }
126}
127
128/** Take a queued message back before it is sent. */
129export async function cancelQueued(chatId: string, id: string) {
130  const result = await api.post<{ queue: unknown }>('/api/chat/queue/cancel', { sessionId: chatId, id });
131  applyQueueFrame(chatId, result.queue);
132}
133
134/** The step the queued message waits for: the one running now, or the next that has not started. 1-based, 0 if there is none. */
135export function currentStep(plan: Plan | null): number {
136  if (!plan) return 0;
137  const running = plan.steps.findIndex(s => s.state === 'running');
138  if (running >= 0) return running + 1;
139  const next = plan.steps.findIndex(s => s.state === 'pending');
140  return next >= 0 ? next + 1 : 0;
141}
142
143/** The words under a queued message: when it will be sent. The first one goes out after the current step, the next ones after that. */
144export function queuedWhen(item: QueuedMessage, index: number, plan: Plan | null): { id: string; args?: unknown[] } {
145  if (item.deliverAt === 'end') return { id: 'Queued — sends when the goal finishes' };
146  if (index > 0) return { id: 'Queued — sends after that' };
147  const step = currentStep(plan);
148  return step > 0 ? { id: 'Queued — sends when step {0} finishes', args: [step] } : { id: 'Queued — sends when the goal finishes' };
149}
150
151export const stepsDone = (plan: Plan) => plan.steps.filter(s => s.state === 'done').length;
152
153/** The stored plan of a chat without asking the host (the one that asks is usePlan, used once per chat). */
154export function usePlanQuiet(chatId: string | null | undefined): Plan | null {
155  return useSyncExternalStore(subscribe, () => planOf(chatId), () => null);
156}