Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
/loop stops by itself: a count, a time or a stop condition in words is read when the loop is created and enforced by the scheduler
Niko1221c0abfdc3584f
diff --git a/apps/host/src/lib/loop-runner.ts b/apps/host/src/lib/loop-runner.tsnew file mode 100644index 000000000..6f489136c--- /dev/null+++ b/apps/host/src/lib/loop-runner.ts@@ -0,0 +1,120 @@+import { tr } from './i18n';+import { LOOP_MAX_FAILURES, LOOP_MAX_RUNS, judgeAnswer, loopEndNote, loopEvery, loopLimitNote, withStopRule, type LoopLimits, type LoopStop } from './loop';++/**+ * The /loop scheduler. It owns the timer, the count, the time limit and the "the answer says it is done" rule, so a stop condition+ * is enforced here, in the app, and never left to the model: once a loop has ended nothing is sent again.+ *+ * Everything outside (sending the message, reading the answer, adding a line to the chat, the clock) is passed in, so the same code+ * runs in the app (store.ts) and in the tests with a scripted model and a fake clock.+ */+export interface LoopHost {+ /** Send the message as an ordinary chat turn and resolve when the answer is complete. `answered` is false when nothing was sent (the chat was busy). */+ send(sessionId: string, message: { text: string; shown: string }): Promise<{ answered: boolean; text: string; failed: boolean }>;+ /** A line from the app itself in the chat (never sent to the model). */+ note(sessionId: string, text: string): void;+ /** False when the chat was deleted: the loop ends quietly. */+ exists(sessionId: string): boolean;+ /** True when this chat is open and nothing is being answered. */+ ready(sessionId: string): boolean;+ now(): number;+ setTimer(fn: () => void, ms: number): unknown;+ clearTimer(handle: unknown): void;+}++export interface LoopStart extends LoopLimits { everyMs: number; prompt: string }++interface LoopState extends LoopStart {+ answers: number;+ failures: number;+ startedAt: number;+ timer: unknown;+ running: boolean;+}++export class LoopScheduler {+ private readonly loops = new Map<string, LoopState>();+ /** How long to wait before looking again when the chat is busy or not open. */+ busyRetryMs = 15_000;++ constructor(private readonly host: LoopHost) {}++ isRunning(sessionId: string | null): boolean { return !!sessionId && this.loops.has(sessionId); }++ /** What the person is told for /loop with nothing after it. */+ describe(sessionId: string): string | null {+ const loop = this.loops.get(sessionId);+ if (!loop) return null;+ const limit = loopLimitNote(loop);+ return tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : '');+ }++ stop(sessionId: string): boolean {+ const loop = this.loops.get(sessionId);+ if (!loop) return false;+ if (loop.timer) this.host.clearTimer(loop.timer);+ this.loops.delete(sessionId);+ return true;+ }++ /** Start a loop and send its first message now. Returns false (and says why in the chat) when the chat already has one. */+ async start(sessionId: string, command: LoopStart): Promise<boolean> {+ if (this.loops.has(sessionId)) { this.host.note(sessionId, tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return false; }+ const loop: LoopState = { ...command, answers: 0, failures: 0, startedAt: this.host.now(), timer: null, running: false };+ this.loops.set(sessionId, loop);+ const limit = loopLimitNote(loop);+ this.host.note(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : ''));+ await this.run(sessionId);+ return true;+ }++ /** Send once, judge the answer, then either end the loop with a plain note or wait for the next time. */+ private async run(sessionId: string): Promise<void> {+ const loop = this.loops.get(sessionId);+ if (!loop || loop.running) return;+ loop.running = true;+ let why: LoopStop | null = null;+ try {+ const result = await this.host.send(sessionId, { text: withStopRule(loop.prompt, loop.stopWhen), shown: loop.prompt });+ // The person may have typed /loop stop while the answer was coming: nothing more happens then.+ if (this.loops.get(sessionId) !== loop) return;+ if (result.answered) {+ if (result.failed) loop.failures += 1; else { loop.failures = 0; loop.answers += 1; }+ why = judgeAnswer(loop, loop, result, this.host.now());+ }+ } catch {+ if (this.loops.get(sessionId) !== loop) return;+ loop.failures += 1;+ if (loop.failures >= LOOP_MAX_FAILURES) why = 'failures';+ } finally {+ loop.running = false;+ }+ if (why) { this.finish(sessionId, loop, why); return; }+ this.schedule(sessionId, loop.everyMs);+ }++ private finish(sessionId: string, loop: LoopState, why: LoopStop) {+ this.stop(sessionId);+ this.host.note(sessionId, loopEndNote(why, loop.answers));+ }++ private schedule(sessionId: string, ms: number) {+ const loop = this.loops.get(sessionId);+ if (!loop) return;+ loop.timer = this.host.setTimer(() => void this.tick(sessionId), ms);+ }++ private async tick(sessionId: string): Promise<void> {+ const loop = this.loops.get(sessionId);+ if (!loop) return;+ loop.timer = null;+ if (!this.host.exists(sessionId)) { this.stop(sessionId); return; }+ // The time is up, or the count is reached: never fire again, even if the last answer was not judged (a busy chat).+ if (loop.maxMs !== undefined && this.host.now() - loop.startedAt >= loop.maxMs) { this.finish(sessionId, loop, 'time'); return; }+ if (loop.maxRuns !== undefined && loop.answers >= loop.maxRuns) { this.finish(sessionId, loop, 'count'); return; }+ if (loop.answers >= LOOP_MAX_RUNS) { this.finish(sessionId, loop, 'cap'); return; }+ // Wait for a quiet moment: this chat is open and nothing is being answered.+ if (!this.host.ready(sessionId)) { this.schedule(sessionId, this.busyRetryMs); return; }+ await this.run(sessionId);+ }+}diff --git a/apps/host/src/lib/loop.ts b/apps/host/src/lib/loop.tsindex bd141df68..3de12c490 100644--- a/apps/host/src/lib/loop.ts+++ b/apps/host/src/lib/loop.ts@@ -3,20 +3,29 @@ import { tr } from './i18n';/*** /loop: send the same message again and again, every few minutes, while this chat is open.*- * /loop 10m check whether the build passes start (the message is sent now, then every 10 minutes)- * /loop stop stop- * /loop say whether a loop is running+ * /loop 10m check whether the build passes start (the message is sent now, then every 10 minutes)+ * /loop 5m say hi, stop after 3 answers stops by itself after the 3rd answer (a count in words works too)+ * /loop 10m check the build for the next 2 hours stops by itself when the time is up+ * /loop 5m check the build, stop when it passes stops when the answer says it is done+ * /loop stop stop+ * /loop say whether a loop is running** The loop lives in the app window: it waits for the chat to be idle, and it stops when the window closes.* For work that must go on with the app closed, a task on the Tasks screen is the right tool.+ *+ * A stop condition is the scheduler's job, not the model's: the count and the time are read when the loop is created and are+ * enforced by the scheduler (loop-runner.ts), and the scheduler also ends the loop when an answer says the work is done or stopped.+ * The model is never left to keep answering "stopped" every minute.*/export const LOOP_MIN_MS = 60_000;export const LOOP_MAX_MS = 24 * 3_600_000;export const LOOP_MAX_RUNS = 100;+/** This many answers in a row that failed (no model, an error) end the loop, so it does not retry a broken thing all day. */+export const LOOP_MAX_FAILURES = 3;export type LoopCommand =- | { kind: 'start'; everyMs: number; prompt: string }+ | { kind: 'start'; everyMs: number; prompt: string; maxRuns?: number; maxMs?: number; stopWhen?: string }| { kind: 'stop' }| { kind: 'status' }| { kind: 'help'; problem: string };@@ -24,7 +33,53 @@ export type LoopCommand =const UNITS: Record<string, number> = { s: 1000, sec: 1000, second: 1000, seconds: 1000, m: 60_000, min: 60_000, mins: 60_000, minute: 60_000, minutes: 60_000, h: 3_600_000, hr: 3_600_000, hour: 3_600_000, hours: 3_600_000 };/** The words shown when a /loop line is not understood. */-export const LOOP_USAGE = 'Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Use /loop stop to stop.';+export const LOOP_USAGE = 'Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Add "stop after 3 answers" to end it by itself. Use /loop stop to stop.';++const NUMBER_WORDS: Record<string, number> = { a: 1, an: 1, one: 1, once: 1, two: 2, twice: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, fifteen: 15, twenty: 20, thirty: 30, fifty: 50 };+const NUM = '(\\d{1,4}|[a-z]+)';+const THINGS = '(?:answers?|repl(?:y|ies)|responses?|runs?|times?|messages?|rounds?|checks?|iterations?|turns?|updates?|reports?|passes|tries|attempts?|loops?)';+const STOP_VERB = '(?:stop|end|quit|finish|halt|cancel|exit)';+const number = (word: string): number | null => {+ const n = /^\d+$/.test(word) ? Number(word) : NUMBER_WORDS[word.toLowerCase()];+ return Number.isFinite(n) && n >= 1 ? n : null;+};+/** A clause with its comma or "and" in front and its full stop behind, so removing it leaves a clean sentence. */+const clause = (body: string) => new RegExp(`(?:[,;.]\\s*|\\s+(?:and|then)\\s+|\\s+)?(?:please\\s+)?${body}(?=\\s*[,;.!]|\\s+(?:and|then)\\b|\\s*$)[,;.!]?`, 'i');++interface Limits { prompt: string; maxRuns?: number; maxMs?: number; stopWhen?: string }++/** The count, the time and the condition the person put in words, with those words taken out of the message the model gets. */+export function readLimits(text: string): Limits {+ let prompt = text.trim();+ let maxRuns: number | undefined;+ let maxMs: number | undefined;+ let stopWhen: string | undefined;+ const take = (re: RegExp, use: (m: RegExpMatchArray) => boolean) => {+ const m = prompt.match(re);+ if (!m || !use(m)) return;+ prompt = (prompt.slice(0, m.index) + ' ' + prompt.slice((m.index ?? 0) + m[0].length)).replace(/\s+/g, ' ').replace(/\s+([,.;!])/g, '$1').replace(/^[\s,;.]+|[\s,;]+$/g, '').trim();+ };+ const setRuns = (n: number | null) => { if (n === null) return false; maxRuns = Math.min(n, LOOP_MAX_RUNS); return true; };+ // "stop after 3 answers", "stop the loop after three replies", "stop after the 3rd run", "end after 5 more checks"+ take(clause(`${STOP_VERB}(?:\\s+(?:the\\s+)?(?:loop|looping|it|this|all))?\\s+after\\s+(?:the\\s+)?${NUM}(?:st|nd|rd|th)?\\s+(?:more\\s+)?${THINGS}`), m => setRuns(number(m[1])));+ // "only 3 times", "just 3 answers", "3 times only", "3 times", "for 3 answers", "up to 3 runs", "at most 3 times", "max 3 runs", "run it 3 times"+ if (maxRuns === undefined) take(clause(`(?:only|just|exactly|up\\s+to|at\\s+most|no\\s+more\\s+than|max(?:imum)?(?:\\s+of)?|for|do\\s+this|do\\s+it|repeat(?:\\s+this|\\s+it)?|run(?:\\s+this|\\s+it)?|send(?:\\s+this|\\s+it)?|ask(?:\\s+me)?)\\s+${NUM}\\s+${THINGS}(?:\\s+only)?`), m => setRuns(number(m[1])));+ if (maxRuns === undefined) take(clause(`${NUM}\\s+${THINGS}\\s+(?:only|in\\s+total|total|at\\s+most)`), m => setRuns(number(m[1])));+ if (maxRuns === undefined) take(clause(`${NUM}\\s+times`), m => setRuns(number(m[1])));+ if (maxRuns === undefined) take(clause(`(?:${STOP_VERB}\\s+)?(?:for\\s+)?(?:the\\s+)?(?:first|next)\\s+${NUM}\\s+${THINGS}`), m => setRuns(number(m[1])));+ // "for the next 2 hours", "for 30 minutes", "stop after 2 hours", "for an hour"+ const span = (m: RegExpMatchArray) => {+ const n = number(m[1]); const unit = UNITS[m[2].toLowerCase()];+ if (n === null || !unit || unit < 60_000) return false;+ maxMs = Math.min(n * unit, LOOP_MAX_MS);+ return true;+ };+ take(clause(`${STOP_VERB}(?:\\s+(?:the\\s+)?(?:loop|it|this))?\\s+after\\s+(?:about\\s+)?${NUM}\\s*(minutes?|mins?|hours?|hrs?|[mh])\\b`), span);+ if (maxMs === undefined) take(clause(`(?:for|over)\\s+(?:the\\s+)?(?:next\\s+)?(?:about\\s+)?${NUM}\\s*(minutes?|mins?|hours?|hrs?)\\b`), span);+ // "stop when the build passes", "stop once it is green", "until the file exists": the model judges it; the scheduler stops on its word+ take(clause(`(?:${STOP_VERB}\\s+(?:the\\s+loop\\s+)?(?:when|once|as\\s+soon\\s+as|if|the\\s+moment)|until)\\s+([^.;!]{3,160})`), m => { stopWhen = m[1].trim(); return true; });+ return { prompt, ...(maxRuns !== undefined ? { maxRuns } : {}), ...(maxMs !== undefined ? { maxMs } : {}), ...(stopWhen ? { stopWhen } : {}) };+}/** null means the text is an ordinary message. */export function parseLoop(text: string): LoopCommand | null {@@ -39,7 +94,9 @@ export function parseLoop(text: string): LoopCommand | null {const everyMs = Math.round(Number(timed[1]) * unit);if (everyMs < LOOP_MIN_MS) return { kind: 'help', problem: 'The shortest time between runs is 1 minute, so the model has time to finish each one.' };if (everyMs > LOOP_MAX_MS) return { kind: 'help', problem: 'The longest time between runs is 24 hours. For longer waits, use a task on the Tasks screen.' };- return { kind: 'start', everyMs, prompt: timed[3].trim() };+ const limits = readLimits(timed[3]);+ if (!limits.prompt) return { kind: 'help', problem: 'Say what to do each time, not only when to stop.' };+ return { kind: 'start', everyMs, ...limits };}/** "every 10 minutes", "every hour". */@@ -48,3 +105,68 @@ export function loopEvery(ms: number): string {const m = Math.round(ms / 60_000);return m === 1 ? tr('every minute') : tr('every {0} minutes', [m]);}++/** The line added to a message that carries a stop condition in words, so the model can say it is met (it is not shown in the chat). */+export const LOOP_DONE_WORD = 'DONE';+export function withStopRule(prompt: string, stopWhen?: string): string {+ return stopWhen ? `${prompt}\n\n(This repeats on a timer. If this is finished or "${stopWhen}" is true, begin your reply with the word ${LOOP_DONE_WORD} and say so in one sentence. Otherwise just answer.)` : prompt;+}++const plain = (text: string) => text.replace(/[*_`#>~]/g, '').replace(/\s+/g, ' ').trim();++/**+ * Does this reply say the work is finished or stopped? The scheduler ends the loop on it.+ *+ * Always: the model's own marker ("DONE ...", "LOOP DONE", "LOOP STOPPED") or a reply that is only "stopped" / "done" / "finished".+ * When the person stated a stop condition (a count, a time or a condition in words), also the short ways a model closes the job:+ * "Stopped.", "The loop is stopped.", "I have stopped as requested.", "Done, the build passes."+ */+export function replySaysDone(reply: string, stated: boolean): boolean {+ const text = plain(reply);+ if (!text) return false;+ if (/\bLOOP[ _-]?(?:DONE|STOPPED|STOP|COMPLETE|FINISHED|ENDED)\b/i.test(text)) return true;+ if (new RegExp(`^${LOOP_DONE_WORD}\\b`).test(text)) return true;+ const bare = text.replace(/[.!\s]+$/g, '').toLowerCase();+ if (/^(?:ok(?:ay)?[,. ]+)?(?:stopped|done|finished|complete|completed|all done|ended|stopping)$/.test(bare)) return true;+ if (!stated || text.length > 280) return false;+ return /^(?:ok(?:ay)?[,. ]+|sure[,. ]+|yes[,. ]+)?(?:the\s+)?(?:loop\s+(?:is\s+|has\s+)?(?:now\s+)?)?(?:stopped|done|finished|complete(?:d)?|ended|stopping|all done)\b/i.test(text)+ || /\b(?:loop|repeat\w*|schedule\w*)\s+(?:is\s+|has\s+been\s+|was\s+)?(?:now\s+)?(?:stopped|finished|complete(?:d)?|ended|over|done)\b/i.test(text)+ || /\bi(?:'ve|\s+have|'m|\s+am)?\s+(?:now\s+)?(?:stopped|stopping|done|finished)\b/i.test(text)+ || /\b(?:stop|end)\s+condition\s+(?:is\s+|has\s+been\s+)?met\b/i.test(text)+ || /\bnothing\s+(?:more|else|left)\s+to\s+(?:do|check|report)\b/i.test(text);+}++export interface LoopLimits { maxRuns?: number; maxMs?: number; stopWhen?: string }+export interface LoopProgress { answers: number; failures: number; startedAt: number }+export type LoopStop = 'count' | 'said-done' | 'time' | 'failures' | 'cap';++/** After an answer: should the loop end, and why? `reply` is the model's text of that run; `failed` is an answer that did not work. */+export function judgeAnswer(limits: LoopLimits, progress: LoopProgress, reply: { text: string; failed: boolean }, now: number): LoopStop | null {+ if (reply.failed) return progress.failures >= LOOP_MAX_FAILURES ? 'failures' : null;+ const stated = limits.maxRuns !== undefined || limits.maxMs !== undefined || !!limits.stopWhen;+ if (replySaysDone(reply.text, stated)) return 'said-done';+ if (limits.maxRuns !== undefined && progress.answers >= limits.maxRuns) return 'count';+ if (limits.maxMs !== undefined && now - progress.startedAt >= limits.maxMs) return 'time';+ if (progress.answers >= LOOP_MAX_RUNS) return 'cap';+ return null;+}++/** Plain words for the person when a loop ends by itself. */+export function loopEndNote(why: LoopStop, answers: number): string {+ switch (why) {+ case 'count': return tr('The loop is done: it ran {0} times, as you asked. Type /loop to start another.', [answers]);+ case 'said-done': return tr('The loop stopped because the last answer said the work is done. Type /loop to start another.');+ case 'time': return tr('The loop stopped because the time you set is up. Type /loop to start another.');+ case 'failures': return tr('The loop stopped because {0} runs in a row did not work. Check the model, then type /loop to start it again.', [LOOP_MAX_FAILURES]);+ default: return tr('The loop stopped after {0} runs. Type /loop again to start it again.', [LOOP_MAX_RUNS]);+ }+}++/** The part of the "Loop started" note that says how it ends by itself ('' when it only ends when the person stops it). */+export function loopLimitNote(limits: LoopLimits): string {+ const parts: string[] = [];+ if (limits.maxRuns !== undefined) parts.push(limits.maxRuns === 1 ? tr('It stops by itself after the first answer.') : tr('It stops by itself after {0} answers.', [limits.maxRuns]));+ if (limits.maxMs !== undefined) parts.push(tr('It stops by itself after {0} minutes.', [Math.max(1, Math.round(limits.maxMs / 60_000))]));+ if (limits.stopWhen) parts.push(tr('It stops by itself when an answer says the work is done.'));+ return parts.join(' ');+}diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.tsindex 9899b80c9..b38a25855 100644--- a/apps/host/src/lib/store.ts+++ b/apps/host/src/lib/store.ts@@ -1,7 +1,8 @@import { plainFailure, plainFailureText } from './plain-errors';import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase';import { updateAgent } from './agents';-import { LOOP_MAX_RUNS, LOOP_USAGE, loopEvery, parseLoop, type LoopCommand } from './loop';+import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop';+import { LoopScheduler } from './loop-runner';import { applyStatusFrame, clearStatus } from './live-status';import { applyGoalFrame } from './goal';import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables';@@ -1444,9 +1445,8 @@ export function exportConversation() {}/* ---------------------------------------------------------------- /loop- The same message, again and again, while the chat is open. See lib/loop.ts. */-interface LoopState { everyMs: number; prompt: string; runs: number; timer: ReturnType<typeof setTimeout> | null }-const loops = new Map<string, LoopState>();+ The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is+ lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. *//** A line from the app itself (not the model) in the transcript. It is never sent to the model. */function addNote(sessionId: string, content: string) {@@ -1454,50 +1454,34 @@ function addNote(sessionId: string, content: string) {patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] }));}-export function loopIsRunning(sessionId: string | null): boolean { return !!sessionId && loops.has(sessionId); }+const lastAnswer = (sessionId: string) => [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse().find(m => m.role === 'assistant' && !m.local);-function stopLoop(sessionId: string): boolean {- const loop = loops.get(sessionId);- if (!loop) return false;- if (loop.timer) clearTimeout(loop.timer);- loops.delete(sessionId);- return true;-}+const loopScheduler = new LoopScheduler({+ async send(sessionId, { text, shown }) {+ const before = lastAnswer(sessionId)?.id;+ await sendMessage(text, { fromLoop: true, shown, title: shown.length > 48 ? shown.slice(0, 47).trimEnd() + '…' : shown });+ const answer = lastAnswer(sessionId);+ if (!answer || answer.id === before || answer.streaming) return { answered: false, text: '', failed: false };+ return { answered: true, text: answer.content ?? '', failed: !!answer.error };+ },+ note: addNote,+ exists: sessionId => state.sessions.some(s => s.id === sessionId),+ ready: sessionId => state.activeSession === sessionId && !state.streaming,+ now: () => Date.now(),+ setTimer: (fn, ms) => setTimeout(fn, ms),+ clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),+});-function scheduleLoop(sessionId: string) {- const loop = loops.get(sessionId);- if (!loop) return;- loop.timer = setTimeout(() => void tickLoop(sessionId), loop.everyMs);-}--async function tickLoop(sessionId: string) {- const loop = loops.get(sessionId);- if (!loop) return;- if (!state.sessions.some(s => s.id === sessionId)) { stopLoop(sessionId); return; }- // Wait for a quiet moment: this chat is open and nothing is being answered.- if (state.activeSession !== sessionId || state.streaming) { loop.timer = setTimeout(() => void tickLoop(sessionId), 15_000); return; }- loop.runs += 1;- if (loop.runs > LOOP_MAX_RUNS) { stopLoop(sessionId); addNote(sessionId, tr('The loop stopped after {0} runs. Type /loop again to start it again.', [LOOP_MAX_RUNS])); return; }- await sendMessage(loop.prompt, { fromLoop: true });- scheduleLoop(sessionId);-}+export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); }async function runLoopCommand(command: LoopCommand) {const sessionId = state.activeSession ?? newSession().id;const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); };if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; }- if (command.kind === 'status') {- const loop = loops.get(sessionId);- say(loop ? tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) : tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE));- return;- }- if (command.kind === 'stop') { say(stopLoop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; }- if (loops.has(sessionId)) { say(tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return; }- loops.set(sessionId, { everyMs: command.everyMs, prompt: command.prompt, runs: 1, timer: null });- addNote(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [command.prompt, loopEvery(command.everyMs)]));+ if (command.kind === 'status') { say(loopScheduler.describe(sessionId) ?? tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); return; }+ if (command.kind === 'stop') { say(loopScheduler.stop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; }go('chat', sessionId);- await sendMessage(command.prompt, { fromLoop: true });- scheduleLoop(sessionId);+ await loopScheduler.start(sessionId, command);}/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.jsonindex 6f5f19805..d392b247e 100644--- a/apps/host/src/locales/de.json+++ b/apps/host/src/locales/de.json@@ -1,5 +1,15 @@{"s0001": "% PCIe",+ "s7301": "Tippen Sie /loop, wie oft und dann, was zu tun ist. Zum Beispiel: /loop 10m prüfe, ob der Build besteht. Mit „stop after 3 answers“ endet es von selbst. Mit /loop stop halten Sie es an.",+ "s7302": "Sagen Sie, was jedes Mal zu tun ist, nicht nur, wann es endet.",+ "s7303": "Die Schleife ist fertig: Sie lief {0}-mal, wie gewünscht. Mit /loop starten Sie eine neue.",+ "s7304": "Die Schleife wurde beendet, weil die letzte Antwort sagte, dass die Arbeit erledigt ist. Mit /loop starten Sie eine neue.",+ "s7305": "Die Schleife wurde beendet, weil die von Ihnen gesetzte Zeit abgelaufen ist. Mit /loop starten Sie eine neue.",+ "s7306": "Die Schleife wurde beendet, weil {0} Durchläufe hintereinander nicht funktioniert haben. Prüfen Sie das Modell und starten Sie sie mit /loop neu.",+ "s7307": "Es endet von selbst nach der ersten Antwort.",+ "s7308": "Es endet von selbst nach {0} Antworten.",+ "s7309": "Es endet von selbst nach {0} Minuten.",+ "s7310": "Es endet von selbst, wenn eine Antwort sagt, dass die Arbeit erledigt ist.","s7311": "Anthropic-Apps hängen /v1/messages selbst an, deshalb steht am Ende dieser Adresse kein /v1. In Claude Code setzen Sie ANTHROPIC_BASE_URL darauf.","s0002": "(optional)","s0003": ", Kontextcache passt nicht in den Speicher",diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.jsonindex 4b752d647..bb2df9408 100644--- a/apps/host/src/locales/en.json+++ b/apps/host/src/locales/en.json@@ -1,5 +1,15 @@{"s0001": "% PCIe",+ "s7301": "Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Add \"stop after 3 answers\" to end it by itself. Use /loop stop to stop.",+ "s7302": "Say what to do each time, not only when to stop.",+ "s7303": "The loop is done: it ran {0} times, as you asked. Type /loop to start another.",+ "s7304": "The loop stopped because the last answer said the work is done. Type /loop to start another.",+ "s7305": "The loop stopped because the time you set is up. Type /loop to start another.",+ "s7306": "The loop stopped because {0} runs in a row did not work. Check the model, then type /loop to start it again.",+ "s7307": "It stops by itself after the first answer.",+ "s7308": "It stops by itself after {0} answers.",+ "s7309": "It stops by itself after {0} minutes.",+ "s7310": "It stops by itself when an answer says the work is done.","s7311": "Anthropic apps add /v1/messages themselves, so this address has no /v1 at the end. In Claude Code, set ANTHROPIC_BASE_URL to it.","s0002": "(optional)","s0003": ", context cache does not fit",diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.jsonindex ce7d7f381..7f8344dac 100644--- a/apps/host/src/locales/es.json+++ b/apps/host/src/locales/es.json@@ -1,5 +1,15 @@{"s0001": "% PCIe",+ "s7301": "Escribe /loop, cada cuánto y luego qué hacer. Por ejemplo: /loop 10m comprueba si la compilación pasa. Añade \"stop after 3 answers\" para que termine solo. Usa /loop stop para pararlo.",+ "s7302": "Indica qué hacer cada vez, no solo cuándo parar.",+ "s7303": "El bucle terminó: se ejecutó {0} veces, como pediste. Escribe /loop para iniciar otro.",+ "s7304": "El bucle se detuvo porque la última respuesta dijo que el trabajo está terminado. Escribe /loop para iniciar otro.",+ "s7305": "El bucle se detuvo porque se acabó el tiempo que indicaste. Escribe /loop para iniciar otro.",+ "s7306": "El bucle se detuvo porque {0} ejecuciones seguidas no funcionaron. Revisa el modelo y escribe /loop para iniciarlo de nuevo.",+ "s7307": "Se detiene solo después de la primera respuesta.",+ "s7308": "Se detiene solo después de {0} respuestas.",+ "s7309": "Se detiene solo después de {0} minutos.",+ "s7310": "Se detiene solo cuando una respuesta dice que el trabajo está terminado.","s7311": "Las apps de Anthropic añaden /v1/messages por sí mismas, así que esta dirección no termina en /v1. En Claude Code, pon esta dirección en ANTHROPIC_BASE_URL.","s0002": "(opcional)","s0003": ", la caché de contexto no cabe",diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.jsonindex 68cb27cce..93fbf815b 100644--- a/apps/host/src/locales/ja.json+++ b/apps/host/src/locales/ja.json@@ -1,5 +1,15 @@{"s0001": "% PCIe",+ "s7301": "/loop、間隔、やることの順に入力します。例:/loop 10m ビルドが通るか確認する。「stop after 3 answers」を付けると自動で止まります。止めるときは /loop stop。",+ "s7302": "止める条件だけでなく、毎回やることも書いてください。",+ "s7303": "ループが終わりました。ご指定どおり {0} 回実行しました。もう一度始めるには /loop と入力します。",+ "s7304": "直前の回答が作業の完了を伝えたため、ループを止めました。もう一度始めるには /loop と入力します。",+ "s7305": "設定した時間になったため、ループを止めました。もう一度始めるには /loop と入力します。",+ "s7306": "{0} 回続けて失敗したため、ループを止めました。モデルを確認してから /loop と入力してやり直してください。",+ "s7307": "最初の回答のあとで自動的に止まります。",+ "s7308": "{0} 回答えたあとで自動的に止まります。",+ "s7309": "{0} 分後に自動的に止まります。",+ "s7310": "回答が作業の完了を伝えたときに自動的に止まります。","s7311": "Anthropic 系のアプリは /v1/messages を自分で付け足すため、このアドレスの末尾に /v1 はありません。Claude Code では ANTHROPIC_BASE_URL にこのアドレスを設定します。","s0002": "(任意)","s0003": "、コンテキストキャッシュが収まりません",diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.jsonindex 427895f89..5f8aca021 100644--- a/apps/host/src/locales/ko.json+++ b/apps/host/src/locales/ko.json@@ -1,5 +1,15 @@{"s0001": "% PCIe",+ "s7301": "/loop, 얼마나 자주, 그리고 할 일을 순서대로 입력하세요. 예: /loop 10m 빌드가 통과하는지 확인. \"stop after 3 answers\"를 붙이면 저절로 끝납니다. 멈추려면 /loop stop.",+ "s7302": "멈출 때만이 아니라 매번 할 일도 적어 주세요.",+ "s7303": "반복이 끝났습니다. 요청하신 대로 {0}번 실행했습니다. 다시 시작하려면 /loop를 입력하세요.",+ "s7304": "마지막 답변에서 작업이 끝났다고 해서 반복을 멈췄습니다. 다시 시작하려면 /loop를 입력하세요.",+ "s7305": "설정한 시간이 다 되어 반복을 멈췄습니다. 다시 시작하려면 /loop를 입력하세요.",+ "s7306": "{0}번 연속으로 실행이 되지 않아 반복을 멈췄습니다. 모델을 확인한 뒤 /loop를 입력해 다시 시작하세요.",+ "s7307": "첫 번째 답변 뒤에 저절로 멈춥니다.",+ "s7308": "답변이 {0}번 나온 뒤에 저절로 멈춥니다.",+ "s7309": "{0}분 뒤에 저절로 멈춥니다.",+ "s7310": "답변에서 작업이 끝났다고 하면 저절로 멈춥니다.","s7311": "Anthropic 앱은 /v1/messages를 스스로 붙이므로 이 주소 끝에는 /v1이 없습니다. Claude Code에서는 ANTHROPIC_BASE_URL에 이 주소를 넣으세요.","s0002": "(선택 사항)","s0003": ", 컨텍스트 캐시를 저장할 공간이 부족함",diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.jsonindex 05ec2fa59..4b9ad438e 100644--- a/apps/host/src/locales/pt.json+++ b/apps/host/src/locales/pt.json@@ -1,5 +1,15 @@{"s0001": "% PCIe",+ "s7301": "Digite /loop, com que frequência e depois o que fazer. Por exemplo: /loop 10m verifique se a compilação passa. Acrescente \"stop after 3 answers\" para terminar sozinho. Use /loop stop para parar.",+ "s7302": "Diga o que fazer a cada vez, não só quando parar.",+ "s7303": "O loop terminou: rodou {0} vezes, como você pediu. Digite /loop para iniciar outro.",+ "s7304": "O loop parou porque a última resposta disse que o trabalho está concluído. Digite /loop para iniciar outro.",+ "s7305": "O loop parou porque o tempo que você definiu acabou. Digite /loop para iniciar outro.",+ "s7306": "O loop parou porque {0} execuções seguidas não funcionaram. Verifique o modelo e digite /loop para iniciar de novo.",+ "s7307": "Ele para sozinho depois da primeira resposta.",+ "s7308": "Ele para sozinho depois de {0} respostas.",+ "s7309": "Ele para sozinho depois de {0} minutos.",+ "s7310": "Ele para sozinho quando uma resposta disser que o trabalho está concluído.","s7311": "Os apps da Anthropic acrescentam /v1/messages sozinhos, por isso este endereço não termina em /v1. No Claude Code, defina ANTHROPIC_BASE_URL com ele.","s0002": "(opcional)","s0003": ", o cache de contexto não cabe",diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.jsonindex d0f94a958..a365c401b 100644--- a/apps/host/src/locales/ru.json+++ b/apps/host/src/locales/ru.json@@ -1,5 +1,15 @@{"s0001": "% PCIe",+ "s7301": "Введите /loop, как часто и что делать. Например: /loop 10m проверь, проходит ли сборка. Добавьте «stop after 3 answers», чтобы цикл закончился сам. Чтобы остановить, введите /loop stop.",+ "s7302": "Напишите, что делать каждый раз, а не только когда остановиться.",+ "s7303": "Цикл завершён: он выполнился {0} раз, как вы просили. Введите /loop, чтобы запустить новый.",+ "s7304": "Цикл остановлен: в последнем ответе сказано, что работа закончена. Введите /loop, чтобы запустить новый.",+ "s7305": "Цикл остановлен: заданное вами время вышло. Введите /loop, чтобы запустить новый.",+ "s7306": "Цикл остановлен: {0} запусков подряд не удались. Проверьте модель и введите /loop, чтобы начать заново.",+ "s7307": "Он остановится сам после первого ответа.",+ "s7308": "Он остановится сам после {0} ответов.",+ "s7309": "Он остановится сам через {0} мин.",+ "s7310": "Он остановится сам, когда в ответе будет сказано, что работа закончена.","s7311": "Приложения Anthropic сами добавляют /v1/messages, поэтому в конце этого адреса нет /v1. В Claude Code укажите его в ANTHROPIC_BASE_URL.","s0002": "(необязательно)","s0003": ", кеш контекста не помещается",diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.jsonindex de4f4c02c..12988d33f 100644--- a/apps/host/src/locales/zh.json+++ b/apps/host/src/locales/zh.json@@ -1,5 +1,15 @@{"s0001": "% PCIe",+ "s7301": "输入 /loop,再写多久一次,然后写要做什么。例如:/loop 10m 检查构建是否通过。加上“stop after 3 answers”可让它自动结束。用 /loop stop 停止。",+ "s7302": "请写明每次要做什么,而不只是何时停止。",+ "s7303": "循环已完成:按你的要求运行了 {0} 次。输入 /loop 可再开始一个。",+ "s7304": "循环已停止,因为上一条回答说工作已完成。输入 /loop 可再开始一个。",+ "s7305": "循环已停止,因为你设定的时间到了。输入 /loop 可再开始一个。",+ "s7306": "循环已停止,因为连续 {0} 次运行都没有成功。请检查模型,然后输入 /loop 重新开始。",+ "s7307": "第一条回答之后会自动停止。",+ "s7308": "{0} 条回答之后会自动停止。",+ "s7309": "{0} 分钟后会自动停止。",+ "s7310": "当某条回答说工作已完成时,会自动停止。","s7311": "Anthropic 类应用会自己加上 /v1/messages,所以这个地址末尾没有 /v1。在 Claude Code 中,把 ANTHROPIC_BASE_URL 设为这个地址。","s0002": "(可选)","s0003": ",上下文缓存无法容纳",diff --git a/apps/host/tests/loop-stop.test.mjs b/apps/host/tests/loop-stop.test.mjsnew file mode 100644index 000000000..0e027d863--- /dev/null+++ b/apps/host/tests/loop-stop.test.mjs@@ -0,0 +1,199 @@+// /loop stops by itself: a count or a time said in words is read when the loop is created and enforced by the scheduler, and an+// answer that says "done" / "stopped" ends it. The model is never left to keep replying "stopped" every minute.+import test from 'node:test';+import assert from 'node:assert/strict';+import { build } from 'esbuild';++const bundled = await build({ stdin: { contents: "export * from './src/lib/loop'; export * from './src/lib/loop-runner';", resolveDir: process.cwd(), loader: 'ts' }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });+const { parseLoop, readLimits, replySaysDone, judgeAnswer, withStopRule, LoopScheduler, LOOP_MAX_FAILURES, LOOP_MAX_RUNS } = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString('base64')}`);++const start = text => { const c = parseLoop(text); assert.equal(c?.kind, 'start', text); return c; };++test('a count in words or digits is read when the loop is created, and left out of the message', () => {+ for (const [line, runs, prompt] of [+ ['/loop 1m say hi, stop after 3 answers', 3, 'say hi'],+ ['/loop 1m say hi and stop after three replies', 3, 'say hi'],+ ['/loop 5m say hi. Stop the loop after 2 runs.', 2, 'say hi'],+ ['/loop 5m check the build, only 4 times', 4, 'check the build'],+ ['/loop 5m ping 3 times', 3, 'ping'],+ ['/loop every 2 minutes say hi for 5 answers', 5, 'say hi'],+ ['/loop 1m report the time, up to 6 times', 6, 'report the time'],+ ['/loop 1m say hi then stop after 1 answer', 1, 'say hi'],+ ['/loop 1m say hi, end after the 3rd run', 3, 'say hi'],+ ]) {+ const c = start(line);+ assert.equal(c.maxRuns, runs, line);+ assert.equal(c.prompt, prompt, line);+ }+});++test('a time limit and a stop condition in words are read too', () => {+ let c = start('/loop 10m check the build for the next 2 hours');+ assert.equal(c.maxMs, 2 * 3_600_000); assert.equal(c.prompt, 'check the build');+ c = start('/loop 5m check the build, stop after 30 minutes');+ assert.equal(c.maxMs, 30 * 60_000); assert.equal(c.prompt, 'check the build');+ c = start('/loop 2m check the build, stop when it passes');+ assert.equal(c.stopWhen, 'it passes'); assert.equal(c.prompt, 'check the build'); assert.equal(c.maxRuns, undefined);+ c = start('/loop 2m look for the file until it exists');+ assert.equal(c.stopWhen, 'it exists'); assert.equal(c.prompt, 'look for the file');+});++test('an ordinary message is not mistaken for a limit, and a limit with nothing to do is explained', () => {+ for (const line of ['/loop 10m summarise my inbox notes', '/loop 5m say hi', '/loop 10m check whether the build passes', '/loop 5m run the tests faster than last time']) {+ const c = start(line);+ assert.equal(c.maxRuns, undefined, line); assert.equal(c.maxMs, undefined, line); assert.equal(c.stopWhen, undefined, line);+ assert.equal(c.prompt, line.replace(/^\/loop \S+ /, ''));+ }+ assert.equal(parseLoop('/loop 5m stop after 3 answers').kind, 'help');+ assert.match(parseLoop('/loop 5m stop after 3 answers').problem, /what to do/);+ assert.equal(readLimits('say hi').prompt, 'say hi');+ assert.equal(start('/loop 5m say hi, stop after 500 answers').maxRuns, LOOP_MAX_RUNS, 'the count is capped like the loop');+});++test('a reply that says done or stopped ends the loop, a normal reply does not', () => {+ for (const reply of ['stopped', 'Stopped.', 'Done', 'DONE the build passes', 'LOOP DONE', 'The loop is stopped.']) assert.equal(replySaysDone(reply, true), true, reply);+ for (const reply of ['stopped', 'Done.', 'DONE: it passes', 'LOOP STOPPED']) assert.equal(replySaysDone(reply, false), true, reply + ' (nothing stated)');+ for (const reply of ['The build is done and the tests pass: 41 of 41.', 'Hi! Nice to see you.', 'I checked the folder and found nothing new.', '']) assert.equal(replySaysDone(reply, true), false, reply);+ // Without a stated limit only the bare words count: "Done. The deploy finished" could be a normal answer.+ assert.equal(replySaysDone('Done. The build passes.', false), false);+ assert.equal(replySaysDone('Done. The build passes.', true), true);+ assert.match(withStopRule('check the build', 'it passes'), /begin your reply with the word DONE/);+ assert.equal(withStopRule('check the build'), 'check the build');+});++test('judgeAnswer: count, time, failures and the said-done rule, in that situation order', () => {+ const p = (answers, failures = 0, startedAt = 0) => ({ answers, failures, startedAt });+ assert.equal(judgeAnswer({ maxRuns: 3 }, p(2), { text: 'hi', failed: false }, 0), null);+ assert.equal(judgeAnswer({ maxRuns: 3 }, p(3), { text: 'hi', failed: false }, 0), 'count');+ assert.equal(judgeAnswer({ maxMs: 1000 }, p(1), { text: 'hi', failed: false }, 999), null);+ assert.equal(judgeAnswer({ maxMs: 1000 }, p(1), { text: 'hi', failed: false }, 1000), 'time');+ assert.equal(judgeAnswer({}, p(1, LOOP_MAX_FAILURES - 1), { text: '', failed: true }, 0), null);+ assert.equal(judgeAnswer({}, p(1, LOOP_MAX_FAILURES), { text: '', failed: true }, 0), 'failures');+ assert.equal(judgeAnswer({}, p(1), { text: 'stopped', failed: false }, 0), 'said-done');+ assert.equal(judgeAnswer({}, p(LOOP_MAX_RUNS), { text: 'hi', failed: false }, 0), 'cap');+});++/** A scheduler on a fake clock with a scripted model. `reply(n, prompt)` is the model's n-th answer. */+function harness(reply, { ready = () => true } = {}) {+ const sent = []; const notes = []; const timers = new Map(); let t = 0, nextTimer = 1;+ const host = {+ async send(_id, message) {+ sent.push(message);+ const r = await reply(sent.length, message.text);+ return r === null ? { answered: false, text: '', failed: false } : typeof r === 'string' ? { answered: true, text: r, failed: false } : { answered: true, ...r };+ },+ note: (_id, text) => notes.push(text),+ exists: () => true,+ ready,+ now: () => t,+ setTimer: (fn, ms) => { const id = nextTimer++; timers.set(id, { fn, at: t + ms }); return id; },+ clearTimer: id => timers.delete(id),+ };+ const scheduler = new LoopScheduler(host);+ /** Move the clock to the next timer and run it; false when nothing is waiting. */+ const advance = async () => {+ const next = [...timers.entries()].sort((a, b) => a[1].at - b[1].at)[0];+ if (!next) return false;+ timers.delete(next[0]); t = Math.max(t, next[1].at); next[1].fn();+ for (let i = 0; i < 20; i++) await Promise.resolve();+ await new Promise(r => setImmediate(r));+ return true;+ };+ const drain = async (max = 400) => { let n = 0; while (n < max && await advance()) n++; return n; };+ return { scheduler, sent, notes, timers, advance, drain, clock: () => t };+}++test('"stop after 3 answers" stops the scheduler after the third answer and nothing is sent again', async () => {+ const h = harness(() => 'Hello!');+ const c = start('/loop 1m say hi, stop after 3 answers');+ await h.scheduler.start('chat', c);+ await h.drain();+ assert.equal(h.sent.length, 3);+ assert.equal(h.sent[0].text, 'say hi', 'the model is not told about the stop rule');+ assert.equal(h.timers.size, 0, 'no timer is left');+ assert.equal(h.scheduler.isRunning('chat'), false);+ assert.match(h.notes.at(-1), /The loop is done: it ran 3 times/);+ assert.equal(h.notes.filter(n => /stops by itself after 3 answers/.test(n)).length, 1, 'the start note says how it ends');+});++test('the owner case: a model that answers "stopped" every minute is cut off at once', async () => {+ // With a count in the line the scheduler stops at 3 by itself, and a "stopped" answer before that also ends it.+ const h = harness(n => (n < 2 ? 'Hi!' : 'stopped'));+ await h.scheduler.start('chat', start('/loop 1m say hi, stop after 3 answers'));+ await h.drain();+ assert.equal(h.sent.length, 2, 'the "stopped" answer ended the loop');+ assert.match(h.notes.at(-1), /last answer said the work is done/);+ // No limit in the line at all: a bare "Stopped." still ends it, instead of 100 minutes of "stopped".+ const g = harness(n => (n < 3 ? 'Still going.' : 'Stopped.'));+ await g.scheduler.start('chat', start('/loop 1m keep an eye on the queue'));+ await g.drain();+ assert.equal(g.sent.length, 3); assert.equal(g.timers.size, 0);+});++test('a stop condition in words: the model is told how to say it is met, and its DONE ends the loop', async () => {+ const h = harness(n => (n < 4 ? 'Not yet: 2 tests fail.' : 'DONE all tests pass.'));+ await h.scheduler.start('chat', start('/loop 2m run the tests, stop when they all pass'));+ await h.drain();+ assert.equal(h.sent.length, 4);+ assert.match(h.sent[0].text, /begin your reply with the word DONE/);+ assert.equal(h.sent[0].shown, 'run the tests', 'the chat shows the message without the rule');+});++test('a time limit ends the loop by the clock, between answers', async () => {+ const h = harness(() => 'ok');+ await h.scheduler.start('chat', start('/loop 10m check the queue for the next 35 minutes'));+ await h.drain();+ // answers at 0, 10, 20, 30 minutes; the timer at 40 finds the 35 minutes over+ assert.equal(h.sent.length, 4);+ assert.match(h.notes.at(-1), /time you set is up/);+ assert.equal(h.timers.size, 0);+});++test('a busy chat waits, and does not use up the count', async () => {+ let busy = true;+ const h = harness(() => 'ok', { ready: () => !busy });+ await h.scheduler.start('chat', start('/loop 1m ping, stop after 2 answers'));+ assert.equal(h.sent.length, 1);+ await h.advance(); // 1 minute: busy, retried in 15 s+ await h.advance(); await h.advance();+ assert.equal(h.sent.length, 1, 'nothing is sent while the chat is busy');+ busy = false;+ await h.drain();+ assert.equal(h.sent.length, 2);+ assert.equal(h.scheduler.isRunning('chat'), false);+});++test('three failed answers in a row end the loop, one failure does not', async () => {+ const h = harness(n => (n === 2 ? { text: '', failed: true } : 'ok'));+ await h.scheduler.start('chat', start('/loop 1m check something, stop after 4 answers'));+ await h.drain();+ assert.equal(h.sent.length, 5, 'the failed run is not an answer, so 4 good answers took 5 sends');+ const bad = harness(() => ({ text: '', failed: true }));+ await bad.scheduler.start('chat', start('/loop 1m check something'));+ await bad.drain();+ assert.equal(bad.sent.length, LOOP_MAX_FAILURES);+ assert.match(bad.notes.at(-1), /did not work/);+});++test('/loop stop while an answer is coming means nothing more is sent', async () => {+ let release;+ const h = harness(() => new Promise(resolve => { release = () => resolve('ok'); }));+ const started = h.scheduler.start('chat', start('/loop 1m ping'));+ await Promise.resolve();+ assert.equal(h.scheduler.stop('chat'), true);+ release(); await started;+ assert.equal(h.timers.size, 0);+ assert.equal(h.scheduler.isRunning('chat'), false);+ assert.equal(await h.advance(), false);+ assert.equal(h.sent.length, 1);+});++test('a second /loop in the same chat is refused with one plain sentence; a loop with no limit still runs on', async () => {+ const h = harness(() => 'ok');+ await h.scheduler.start('chat', start('/loop 1m ping'));+ assert.equal(await h.scheduler.start('chat', start('/loop 1m other')), false);+ assert.match(h.notes.at(-1), /already has a loop/);+ for (let i = 0; i < 5; i++) await h.advance();+ assert.equal(h.sent.length, 6, 'no limit: it keeps going until the person stops it');+ assert.equal(h.scheduler.stop('chat'), true);+});