mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-23 21:59:14 +09:00
feat(console): conversation model, transports, tests with fake transports (ADR-465 wip)
Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
1 parent
3f44b13f3e
commit
3c658f92de
5 files changed
+787
-3
No files matched your search
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* The conversation model (ADR-465): one thread per target, a composer, fan-out with side-by-side answers, relay, reply polling and a
|
||||
* masked, capped transcript. Pure and in memory: the module holds no timers and calls no transport (data/wf-send.ts does that, injected),
|
||||
* so every figure here is something a test can build by hand. What a thread shows was SENT or RECEIVED; nothing is composed for a target
|
||||
* that did not answer, and a cost is shown only where the provider reported one.
|
||||
*/
|
||||
import { jsonAfter } from './cli'
|
||||
import { tidy, type SendResult, type SendState } from './wf-send'
|
||||
import { MAX_FANOUT, type Target } from './wf-targets'
|
||||
|
||||
export type Who = 'you' | 'target'
|
||||
|
||||
export type Msg = {
|
||||
id: number
|
||||
atMs: number
|
||||
who: Who
|
||||
text: string
|
||||
/** `reply` and `queued`/`sent` describe what happened to a message of yours; `error` and `refused` say why it did not go. */
|
||||
state: SendState | 'you' | 'received'
|
||||
tokensIn?: number
|
||||
tokensOut?: number
|
||||
costUsd?: number
|
||||
model?: string
|
||||
}
|
||||
|
||||
export type Thread = {
|
||||
target: string
|
||||
msgs: Msg[]
|
||||
/** The newest envelope id or timestamp seen by a poll, so the next one asks only for what came after. */
|
||||
cursor?: string
|
||||
/** True while a poll timer runs for this thread (the controller owns the timer; this records that it should). */
|
||||
isWatching: boolean
|
||||
polls: number
|
||||
/** How many messages the cap has already dropped from the front. */
|
||||
dropped: number
|
||||
}
|
||||
|
||||
export type Convo = { threads: Map<string, Thread>; picked: string | null; seq: number }
|
||||
|
||||
export const MAX_THREADS = 24
|
||||
export const MAX_MSGS = 100
|
||||
export const MAX_TEXT = 4000
|
||||
/** A poll runs this often, at most this many times, then stops by itself: nothing watches forever. */
|
||||
export const POLL_MS = 20_000
|
||||
export const POLL_MAX = 30
|
||||
export const TRANSCRIPT_MAX = 60_000
|
||||
|
||||
export const newConvo = (): Convo => ({ threads: new Map(), picked: null, seq: 0 })
|
||||
|
||||
export function threadOf(convo: Convo, target: string): Thread | null {
|
||||
const held = convo.threads.get(target)
|
||||
|
||||
if (held !== undefined) return held
|
||||
if (convo.threads.size >= MAX_THREADS) return null
|
||||
|
||||
const made: Thread = { target, msgs: [], isWatching: false, polls: 0, dropped: 0 }
|
||||
|
||||
convo.threads.set(target, made)
|
||||
|
||||
return made
|
||||
}
|
||||
|
||||
/** Adds a message, masked and capped, dropping the oldest past the cap (and counting them). Null where there is no room for another thread. */
|
||||
export function addMessage(convo: Convo, target: string, entry: Omit<Msg, 'id'>): Msg | null {
|
||||
const thread = threadOf(convo, target)
|
||||
|
||||
if (thread === null) return null
|
||||
|
||||
const msg: Msg = { ...entry, id: ++convo.seq, text: tidy(entry.text, MAX_TEXT) }
|
||||
|
||||
thread.msgs.push(msg)
|
||||
|
||||
while (thread.msgs.length > MAX_MSGS) {
|
||||
thread.msgs.shift()
|
||||
thread.dropped++
|
||||
}
|
||||
|
||||
return msg
|
||||
}
|
||||
|
||||
/** Records what you sent and what came of it (the answer, the queue note or the reason it did not go). */
|
||||
export function recordSend(convo: Convo, target: Target, body: string, result: SendResult, nowMs: number): void {
|
||||
addMessage(convo, target.id, { atMs: nowMs, who: 'you', text: body, state: 'you' })
|
||||
addMessage(convo, target.id, { atMs: nowMs, who: 'target', text: result.text, state: result.state, ...(result.tokensIn !== undefined && { tokensIn: result.tokensIn }), ...(result.tokensOut !== undefined && { tokensOut: result.tokensOut }), ...(result.costUsd !== undefined && { costUsd: result.costUsd }), ...(result.model !== undefined && { model: result.model }) })
|
||||
}
|
||||
|
||||
export type Stats = { sent: number; answered: number; failed: number; tokensIn: number; tokensOut: number; usd: number | null; pricedAnswers: number }
|
||||
|
||||
/** Per-thread totals. USD sums only the answers whose provider reported one: `usd` is null when none did (n/a, not $0). */
|
||||
export function statsOf(thread: Thread): Stats {
|
||||
const stats: Stats = { sent: 0, answered: 0, failed: 0, tokensIn: 0, tokensOut: 0, usd: null, pricedAnswers: 0 }
|
||||
|
||||
for (const msg of thread.msgs) {
|
||||
if (msg.who === 'you') stats.sent++
|
||||
else if (msg.state === 'reply' || msg.state === 'received') stats.answered++
|
||||
else if (msg.state === 'error' || msg.state === 'refused') stats.failed++
|
||||
|
||||
stats.tokensIn += msg.tokensIn ?? 0
|
||||
stats.tokensOut += msg.tokensOut ?? 0
|
||||
|
||||
if (msg.costUsd !== undefined) {
|
||||
stats.usd = (stats.usd ?? 0) + msg.costUsd
|
||||
stats.pricedAnswers++
|
||||
}
|
||||
}
|
||||
|
||||
return stats
|
||||
}
|
||||
|
||||
export type CompareCell = { target: string; label: string; text: string; state: Msg['state'] | 'none'; tokens: string; usd: string }
|
||||
|
||||
/** The newest answer of each target to the question last asked of it, side by side; a target that has not answered says so. */
|
||||
export function compareOf(convo: Convo, targets: readonly Target[]): CompareCell[] {
|
||||
return targets.map(target => {
|
||||
const msgs = convo.threads.get(target.id)?.msgs ?? []
|
||||
const askedAt = msgs.findLastIndex(msg => msg.who === 'you')
|
||||
const answer = askedAt < 0 ? undefined : msgs.slice(askedAt + 1).findLast(msg => msg.who === 'target')
|
||||
|
||||
return {
|
||||
target: target.id,
|
||||
label: target.label,
|
||||
text: answer?.text ?? (askedAt < 0 ? 'not asked' : 'no answer yet'),
|
||||
state: answer?.state ?? 'none',
|
||||
tokens: answer === undefined || (answer.tokensIn === undefined && answer.tokensOut === undefined) ? 'tokens n/a' : `${answer.tokensIn ?? '?'} in · ${answer.tokensOut ?? '?'} out`,
|
||||
usd: answer?.costUsd === undefined ? 'cost n/a' : `$${answer.costUsd.toFixed(4)} (billed, as the provider reported it)`,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** What a relay sends: the answer of one target, attributed, with what to do with it. The body then goes through the target's own send and confirm card. */
|
||||
export function relayBody(from: Target, answer: string, instruction: string): string {
|
||||
const quoted = tidy(answer, 1200).replace(/\s+/g, ' ')
|
||||
const ask = instruction.trim() === '' ? 'Review it and say what you would change.' : instruction.trim()
|
||||
|
||||
return `Another assistant (${from.label}) answered: "${quoted}" ${ask}`.slice(0, 1500)
|
||||
}
|
||||
|
||||
/** The answer a relay would carry: the target's newest answer, or null if it has none. */
|
||||
export function lastAnswer(convo: Convo, target: string): string | null {
|
||||
const answer = convo.threads.get(target)?.msgs.findLast(msg => msg.who === 'target' && (msg.state === 'reply' || msg.state === 'received'))
|
||||
|
||||
return answer?.text ?? null
|
||||
}
|
||||
|
||||
/** A file name for a transcript: the target and the time, nothing a path could be built from. */
|
||||
export const transcriptName = (target: string, nowMs: number): string => `convo-${target.replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'thread'}-${new Date(nowMs).toISOString().replace(/[:.]/g, '-')}.md`
|
||||
|
||||
/** The thread as markdown, masked again here whatever the thread holds, and cut at the cap (the cut says how much was left out). */
|
||||
export function transcriptMarkdown(thread: Thread, target: Target, nowMs: number): { text: string; isCut: boolean } {
|
||||
const head = [`# Conversation with ${tidy(target.label, 80)}`, '', `Saved ${new Date(nowMs).toISOString()} by the ruflo console. Transport: ${target.transport}. ${target.leavesText}.`, thread.dropped > 0 ? `The ${thread.dropped} oldest messages were dropped by the ${MAX_MSGS}-message cap.` : '', '']
|
||||
const body = thread.msgs.map(msg => `**${msg.who === 'you' ? 'you' : tidy(target.label, 60)}** (${new Date(msg.atMs).toISOString()}, ${msg.state}${msg.tokensIn !== undefined || msg.tokensOut !== undefined ? `, ${msg.tokensIn ?? '?'} in / ${msg.tokensOut ?? '?'} out tokens` : ''}${msg.costUsd === undefined ? '' : `, $${msg.costUsd.toFixed(4)} billed`}):\n\n${tidy(msg.text, MAX_TEXT)}\n`)
|
||||
const all = [...head, ...body].join('\n')
|
||||
|
||||
return all.length <= TRANSCRIPT_MAX ? { text: all, isCut: false } : { text: `${all.slice(0, TRANSCRIPT_MAX)}\n\n(cut at ${TRANSCRIPT_MAX} characters; ${all.length - TRANSCRIPT_MAX} more were not saved)\n`, isCut: true }
|
||||
}
|
||||
|
||||
export type Fetched = { msgs: { text: string; atMs: number }[]; cursor?: string }
|
||||
|
||||
/** `federation_bbs_watch` output: the envelopes after the cursor that were not written by this console. */
|
||||
export function fromBbs(stdout: string, nowMs: number): Fetched {
|
||||
const json = jsonAfter(stdout) as { envelopes?: { envelopeId?: unknown; payload?: { text?: unknown; from?: unknown }; timestamp?: unknown }[] } | null
|
||||
const list = Array.isArray(json?.envelopes) ? json.envelopes : []
|
||||
const last = list.at(-1)?.envelopeId
|
||||
const msgs = list.flatMap(item => (typeof item.payload?.text === 'string' && item.payload.from !== 'ruflo-console' ? [{ text: tidy(item.payload.text, MAX_TEXT), atMs: typeof item.timestamp === 'string' && Number.isFinite(Date.parse(item.timestamp)) ? Date.parse(item.timestamp) : nowMs }] : []))
|
||||
|
||||
return { msgs: msgs.slice(-20), ...(typeof last === 'string' && { cursor: last.slice(0, 80) }) }
|
||||
}
|
||||
|
||||
/** `x_federation_channel_read` output: messages with text that this console did not send and that came after the cursor (a created_at second). */
|
||||
export function fromChannel(stdout: string, cursor: string | undefined): Fetched {
|
||||
const json = jsonAfter(stdout) as { messages?: { created_at?: unknown; text?: unknown; from?: unknown; encrypted?: unknown }[] } | null
|
||||
const list = Array.isArray(json?.messages) ? json.messages : []
|
||||
const after = cursor === undefined ? 0 : Number(cursor)
|
||||
const fresh = list.filter(item => typeof item.created_at === 'number' && item.created_at > after)
|
||||
const newest = fresh.reduce((top, item) => Math.max(top, item.created_at as number), after)
|
||||
const msgs = fresh.flatMap(item => (item.encrypted === true ? [{ text: '(an encrypted message this console holds no key for)', atMs: (item.created_at as number) * 1000 }] : typeof item.text === 'string' && item.from !== 'ruflo-console' ? [{ text: tidy(item.text, MAX_TEXT), atMs: (item.created_at as number) * 1000 }] : []))
|
||||
|
||||
return { msgs: msgs.slice(-20), ...(newest > after && { cursor: String(newest) }) }
|
||||
}
|
||||
|
||||
/** Applies a poll's finding: new messages become `received`, the cursor moves, the poll count rises and the watch ends at the cap. */
|
||||
export function applyFetch(convo: Convo, target: string, fetched: Fetched): number {
|
||||
const thread = threadOf(convo, target)
|
||||
|
||||
if (thread === null) return 0
|
||||
|
||||
for (const msg of fetched.msgs) addMessage(convo, target, { atMs: msg.atMs, who: 'target', text: msg.text, state: 'received' })
|
||||
|
||||
if (fetched.cursor !== undefined) thread.cursor = fetched.cursor
|
||||
|
||||
thread.polls++
|
||||
if (thread.polls >= POLL_MAX) thread.isWatching = false
|
||||
|
||||
return fetched.msgs.length
|
||||
}
|
||||
|
||||
/** The read a poll runs for a polled target, as `ruflo mcp exec` params; null for a target that is not polled. */
|
||||
export function pollParams(target: Target, cursor: string | undefined, nowMs: number): { tool: string; params: Record<string, unknown> } | null {
|
||||
if (target.transport === 'bbs') return { tool: 'federation_bbs_watch', params: { roomId: target.ref, limit: 20, ...(cursor !== undefined && { sinceEnvelopeId: cursor }) } }
|
||||
if (target.transport === 'x-channel') return { tool: 'x_federation_channel_read', params: { channel: target.ref, sinceSeconds: cursor === undefined ? 600 : Math.max(30, Math.min(3600, Math.ceil(nowMs / 1000 - Number(cursor)) + 5)), limit: 20 } }
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** What a fan-out means: who gets the question, who is cut, and who was named but unknown. */
|
||||
export function fanOutOf(picked: readonly Target[], unknown: readonly string[]): { targets: Target[]; why: string } {
|
||||
const targets = picked.slice(0, MAX_FANOUT)
|
||||
const bits = [picked.length > MAX_FANOUT ? `only the first ${MAX_FANOUT} are asked` : '', unknown.length > 0 ? `not a target: ${unknown.slice(0, 4).map(name => `@${name}`).join(' ')}` : '']
|
||||
|
||||
return { targets, why: bits.filter(Boolean).join('; ') }
|
||||
}
|
||||
@@ -47,7 +47,7 @@ const endpointOf = (target: Target, config: Config): Endpoint | undefined => end
|
||||
/** `task-12 the note`: the first word is the id, the rest the note. */
|
||||
export function taskNote(body: string): { id: string; note: string } | null {
|
||||
const [first = '', ...rest] = body.trim().split(/\s+/)
|
||||
const id = idOf(first)
|
||||
const id = /\d/.test(first) ? idOf(first) : null
|
||||
const note = rest.join(' ').trim()
|
||||
|
||||
return id === null || note === '' ? null : { id, note }
|
||||
@@ -65,7 +65,7 @@ export function payloadOf(target: Target, raw: string, deps: Pick<SendDeps, 'con
|
||||
if (!typed.ok) return typed
|
||||
|
||||
const body = typed.text
|
||||
const done = (shows: string, note: string): { ok: true; payload: Payload; body: string } => ({ ok: true, payload: { shows: tidy(shows, 700), note }, body })
|
||||
const done = (shows: string, note: string): { ok: true; payload: Payload; body: string } => ({ ok: true, payload: { shows: shows.slice(0, 700), note }, body })
|
||||
|
||||
switch (target.transport) {
|
||||
case 'prompt':
|
||||
|
||||
@@ -161,7 +161,7 @@ export function parseMentions(text: string, targets: readonly Target[]): Mention
|
||||
const found = targets.find(target => target.id === name)
|
||||
|
||||
if (name === 'all') {
|
||||
for (const target of targets.filter(held => held.leaves === 'machine' && ['send-message', 'hive', 'bbs'].includes(held.transport))) if (!picked.includes(target)) picked.push(target)
|
||||
for (const target of targets.filter(held => held.leaves === 'machine' && ['send-message', 'hive', 'bbs'].includes(held.transport) && held.ref !== 'propose')) if (!picked.includes(target)) picked.push(target)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* Stop, Message and Redirect (ADR-465): the exact engine call on the card, the engine's permission respected, the spike's real answers
|
||||
* classified, and every failure said as itself. Fake bridges only. Run with
|
||||
* npx vitest run plugins/ruflo-console/tests/wf-control.spec.ts --testTimeout=30000
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { ToolReply } from '../hooks/host'
|
||||
import { callTool, classifyReply, controlActions, ENGINE_ID, permissionOf, relayText, resumeText, type Bridge, type ControlAction, type ControlInput } from '../hooks/data/wf-control'
|
||||
import type { WfAgent, WfRun } from '../hooks/data/workflows'
|
||||
|
||||
const AGENT = 'acf991387298086c7'
|
||||
const RUN = 'wf_abc12345'
|
||||
|
||||
const agent = (over: Partial<WfAgent> = {}): WfAgent => ({ id: AGENT, label: 'sleeper', phase: 'Build', state: 'running', hasWorktree: false, ...over })
|
||||
const run = (over: Partial<WfRun> = {}): WfRun => ({ id: RUN, name: 'my flow', kind: 'workflow', state: 'running', phases: [{ title: 'Build', agents: [agent()], done: 0, total: 1, running: 1, failed: 0 }], running: 1, done: 0, failed: 0, idle: 0, total: 1, totalTokens: null, isTokensPartial: false, hasRecord: false, dir: '/home/u/.claude/projects/-p/sess/subagents/workflows/wf_abc12345', ...over })
|
||||
|
||||
type Calls = { tool: Record<string, unknown>[]; check: { tool: string; input: unknown }[]; fill: string[]; said: { label: string; ok: boolean; detail: string }[] }
|
||||
|
||||
function harness(over: { reply?: ToolReply | ((input: Record<string, unknown>) => ToolReply); verdict?: 'allow' | 'ask' | 'deny'; reject?: string; noTool?: boolean; fill?: boolean; text?: string; agent?: WfAgent | null; run?: WfRun } = {}): { input: ControlInput; calls: Calls } {
|
||||
const calls: Calls = { tool: [], check: [], fill: [], said: [] }
|
||||
const reply = over.reply ?? { text: JSON.stringify({ message: 'Successfully stopped task: acf991387298086c7 (sleeper)', task_type: 'local_agent' }) }
|
||||
const bridge: Bridge & { fillPrompt: (text: string) => Promise<boolean> } = {
|
||||
...(over.noTool === true ? {} : { toolCall: async (input: Record<string, unknown> & { tool: string }) => { calls.tool.push(input); if (over.reject !== undefined) throw new Error(over.reject); return typeof reply === 'function' ? reply(input) : reply } }),
|
||||
toolCheck: async (tool, input) => { calls.check.push({ tool, input }); return { decision: over.verdict ?? 'allow', ...(over.verdict === 'deny' && { reason: 'Bash(*) is denied' }) } },
|
||||
fillPrompt: async text => { calls.fill.push(text); return over.fill ?? true },
|
||||
}
|
||||
|
||||
return { calls, input: { run: over.run ?? run(), agent: over.agent === undefined ? agent() : over.agent, text: over.text ?? '', bridge, report: (label, ok, detail) => calls.said.push({ label, ok, detail }), isRunPath: path => path.startsWith('/home/u/.claude/projects/') && !path.includes('..') } }
|
||||
}
|
||||
|
||||
const by = (actions: ControlAction[], id: string): ControlAction => actions.find(action => action.id === id) as ControlAction
|
||||
|
||||
describe('classifyReply: the engine\'s words, as the spike saw them', () => {
|
||||
it('reads the real TaskStop success, the real TaskStop miss and the real SendMessage answers', () => {
|
||||
expect(classifyReply({ text: '{"message":"Successfully stopped task: acf991387298086c7 (sleeper)","task_type":"local_agent"}' })).toMatchObject({ ok: true, kind: 'done', text: expect.stringContaining('Successfully stopped task') })
|
||||
expect(classifyReply({ text: 'Error: No task found with ID: nonexistent', isError: true })).toMatchObject({ ok: false, kind: 'error', text: expect.stringContaining('No task found') })
|
||||
expect(classifyReply({ result: { success: true, message: 'Message queued for delivery to sleeper at its next tool round.' } })).toMatchObject({ ok: true, text: expect.stringContaining('queued') })
|
||||
expect(classifyReply({ text: '{"success":false,"message":"No agent named \'nobody\' is reachable.\\nUse ListAgents to see everyone you can message."}' })).toMatchObject({ ok: false, kind: 'error', text: expect.stringContaining('nobody') })
|
||||
})
|
||||
|
||||
it('a deny is a refusal, not an error; a missing bridge says so; nothing is invented for an empty answer', () => {
|
||||
expect(classifyReply({ deny: 'Permission to use TaskStop has been denied' })).toMatchObject({ ok: false, kind: 'denied', text: expect.stringContaining('the engine refused it') })
|
||||
expect(classifyReply(undefined)).toMatchObject({ ok: false, kind: 'not-wired' })
|
||||
expect(classifyReply({})).toMatchObject({ ok: true, text: 'the engine answered ok with no text' })
|
||||
})
|
||||
|
||||
it('masks a credential and strips escapes from what the engine said', () => {
|
||||
const said = classifyReply({ text: 'failed \u001b[31mred\u001b[0m token=sk-live-AAAABBBBCCCCDDDD', isError: true }).text
|
||||
|
||||
expect(said).not.toContain('sk-live')
|
||||
expect(said).not.toContain('\u001b')
|
||||
})
|
||||
|
||||
it('callTool turns a rejection into an error outcome and never throws', async () => {
|
||||
const { input } = harness({ reject: 'no such tool' })
|
||||
|
||||
expect(await callTool(input.bridge, { tool: 'Nope' })).toMatchObject({ ok: false, kind: 'error', text: 'no such tool' })
|
||||
expect(await callTool({}, { tool: 'TaskStop' })).toMatchObject({ kind: 'not-wired' })
|
||||
})
|
||||
|
||||
it('permissionOf reports the engine\'s verdict, and says so when it cannot ask', async () => {
|
||||
expect((await permissionOf(harness({ verdict: 'deny' }).input.bridge, 'TaskStop', {})).text).toContain('deny (Bash(*) is denied)')
|
||||
expect(await permissionOf({}, 'TaskStop', {})).toMatchObject({ decision: 'unknown' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('Stop', () => {
|
||||
it('shows the exact call, runs it through the host after the permission check, and reports the engine\'s own words', async () => {
|
||||
const { input, calls } = harness()
|
||||
const stop = by(controlActions(input), 'stop-agent')
|
||||
|
||||
expect(stop.proof).toBe('verified')
|
||||
expect(stop.call).toBe(`TaskStop {"task_id":"${AGENT}"}`)
|
||||
expect(stop.spec?.declared).toBe('write')
|
||||
expect(calls.tool).toHaveLength(0)
|
||||
|
||||
await stop.spec?.run?.()
|
||||
|
||||
expect(calls.check).toEqual([{ tool: 'TaskStop', input: { task_id: AGENT } }])
|
||||
expect(calls.tool).toEqual([{ tool: 'TaskStop', task_id: AGENT }])
|
||||
expect(calls.said).toEqual([expect.objectContaining({ ok: true, detail: expect.stringContaining('Successfully stopped task') })])
|
||||
expect(calls.said[0]?.detail).toContain('re-read the run')
|
||||
})
|
||||
|
||||
it('the run stop is labelled unverified (the spike never stopped a workflow run) and calls TaskStop with the run id', async () => {
|
||||
const { input, calls } = harness()
|
||||
const stop = by(controlActions(input), 'stop-run')
|
||||
|
||||
expect(stop.proof).toBe('unverified')
|
||||
expect(stop.proofText).toMatch(/not tried/)
|
||||
await stop.spec?.run?.()
|
||||
expect(calls.tool).toEqual([{ tool: 'TaskStop', task_id: RUN }])
|
||||
})
|
||||
|
||||
it('an engine "deny" from the permission check stops it before any call: no other route is tried', async () => {
|
||||
const { input, calls } = harness({ verdict: 'deny' })
|
||||
|
||||
await by(controlActions(input), 'stop-agent').spec?.run?.()
|
||||
|
||||
expect(calls.tool).toHaveLength(0)
|
||||
expect(calls.said[0]).toMatchObject({ ok: false, detail: expect.stringMatching(/permission check: deny.*no other route is tried/) })
|
||||
})
|
||||
|
||||
it('a deny answered by the call itself is shown the same way, and an unknown task is shown as an error', async () => {
|
||||
const denied = harness({ reply: { deny: 'Claude requested permissions to stop which is blocked' } })
|
||||
|
||||
await by(controlActions(denied.input), 'stop-agent').spec?.run?.()
|
||||
expect(denied.calls.said[0]).toMatchObject({ ok: false, detail: expect.stringMatching(/engine refused it.*no other route/) })
|
||||
|
||||
const missing = harness({ reply: { text: 'Error: No task found with ID: x', isError: true } })
|
||||
|
||||
await by(controlActions(missing.input), 'stop-agent').spec?.run?.()
|
||||
expect(missing.calls.said[0]).toMatchObject({ ok: false, detail: expect.stringContaining('No task found') })
|
||||
})
|
||||
|
||||
it('a host with no tool bridge has no stop spec and says why; an id the engine would not accept is not passed on', () => {
|
||||
const none = controlActions(harness({ noTool: true }).input)
|
||||
|
||||
expect(by(none, 'stop-agent').spec).toBeNull()
|
||||
expect(by(none, 'stop-agent').why).toMatch(/does not bind tool calls/)
|
||||
expect(by(controlActions(harness({ agent: agent({ id: 'a b;rm' }) }).input), 'stop-agent').spec).toBeNull()
|
||||
expect(ENGINE_ID.test('a1')).toBe(false)
|
||||
expect(by(controlActions(harness({ agent: null }).input), 'stop-agent').why).toMatch(/pick an agent/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Message', () => {
|
||||
it('needs the typed sentence, then shows the exact SendMessage, labelled queued-only', async () => {
|
||||
expect(by(controlActions(harness().input), 'message').spec).toBeNull()
|
||||
expect(by(controlActions(harness().input), 'message').why).toMatch(/type the guidance/)
|
||||
|
||||
const { input, calls } = harness({ text: 'use the cache', reply: { result: { success: true, message: 'Message queued for delivery to sleeper at its next tool round.' } } })
|
||||
const message = by(controlActions(input), 'message')
|
||||
|
||||
expect(message.proof).toBe('queued-only')
|
||||
expect(message.call).toBe(`SendMessage {"to":"${AGENT}","message":"use the cache"}`)
|
||||
await message.spec?.run?.()
|
||||
expect(calls.tool).toEqual([{ tool: 'SendMessage', to: AGENT, message: 'use the cache', summary: 'use the cache' }])
|
||||
expect(calls.said[0]).toMatchObject({ ok: true, detail: expect.stringMatching(/queued.*queued is not delivered/) })
|
||||
})
|
||||
|
||||
it('an unreachable agent is an error that offers the prompt-box text, not a success', async () => {
|
||||
const { input, calls } = harness({ text: 'hello', reply: { text: '{"success":false,"message":"No agent named x is reachable."}' } })
|
||||
|
||||
await by(controlActions(input), 'message').spec?.run?.()
|
||||
expect(calls.said[0]).toMatchObject({ ok: false, detail: expect.stringContaining('prepare as text') })
|
||||
})
|
||||
|
||||
it('a text with a credential in it, or a leading dash, is not sent at all', () => {
|
||||
expect(by(controlActions(harness({ text: 'use token=sk-live-AAAABBBBCCCCDDDD' }).input), 'message').why).toMatch(/credential/)
|
||||
expect(by(controlActions(harness({ text: '--force' }).input), 'message').why).toMatch(/dash/)
|
||||
})
|
||||
|
||||
it('the prompt-box prefill calls nothing and fills the relay text, saying the main session acts on it', async () => {
|
||||
const { input, calls } = harness({ text: 'use the cache' })
|
||||
const text = by(controlActions(input), 'text')
|
||||
|
||||
expect(text.proof).toBe('prefill')
|
||||
await text.spec?.run?.()
|
||||
expect(calls.tool).toHaveLength(0)
|
||||
expect(calls.fill).toEqual([relayText(run(), agent(), 'use the cache')])
|
||||
expect(calls.fill[0]).toContain('with SendMessage')
|
||||
expect(calls.said[0]).toMatchObject({ ok: true, detail: expect.stringContaining('press Enter') })
|
||||
})
|
||||
})
|
||||
|
||||
describe('Redirect: two halves, said as two', () => {
|
||||
it('stops the run, then prepares the resume text with the guidance; the card shows both', async () => {
|
||||
const { input, calls } = harness({ text: 'prefer the cache' })
|
||||
const redirect = by(controlActions(input), 'redirect')
|
||||
|
||||
expect(redirect.call).toContain(`TaskStop {"task_id":"${RUN}"}, then into the prompt box`)
|
||||
expect(redirect.spec?.note).toMatch(/only when the stop worked/)
|
||||
await redirect.spec?.run?.()
|
||||
expect(calls.tool).toEqual([{ tool: 'TaskStop', task_id: RUN }])
|
||||
expect(calls.fill).toHaveLength(1)
|
||||
expect(calls.fill[0]).toContain(`resumeFromRunId: "${RUN}"`)
|
||||
expect(calls.fill[0]).toContain('prefer the cache')
|
||||
expect(calls.fill[0]).toContain('/home/u/.claude/projects/-p/sess/workflows/scripts/my flow-wf_abc12345.js')
|
||||
expect(calls.said[0]).toMatchObject({ ok: true, detail: expect.stringContaining('press Enter there to resume') })
|
||||
})
|
||||
|
||||
it('when the stop fails the resume text is NOT prepared (a resume against a live run would fight it)', async () => {
|
||||
const { input, calls } = harness({ text: 'x y', reply: { text: 'Error: No task found', isError: true } })
|
||||
|
||||
await by(controlActions(input), 'redirect').spec?.run?.()
|
||||
expect(calls.fill).toHaveLength(0)
|
||||
expect(calls.said[0]?.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('resumeText refuses a run dir outside the projects folder (it names the scripts folder generically instead)', () => {
|
||||
expect(resumeText(run({ dir: '/etc/../x' }), null, 'g', () => false)).toContain('<session>/workflows/scripts')
|
||||
expect(resumeText(run({ id: 'a b' }), null, 'g', () => true)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('a ruflo swarm run', () => {
|
||||
it('has no Claude task to stop or message: the page says where its own verbs are, and offers no spec', () => {
|
||||
const actions = controlActions(harness({ run: run({ kind: 'ruflo-swarm' }) }).input)
|
||||
|
||||
expect(actions).toHaveLength(1)
|
||||
expect(actions[0]?.spec).toBeNull()
|
||||
expect(actions[0]?.proofText).toMatch(/not a Claude Code task/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,367 @@
|
||||
/**
|
||||
* The targets registry, the transports and the conversation model (ADR-465), with fake transports that record the exact payload. Run with
|
||||
* npx vitest run plugins/ruflo-console/tests/wf-convo.spec.ts --testTimeout=30000
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { HiveInfo } from '../hooks/data/parse'
|
||||
import { addMessage, applyFetch, compareOf, fanOutOf, fromBbs, fromChannel, lastAnswer, MAX_MSGS, MAX_THREADS, newConvo, pollParams, POLL_MAX, recordSend, relayBody, statsOf, threadOf, transcriptMarkdown, transcriptName, TRANSCRIPT_MAX } from '../hooks/data/wf-convo'
|
||||
import { chatBody, parseChat, payloadOf, sendTo, taskNote, type SendDeps } from '../hooks/data/wf-send'
|
||||
import { endpointsOf, isBaseUrl, MAX_FANOUT, OPENROUTER, parseConfig, parseMentions, peersOf, targetsOf, type Target } from '../hooks/data/wf-targets'
|
||||
|
||||
const KEY = 'sk-or-v1-0123456789abcdefSECRET'
|
||||
const hive = { topology: 'hierarchical-mesh', strategy: 'raft', queen: 'q', queenTerm: 1, workers: ['a1'], pending: [], history: [], broadcasts: [], memoryKeys: [] } as unknown as HiveInfo
|
||||
|
||||
type Rec = { run: { argv: readonly string[]; timeoutMs: number; stdin?: string }[]; http: { url: string; init: { method: string; headers: Record<string, string>; body: string } }[]; tool: Record<string, unknown>[]; prompts: string[] }
|
||||
|
||||
function deps(over: Partial<SendDeps> & { env?: string | null; httpReply?: { ok: boolean; status: number; text: string }; runReply?: (argv: readonly string[]) => { exitCode: number; stdout: string; stderr: string }; verdict?: 'allow' | 'deny' } = {}): { d: SendDeps; rec: Rec } {
|
||||
const rec: Rec = { run: [], http: [], tool: [], prompts: [] }
|
||||
const d: SendDeps = {
|
||||
cli: ['npx', '--offline', '@claude-flow/cli@latest'],
|
||||
helper: '/home/u/.claude/helpers/federation.sh',
|
||||
trustedPeers: new Set(['zenbook']),
|
||||
cwd: '/work/proj',
|
||||
hive,
|
||||
config: parseConfig('endpoint:metallm=https://gw.example.com/v1|COG_KEY|cognitum-auto; bbs:ops; x:pub:team'),
|
||||
run: async (argv, timeoutMs, stdin) => {
|
||||
rec.run.push({ argv, timeoutMs, ...(stdin !== undefined && { stdin }) })
|
||||
|
||||
if (argv[0] === 'printenv') return over.env === null ? { exitCode: 1, stdout: '', stderr: '' } : { exitCode: 0, stdout: `${over.env ?? KEY}\n`, stderr: '' }
|
||||
|
||||
return over.runReply?.(argv) ?? { exitCode: 0, stdout: 'Result:\n{"success":true}', stderr: '' }
|
||||
},
|
||||
httpSend: async (url, init) => { rec.http.push({ url, init }); return over.httpReply ?? { ok: true, status: 200, text: JSON.stringify({ model: 'm', choices: [{ message: { content: 'an answer' } }], usage: { prompt_tokens: 12, completion_tokens: 5 } }) } },
|
||||
submitPrompt: async text => { rec.prompts.push(text) },
|
||||
toolCall: async input => { rec.tool.push(input); return { text: '{"success":true,"message":"Message queued for delivery to sleeper at its next tool round."}' } },
|
||||
toolCheck: async () => ({ decision: over.verdict ?? 'allow' }),
|
||||
...over,
|
||||
}
|
||||
|
||||
return { d, rec }
|
||||
}
|
||||
|
||||
const all = (d: SendDeps): Target[] => targetsOf({ agents: [{ id: 'acf991387298086c7', name: 'sleeper' }], peers: [{ host: 'zenbook', trusted: true }, { host: 'ruv-mac-mini', trusted: false }], config: d.config, hasHive: true, hasCodex: true })
|
||||
const t = (d: SendDeps, id: string): Target => all(d).find(target => target.id === id) as Target
|
||||
|
||||
describe('the config option and the targets', () => {
|
||||
it('parses endpoints, rooms and channels, and refuses what could leak: a key as the env name, credentials in a URL, plain http to the internet', () => {
|
||||
const ok = parseConfig('endpoint:metallm=https://gw.example.com/v1/|COG_KEY|cognitum-auto; bbs:ops; x:prv:0123456789abcdef; x:pub:team')
|
||||
|
||||
expect(ok.errors).toEqual([])
|
||||
expect(ok.endpoints).toEqual([{ name: 'metallm', baseUrl: 'https://gw.example.com/v1', keyEnv: 'COG_KEY', model: 'cognitum-auto' }])
|
||||
expect(ok.rooms).toEqual(['ops'])
|
||||
expect(ok.channels).toEqual(['prv:0123456789abcdef', 'pub:team'])
|
||||
|
||||
const bad = parseConfig('endpoint:a=https://x.com/v1|sk-live-SECRETSECRET|m; endpoint:b=https://u:p@x.com/v1|KEY|m; endpoint:c=http://evil.example.com/v1|KEY|m; endpoint:d=https://x.com/v1?k=1|KEY|m; x:nope; bbs:a b; endpoint:e=https://x.com/v1|KEY|')
|
||||
|
||||
expect(bad.endpoints).toEqual([])
|
||||
expect(bad.errors).toHaveLength(7)
|
||||
expect(bad.errors.join('\n')).not.toContain('sk-live-SECRETSECRET'.slice(0, 20) + 'X')
|
||||
expect(isBaseUrl('http://127.0.0.1:8080/v1')).toBe(true)
|
||||
expect(isBaseUrl('http://box.tail1399ff.ts.net:11434/v1')).toBe(true)
|
||||
expect(isBaseUrl('http://evil.example.com/v1')).toBe(false)
|
||||
})
|
||||
|
||||
it('offers OpenRouter by default unless the person names their own, and reads peers from the helper\'s file', () => {
|
||||
expect(endpointsOf(parseConfig('')).map(entry => entry.name)).toEqual(['openrouter'])
|
||||
expect(endpointsOf(parseConfig('endpoint:openrouter=https://openrouter.ai/api/v1|OTHER_KEY|x/y')).map(entry => entry.keyEnv)).toEqual(['OTHER_KEY'])
|
||||
expect(peersOf('{"peers":[{"host":"zenbook","trusted":true},{"host":"bad host"},{"host":"ruvzen"}]}')).toEqual([{ host: 'zenbook', trusted: true }, { host: 'ruvzen', trusted: false }])
|
||||
expect(peersOf('not json')).toEqual([])
|
||||
expect(peersOf(null)).toEqual([])
|
||||
})
|
||||
|
||||
it('every target declares its transport, what leaves the machine, its cost class and how a reply arrives', () => {
|
||||
const { d } = deps()
|
||||
const targets = all(d)
|
||||
|
||||
expect(targets.map(target => target.id)).toEqual(['claude', 'sleeper', 'hive', 'hive-propose', 'task', 'bbs-ops', 'x-pub-team', 'peer-zenbook', 'peer-ruv-mac-mini', 'codex', 'metallm', 'openrouter'])
|
||||
|
||||
for (const target of targets) {
|
||||
expect(target.leavesText.length).toBeGreaterThan(5)
|
||||
expect(target.costText.length).toBeGreaterThan(5)
|
||||
expect(target.arrivalText.length).toBeGreaterThan(5)
|
||||
}
|
||||
|
||||
expect(t(d, 'x-pub-team').leavesText).toMatch(/PUBLIC/)
|
||||
expect(t(d, 'peer-ruv-mac-mini').label).toMatch(/not trusted/)
|
||||
expect(t(d, 'openrouter').leavesText).toContain('$OPENROUTER_API_KEY')
|
||||
expect(t(d, 'openrouter').leavesText).not.toContain(KEY)
|
||||
expect(t(d, 'bbs-ops').arrival).toBe('polled')
|
||||
expect(t(d, 'claude').arrival).toBe('turn')
|
||||
})
|
||||
|
||||
it('with no hive, no codex and no config the list is honest and short', () => {
|
||||
const none = targetsOf({ agents: [], peers: [], config: parseConfig(''), hasHive: false, hasCodex: false })
|
||||
|
||||
expect(none.map(target => target.id)).toEqual(['claude', 'task', 'openrouter'])
|
||||
})
|
||||
|
||||
it('@mentions pick targets, @all picks what stays on the machine, unknown names are reported, and the fan-out is capped', () => {
|
||||
const { d } = deps()
|
||||
const targets = all(d)
|
||||
|
||||
expect(parseMentions('@claude @openrouter what is raft?', targets)).toMatchObject({ body: 'what is raft?', unknown: [] })
|
||||
expect(parseMentions('@claude @openrouter what is raft?', targets).targets.map(target => target.id)).toEqual(['claude', 'openrouter'])
|
||||
expect(parseMentions('@all heads up', targets).targets.map(target => target.id)).toEqual(['sleeper', 'hive', 'bbs-ops'])
|
||||
expect(parseMentions('@nobody hi @claude', targets)).toMatchObject({ unknown: ['nobody'] })
|
||||
expect(parseMentions('@claude @sleeper @hive @hive-propose @task @bbs-ops @codex @openrouter q', targets).targets).toHaveLength(MAX_FANOUT)
|
||||
expect(fanOutOf(targets, ['x']).why).toMatch(/only the first 6.*@x/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the exact payload on the card equals what is sent', () => {
|
||||
it('prompt, SendMessage, hive, task, bbs, x, peer, codex and http each show their exact call', async () => {
|
||||
const { d, rec } = deps()
|
||||
const body = 'how do we shard this?'
|
||||
const cases: [string, RegExp][] = [
|
||||
['claude', /^to Claude in this session, as a visible prompt: "how do we shard this\?"$/],
|
||||
['sleeper', /^SendMessage \{"to":"acf991387298086c7","message":"how do we shard this\?"\}$/],
|
||||
['hive', /hive-mind_broadcast \{"message":"how do we shard this\?","priority":"normal","fromId":"console-operator"\}/],
|
||||
['bbs-ops', /federation_bbs_publish \{"roomId":"ops","msgType":"human-message","payload":\{"text":"how do we shard this\?","from":"ruflo-console"\}\}/],
|
||||
['x-pub-team', /x_federation_channel_publish \{"channel":"pub:team","msgType":"Status"/],
|
||||
['peer-zenbook', /^bash federation\.sh dispatch zenbook "how do we shard this\?"$/],
|
||||
['peer-ruv-mac-mini', /dispatch ruv-mac-mini "how do we shard this\?" --confirm$/],
|
||||
['codex', /^codex exec -s read-only --skip-git-repo-check --ephemeral -C \/work\/proj - \(prompt on stdin: "how do we shard this\?"\)$/],
|
||||
]
|
||||
|
||||
for (const [id, pattern] of cases) {
|
||||
const made = payloadOf(t(d, id), body, d)
|
||||
|
||||
expect(made.ok).toBe(true)
|
||||
expect(made.ok && made.payload.shows).toMatch(pattern)
|
||||
}
|
||||
|
||||
const http = payloadOf(t(d, 'openrouter'), body, d)
|
||||
|
||||
expect(http.ok && http.payload.shows).toContain(`POST ${OPENROUTER.baseUrl}/chat/completions Authorization: Bearer ‹from $OPENROUTER_API_KEY›`)
|
||||
expect(http.ok && http.payload.shows).toContain(chatBody(OPENROUTER, body))
|
||||
expect(http.ok && http.payload.shows).not.toContain(KEY)
|
||||
expect(rec.run).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('a message with a credential, a leading dash, no hive, a missing task id or a closed proposal slot is refused with the reason', () => {
|
||||
const { d } = deps()
|
||||
|
||||
expect(payloadOf(t(d, 'claude'), 'use api_key=sk-live-AAAABBBBCCCC', d)).toMatchObject({ ok: false, why: expect.stringMatching(/credential/) })
|
||||
expect(payloadOf(t(d, 'claude'), '--help', d)).toMatchObject({ ok: false })
|
||||
expect(payloadOf(t(d, 'hive'), 'x', { ...d, hive: null })).toMatchObject({ ok: false, why: expect.stringMatching(/no hive-mind/) })
|
||||
expect(payloadOf(t(d, 'task'), 'just a note', d)).toMatchObject({ ok: false, why: expect.stringMatching(/task id/) })
|
||||
expect(taskNote('task-12 the note')).toEqual({ id: 'task-12', note: 'the note' })
|
||||
expect(payloadOf(t(d, 'hive-propose'), 'design: use raft', { ...d, hive: { ...hive, pending: [{ id: 'p', type: 'x', strategy: 'raft', term: 1, status: 'pending', votesFor: 0, votesAgainst: 0 }] } as unknown as HiveInfo })).toMatchObject({ ok: false })
|
||||
})
|
||||
|
||||
it('sendTo runs exactly those transports: argv, stdin, headers and timeouts', async () => {
|
||||
const { d, rec } = deps()
|
||||
|
||||
await sendTo(d, t(d, 'claude'), 'hello')
|
||||
expect(rec.prompts).toEqual(['hello'])
|
||||
|
||||
const queued = await sendTo(d, t(d, 'sleeper'), 'hello')
|
||||
|
||||
expect(rec.tool).toEqual([{ tool: 'SendMessage', to: 'acf991387298086c7', message: 'hello', summary: 'hello' }])
|
||||
expect(queued).toMatchObject({ ok: true, state: 'queued', text: expect.stringContaining('queued is not delivered') })
|
||||
|
||||
await sendTo(d, t(d, 'bbs-ops'), 'hello')
|
||||
await sendTo(d, t(d, 'peer-zenbook'), 'hello')
|
||||
await sendTo(d, t(d, 'peer-ruv-mac-mini'), 'hello')
|
||||
await sendTo(d, t(d, 'codex'), 'hello')
|
||||
await sendTo(d, t(d, 'task'), 'task-9 look at the cache')
|
||||
|
||||
const argvs = rec.run.map(call => call.argv.join(' '))
|
||||
|
||||
expect(argvs[0]).toBe('npx --offline @claude-flow/cli@latest mcp exec -t federation_bbs_publish -p {"roomId":"ops","msgType":"human-message","payload":{"text":"hello","from":"ruflo-console"}}')
|
||||
expect(argvs[1]).toBe('bash /home/u/.claude/helpers/federation.sh dispatch zenbook hello')
|
||||
expect(argvs[2]).toBe('bash /home/u/.claude/helpers/federation.sh dispatch ruv-mac-mini hello --confirm')
|
||||
expect(rec.run[3]).toMatchObject({ argv: ['codex', 'exec', '-s', 'read-only', '--skip-git-repo-check', '--ephemeral', '-C', '/work/proj', '-'], stdin: 'hello', timeoutMs: 300_000 })
|
||||
expect(argvs[4]).toContain('-t task_update -p {"taskId":"task-9","result":{"guidance":"look at the cache"}}')
|
||||
expect(rec.run[1]?.timeoutMs).toBe(600_000)
|
||||
})
|
||||
|
||||
it('the engine\'s permission "deny" for SendMessage stops the send before the call', async () => {
|
||||
const { d, rec } = deps({ verdict: 'deny' })
|
||||
|
||||
expect(await sendTo(d, t(d, 'sleeper'), 'hello')).toMatchObject({ ok: false, state: 'refused' })
|
||||
expect(rec.tool).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the OpenAI-compatible transport and its key', () => {
|
||||
it('reads the key from the NAMED variable, sends it in one header, and returns the answer with the tokens it reported', async () => {
|
||||
const { d, rec } = deps()
|
||||
const result = await sendTo(d, t(d, 'openrouter'), 'compare raft and paxos')
|
||||
|
||||
expect(rec.run[0]?.argv).toEqual(['printenv', 'OPENROUTER_API_KEY'])
|
||||
expect(rec.http).toHaveLength(1)
|
||||
expect(rec.http[0]?.url).toBe('https://openrouter.ai/api/v1/chat/completions')
|
||||
expect(rec.http[0]?.init.headers.authorization).toBe(`Bearer ${KEY}`)
|
||||
expect(JSON.parse(rec.http[0]?.init.body ?? '{}')).toEqual({ model: 'openrouter/auto', messages: [{ role: 'user', content: 'compare raft and paxos' }], usage: { include: true } })
|
||||
expect(result).toMatchObject({ ok: true, state: 'reply', text: 'an answer', tokensIn: 12, tokensOut: 5, model: 'm' })
|
||||
expect(result.costUsd).toBeUndefined()
|
||||
})
|
||||
|
||||
it('a non-OpenRouter endpoint is not sent the usage field; the gateway key comes from its own variable', async () => {
|
||||
const { d, rec } = deps()
|
||||
|
||||
await sendTo(d, t(d, 'metallm'), 'hi')
|
||||
expect(rec.run[0]?.argv).toEqual(['printenv', 'COG_KEY'])
|
||||
expect(JSON.parse(rec.http[0]?.init.body ?? '{}')).toEqual({ model: 'cognitum-auto', messages: [{ role: 'user', content: 'hi' }] })
|
||||
})
|
||||
|
||||
it('an unset variable sends nothing; a provider that echoes the key back gets it masked; an HTTP error is shown as one', async () => {
|
||||
const unset = deps({ env: null })
|
||||
|
||||
expect(await sendTo(unset.d, t(unset.d, 'openrouter'), 'hi')).toMatchObject({ ok: false, state: 'refused', text: expect.stringContaining('$OPENROUTER_API_KEY is not set') })
|
||||
expect(unset.rec.http).toHaveLength(0)
|
||||
|
||||
const echo = deps({ httpReply: { ok: true, status: 200, text: JSON.stringify({ choices: [{ message: { content: `your key is ${KEY}, done` } }] }) } })
|
||||
const answered = await sendTo(echo.d, t(echo.d, 'openrouter'), 'hi')
|
||||
|
||||
expect(answered.text).not.toContain(KEY)
|
||||
expect(answered.text).toContain('‹masked›')
|
||||
|
||||
const failed = deps({ httpReply: { ok: false, status: 401, text: `bad key ${KEY}` } })
|
||||
const refused = await sendTo(failed.d, t(failed.d, 'openrouter'), 'hi')
|
||||
|
||||
expect(refused).toMatchObject({ ok: false, state: 'error', text: expect.stringContaining('HTTP 401') })
|
||||
expect(refused.text).not.toContain(KEY)
|
||||
})
|
||||
|
||||
it('parseChat reports only a cost the provider billed, and says when the answer has no message', () => {
|
||||
expect(parseChat(JSON.stringify({ choices: [{ message: { content: 'ok' } }], usage: { prompt_tokens: 1, completion_tokens: 2, cost: 0.0123 } }))).toMatchObject({ costUsd: 0.0123, tokensIn: 1, tokensOut: 2 })
|
||||
expect(parseChat('<html>')).toMatchObject({ ok: false, text: 'the endpoint did not answer with JSON' })
|
||||
expect(parseChat(JSON.stringify({ error: { message: 'rate limited' } }))).toMatchObject({ ok: false, text: expect.stringContaining('rate limited') })
|
||||
})
|
||||
})
|
||||
|
||||
describe('threads, answers side by side, relay and the transcript', () => {
|
||||
const { d } = deps()
|
||||
const claude = t(d, 'claude')
|
||||
const router = t(d, 'openrouter')
|
||||
|
||||
it('records what was sent and what came of it, per target, masked and capped', () => {
|
||||
const convo = newConvo()
|
||||
|
||||
recordSend(convo, router, 'q1', { ok: true, state: 'reply', text: `a1 token=${KEY}`, tokensIn: 10, tokensOut: 20, costUsd: 0.5 }, 1000)
|
||||
expect(convo.threads.get('openrouter')?.msgs.map(msg => `${msg.who}:${msg.state}`)).toEqual(['you:you', 'target:reply'])
|
||||
expect(convo.threads.get('openrouter')?.msgs[1]?.text).not.toContain(KEY)
|
||||
|
||||
for (let i = 0; i < MAX_MSGS + 5; i++) addMessage(convo, 'openrouter', { atMs: i, who: 'you', text: 'word '.repeat(1000), state: 'you' })
|
||||
|
||||
const thread = convo.threads.get('openrouter')
|
||||
|
||||
expect(thread?.msgs).toHaveLength(MAX_MSGS)
|
||||
expect(thread?.dropped).toBeGreaterThan(0)
|
||||
expect(thread?.msgs[0]?.text.length).toBe(4000)
|
||||
})
|
||||
|
||||
it('a thread count cap refuses the 25th target rather than growing', () => {
|
||||
const convo = newConvo()
|
||||
|
||||
for (let i = 0; i < MAX_THREADS; i++) expect(threadOf(convo, `t${i}`)).not.toBeNull()
|
||||
expect(threadOf(convo, 'one-more')).toBeNull()
|
||||
expect(addMessage(convo, 'one-more', { atMs: 0, who: 'you', text: 'x', state: 'you' })).toBeNull()
|
||||
})
|
||||
|
||||
it('totals tokens, and shows USD only from billed answers: n/a, never $0, when nobody reported one', () => {
|
||||
const convo = newConvo()
|
||||
|
||||
recordSend(convo, router, 'q', { ok: true, state: 'reply', text: 'a', tokensIn: 3, tokensOut: 4 }, 1)
|
||||
expect(statsOf(convo.threads.get('openrouter') as never)).toMatchObject({ sent: 1, answered: 1, tokensIn: 3, tokensOut: 4, usd: null })
|
||||
recordSend(convo, router, 'q', { ok: true, state: 'reply', text: 'a', costUsd: 0.25 }, 2)
|
||||
recordSend(convo, router, 'q', { ok: false, state: 'error', text: 'boom' }, 3)
|
||||
expect(statsOf(convo.threads.get('openrouter') as never)).toMatchObject({ usd: 0.25, pricedAnswers: 1, failed: 1, answered: 2 })
|
||||
})
|
||||
|
||||
it('compares the newest answer of each target to its last question, and says who has not answered or was not asked', () => {
|
||||
const convo = newConvo()
|
||||
|
||||
recordSend(convo, router, 'q', { ok: true, state: 'reply', text: 'answer R', tokensIn: 1, tokensOut: 2, costUsd: 0.001 }, 1)
|
||||
addMessage(convo, 'claude', { atMs: 2, who: 'you', text: 'q', state: 'you' })
|
||||
|
||||
const cells = compareOf(convo, [claude, router, t(d, 'codex')])
|
||||
|
||||
expect(cells.map(cell => `${cell.target}:${cell.text}`)).toEqual(['claude:no answer yet', 'openrouter:answer R', 'codex:not asked'])
|
||||
expect(cells[1]).toMatchObject({ tokens: '1 in · 2 out', usd: expect.stringContaining('$0.0010 (billed') })
|
||||
expect(cells[0]?.usd).toBe('cost n/a')
|
||||
})
|
||||
|
||||
it('relay carries one target\'s answer, attributed, to another, and goes through that target\'s own send', async () => {
|
||||
const convo = newConvo()
|
||||
|
||||
recordSend(convo, router, 'q', { ok: true, state: 'reply', text: 'use raft' }, 1)
|
||||
|
||||
const answer = lastAnswer(convo, 'openrouter') as string
|
||||
const body = relayBody(router, answer, 'Do you agree?')
|
||||
|
||||
expect(body).toBe('Another assistant (openrouter (openrouter/auto)) answered: "use raft" Do you agree?')
|
||||
expect(lastAnswer(convo, 'claude')).toBeNull()
|
||||
|
||||
const sent = deps()
|
||||
|
||||
await sendTo(sent.d, t(sent.d, 'codex'), body)
|
||||
expect(sent.rec.run[0]?.stdin).toBe(body)
|
||||
})
|
||||
|
||||
it('the transcript is masked again, names the cap, and is cut with the amount left out', () => {
|
||||
const convo = newConvo()
|
||||
|
||||
recordSend(convo, router, 'q', { ok: true, state: 'reply', text: 'a', tokensIn: 1, tokensOut: 2, costUsd: 0.01 }, Date.UTC(2026, 9, 5))
|
||||
;(convo.threads.get('openrouter')?.msgs[0] as { text: string }).text = `injected api_key=${KEY}`
|
||||
|
||||
const small = transcriptMarkdown(convo.threads.get('openrouter') as never, router, Date.UTC(2026, 9, 5))
|
||||
|
||||
expect(small.isCut).toBe(false)
|
||||
expect(small.text).not.toContain(KEY)
|
||||
expect(small.text).toContain('1 in / 2 out tokens, $0.0100 billed')
|
||||
expect(small.text).toContain('Transport: http')
|
||||
|
||||
const big = newConvo()
|
||||
|
||||
for (let i = 0; i < MAX_MSGS; i++) addMessage(big, 'openrouter', { atMs: i, who: 'you', text: 'word '.repeat(800), state: 'you' })
|
||||
|
||||
const cut = transcriptMarkdown(big.threads.get('openrouter') as never, router, 0)
|
||||
|
||||
expect(cut.isCut).toBe(true)
|
||||
expect(cut.text.length).toBeLessThan(TRANSCRIPT_MAX + 200)
|
||||
expect(cut.text).toMatch(/cut at 60000 characters; \d+ more were not saved/)
|
||||
expect(transcriptName('x-prv:../../etc', 0)).toBe('convo-x-prv-etc-1970-01-01T00-00-00-000Z.md')
|
||||
expect(transcriptName('///', 0)).toMatch(/^convo-thread-/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reply polling', () => {
|
||||
it('reads new bbs envelopes after the cursor, ignoring this console\'s own', () => {
|
||||
const out = `Result:\n${JSON.stringify({ envelopes: [{ envelopeId: 'e1', payload: { text: 'mine', from: 'ruflo-console' }, timestamp: '2026-10-05T00:00:00Z' }, { envelopeId: 'e2', payload: { text: 'peer says hi' }, timestamp: '2026-10-05T00:00:05Z' }] })}`
|
||||
|
||||
expect(fromBbs(out, 9)).toEqual({ msgs: [{ text: 'peer says hi', atMs: Date.parse('2026-10-05T00:00:05Z') }], cursor: 'e2' })
|
||||
expect(fromBbs('no json here', 9)).toEqual({ msgs: [] })
|
||||
})
|
||||
|
||||
it('reads channel messages newer than the cursor, shows an undecryptable one as such, and moves the cursor', () => {
|
||||
const out = JSON.stringify({ messages: [{ created_at: 100, text: 'old', from: 'k' }, { created_at: 200, text: 'new', from: 'k' }, { created_at: 210, encrypted: true }, { created_at: 220, text: 'mine', from: 'ruflo-console' }] })
|
||||
const got = fromChannel(out, '150')
|
||||
|
||||
expect(got.msgs.map(msg => msg.text)).toEqual(['new', '(an encrypted message this console holds no key for)'])
|
||||
expect(got.cursor).toBe('220')
|
||||
})
|
||||
|
||||
it('builds the read as a real tool call, only for polled targets, and stops watching at the cap', () => {
|
||||
const { d } = deps()
|
||||
|
||||
expect(pollParams(t(d, 'bbs-ops'), 'e2', 0)).toEqual({ tool: 'federation_bbs_watch', params: { roomId: 'ops', limit: 20, sinceEnvelopeId: 'e2' } })
|
||||
expect(pollParams(t(d, 'x-pub-team'), undefined, 0)?.params).toMatchObject({ channel: 'pub:team', sinceSeconds: 600, limit: 20 })
|
||||
expect(pollParams(t(d, 'claude'), undefined, 0)).toBeNull()
|
||||
|
||||
const convo = newConvo()
|
||||
const thread = threadOf(convo, 'bbs-ops') as NonNullable<ReturnType<typeof threadOf>>
|
||||
|
||||
thread.isWatching = true
|
||||
expect(applyFetch(convo, 'bbs-ops', { msgs: [{ text: 'hi', atMs: 1 }], cursor: 'e9' })).toBe(1)
|
||||
expect(thread.cursor).toBe('e9')
|
||||
expect(thread.msgs[0]).toMatchObject({ who: 'target', state: 'received' })
|
||||
|
||||
for (let i = 0; i < POLL_MAX; i++) applyFetch(convo, 'bbs-ops', { msgs: [] })
|
||||
|
||||
expect(thread.isWatching).toBe(false)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user