Skip to content

Commit 1848b43

Browse files
rudolf-blueclaude
andcommitted
fix(core): bound /loop and show when it starts and stops
Intervals under 1m are rejected and a loop ends after 7 days. Start, stop, expiry and a failing run each post a notice in the session. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 147015b commit 1848b43

3 files changed

Lines changed: 120 additions & 18 deletions

File tree

‎packages/core/src/plugin/loop.ts‎

Lines changed: 54 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@ export * as LoopPlugin from "./loop.js"
22

33
import { define } from "@opencode/plugin/effect/plugin"
44
import type { Session } from "@opencode/schema/session"
5-
import { Duration, Effect, FiberMap, Stream } from "effect"
5+
import { Cause, Clock, Duration, Effect, FiberMap, Predicate, Stream } from "effect"
66
import { Bus } from "../bus.js"
77
import { SessionEvent } from "../session/event.js"
88

99
const usage = "Usage: /loop [interval] <prompt>, e.g. /loop 5m check the deploy"
10+
// Same bounds as Claude Code's recurring tasks: minute granularity, gone after a week.
11+
const minimum = Duration.minutes(1)
12+
const lifetime = Duration.days(7)
1013
const intervalRegex = /^\s*([1-9]\d*)([smh])(?:\s+|$)/
1114
const units = { s: 1, m: 60, h: 3600 }
1215

@@ -21,18 +24,39 @@ export function parse(text: string) {
2124
every: interval
2225
? Duration.seconds(Number(interval[1]) * units[interval[2] as keyof typeof units])
2326
: Duration.minutes(10),
27+
label: interval ? `${interval[1]}${interval[2]}` : "10m",
2428
prompt,
2529
command: command && { name: command, text: prompt.slice(command.length + 1).trim() },
2630
}
2731
}
2832

33+
function message(cause: Cause.Cause<unknown>) {
34+
const error = Cause.squash(cause)
35+
if (error instanceof Error) return error.message
36+
if (Predicate.hasProperty(error, "message") && typeof error.message === "string") return error.message
37+
return String(error)
38+
}
39+
2940
export const Plugin = define({
3041
id: "opencode.loop",
3142
effect: Effect.fn(function* (ctx) {
3243
const bus = yield* Bus.Service
3344
const loops = yield* FiberMap.make<Session.ID>()
3445
const busy = new Set<Session.ID>()
3546

47+
// Shown in the session, so a loop never starts or stops without the user seeing it.
48+
const notify = (sessionID: Session.ID, text: string) =>
49+
ctx.session
50+
.synthetic({ sessionID, text, description: text, metadata: { source: "loop" }, resume: false })
51+
.pipe(Effect.catchCause((cause) => Effect.logWarning("failed to post loop notice", { sessionID, cause })))
52+
const stop = (sessionID: Session.ID, text: string) =>
53+
Effect.gen(function* () {
54+
if (!(yield* FiberMap.has(loops, sessionID))) return false
55+
yield* FiberMap.remove(loops, sessionID)
56+
yield* notify(sessionID, text)
57+
return true
58+
})
59+
3660
yield* bus
3761
.subscribe([
3862
SessionEvent.Execution.Started,
@@ -47,7 +71,7 @@ export const Plugin = define({
4771
busy.delete(sessionID)
4872
// interrupting the session also ends its loop
4973
if (event.type === SessionEvent.Execution.Interrupted.type && event.data.reason === "user")
50-
return FiberMap.remove(loops, sessionID)
74+
return stop(sessionID, "Loop stopped because the session was interrupted.")
5175
return Effect.void
5276
}),
5377
Effect.forkScoped({ startImmediately: true }),
@@ -61,7 +85,12 @@ export const Plugin = define({
6185
Effect.gen(function* () {
6286
const parsed = parse(input.prompt.text)
6387
if (!parsed) return yield* Effect.fail(new Error(usage))
64-
if (parsed.type === "stop") return yield* FiberMap.remove(loops, input.sessionID)
88+
if (parsed.type === "stop") {
89+
if (yield* stop(input.sessionID, "Loop stopped.")) return
90+
return yield* Effect.fail(new Error("No loop is running in this session."))
91+
}
92+
if (Duration.isLessThan(parsed.every, minimum))
93+
return yield* Effect.fail(new Error("The loop interval must be at least 1m."))
6594
const step = (delivery: typeof input.delivery) =>
6695
parsed.command
6796
? ctx.session.command({
@@ -73,14 +102,29 @@ export const Plugin = define({
73102
: ctx.session
74103
.prompt({ ...input.prompt, sessionID: input.sessionID, text: parsed.prompt, delivery })
75104
.pipe(Effect.asVoid)
76-
// Ticks that land while the session is busy are skipped rather than queued.
77-
yield* Effect.suspend(() => (busy.has(input.sessionID) ? Effect.void : step("queue"))).pipe(
78-
Effect.delay(parsed.every),
79-
Effect.forever,
80-
Effect.catchCause((cause) => Effect.logError("loop stopped", { sessionID: input.sessionID, cause })),
81-
FiberMap.run(loops, input.sessionID),
105+
const run = Effect.gen(function* () {
106+
const end = (yield* Clock.currentTimeMillis) + Duration.toMillis(lifetime)
107+
while (true) {
108+
yield* Effect.sleep(parsed.every)
109+
if ((yield* Clock.currentTimeMillis) >= end)
110+
return yield* notify(input.sessionID, "Loop ended after 7 days. Run /loop again to restart it.")
111+
// Ticks that land while the session is busy are skipped rather than queued.
112+
if (!busy.has(input.sessionID)) yield* step("queue")
113+
}
114+
}).pipe(
115+
Effect.catchCauseIf(
116+
(cause) => !Cause.hasInterruptsOnly(cause),
117+
(cause) => notify(input.sessionID, `Loop stopped: ${message(cause)}`),
118+
),
119+
)
120+
yield* notify(
121+
input.sessionID,
122+
`Loop started: every ${parsed.label} for up to 7 days: ${parsed.prompt}. Run /loop stop to end it.`,
123+
)
124+
yield* FiberMap.run(loops, input.sessionID, run)
125+
yield* step(input.delivery).pipe(
126+
Effect.tapCause((cause) => stop(input.sessionID, `Loop stopped: ${message(cause)}`)),
82127
)
83-
yield* step(input.delivery).pipe(Effect.onError(() => FiberMap.remove(loops, input.sessionID)))
84128
}),
85129
})
86130
})

‎packages/core/test/plugin/loop.test.ts‎

Lines changed: 64 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ const start = Effect.fnUntraced(function* () {
2424
const command = yield* Command.Service
2525
const events = yield* PubSub.unbounded<{ type: string; data: Record<string, unknown> }>()
2626
const sent: Sent[] = []
27+
const notices: string[] = []
28+
// "flaky" works once, then fails like a command that was removed
29+
let flaky = 0
2730
yield* LoopPlugin.Plugin.effect(
2831
host({
2932
command: {
@@ -45,11 +48,19 @@ const start = Effect.fnUntraced(function* () {
4548
})
4649
}),
4750
command: (input) =>
48-
input.name === "missing"
49-
? Effect.fail(new Error("Command not found: missing"))
51+
input.name === "missing" || (input.name === "flaky" && flaky++ > 0)
52+
? Effect.fail(new Error(`Command not found: ${input.name}`))
5053
: Effect.sync(() => {
5154
sent.push({ command: input.name, text: input.text, delivery: input.delivery })
5255
}),
56+
synthetic: (input) =>
57+
Effect.sync(() => {
58+
expect(input.description).toBe(input.text)
59+
expect(input.resume).toBe(false)
60+
notices.push(input.text)
61+
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
62+
return {} as never
63+
}),
5364
},
5465
}),
5566
).pipe(
@@ -65,7 +76,7 @@ const start = Effect.fnUntraced(function* () {
6576
const emit = (type: string, data: Record<string, unknown> = {}) =>
6677
PubSub.publish(events, { type, data: { sessionID, ...data } }).pipe(Effect.andThen(settle))
6778
const wait = (duration: Duration.Input) => TestClock.adjust(duration).pipe(Effect.andThen(settle))
68-
return { loop, emit, wait, sent }
79+
return { loop, emit, wait, sent, notices }
6980
})
7081

7182
describe("LoopPlugin", () => {
@@ -90,7 +101,7 @@ describe("LoopPlugin", () => {
90101

91102
it.effect("repeats the prompt until /loop stop and skips ticks while busy", () =>
92103
Effect.gen(function* () {
93-
const { loop, emit, wait, sent } = yield* start()
104+
const { loop, emit, wait, sent, notices } = yield* start()
94105
yield* loop("5m say hi")
95106
expect(sent).toEqual([{ text: "say hi", delivery: "steer" }])
96107
yield* wait("5 minutes")
@@ -107,6 +118,11 @@ describe("LoopPlugin", () => {
107118
yield* loop("stop")
108119
yield* wait("20 minutes")
109120
expect(sent).toHaveLength(3)
121+
expect(notices).toEqual([
122+
"Loop started: every 5m for up to 7 days: say hi. Run /loop stop to end it.",
123+
"Loop stopped.",
124+
])
125+
expect(String(yield* loop("stop").pipe(Effect.exit))).toContain("No loop is running")
110126
}),
111127
)
112128

@@ -122,12 +138,16 @@ describe("LoopPlugin", () => {
122138

123139
it.effect("interrupting the session stops the loop", () =>
124140
Effect.gen(function* () {
125-
const { loop, emit, wait, sent } = yield* start()
141+
const { loop, emit, wait, sent, notices } = yield* start()
126142
yield* loop("1m say hi")
127143
yield* emit(SessionEvent.Execution.Started.type)
128144
yield* emit(SessionEvent.Execution.Interrupted.type, { reason: "user" })
129145
yield* wait("5 minutes")
130146
expect(sent).toHaveLength(1)
147+
expect(notices.at(-1)).toBe("Loop stopped because the session was interrupted.")
148+
// an interrupt with no loop running posts nothing
149+
yield* emit(SessionEvent.Execution.Interrupted.type, { reason: "user" })
150+
expect(notices).toHaveLength(2)
131151
}),
132152
)
133153

@@ -145,13 +165,51 @@ describe("LoopPlugin", () => {
145165

146166
it.effect("fails with usage for an empty prompt and drops a loop whose first run fails", () =>
147167
Effect.gen(function* () {
148-
const { loop, wait, sent } = yield* start()
168+
const { loop, wait, sent, notices } = yield* start()
149169
const empty = yield* loop("10m").pipe(Effect.exit)
150170
expect(Exit.isFailure(empty)).toBe(true)
151171
expect(String(empty)).toContain("Usage: /loop")
152172
expect(Exit.isFailure(yield* loop("1m /missing").pipe(Effect.exit))).toBe(true)
153173
yield* wait("5 minutes")
154174
expect(sent).toEqual([])
175+
expect(notices.at(-1)).toBe("Loop stopped: Command not found: missing")
176+
}),
177+
)
178+
179+
it.effect("rejects intervals under a minute", () =>
180+
Effect.gen(function* () {
181+
const { loop, sent, notices } = yield* start()
182+
const exit = yield* loop("30s say hi").pipe(Effect.exit)
183+
expect(String(exit)).toContain("at least 1m")
184+
expect(sent).toEqual([])
185+
expect(notices).toEqual([])
186+
yield* loop("60s say hi")
187+
expect(sent).toHaveLength(1)
188+
}),
189+
)
190+
191+
it.effect("ends the loop after 7 days", () =>
192+
Effect.gen(function* () {
193+
const { loop, wait, sent, notices } = yield* start()
194+
yield* loop("24h say hi")
195+
yield* wait("6 days")
196+
expect(sent).toHaveLength(7)
197+
yield* wait("1 day")
198+
expect(sent).toHaveLength(7)
199+
expect(notices.at(-1)).toBe("Loop ended after 7 days. Run /loop again to restart it.")
200+
yield* wait("3 days")
201+
expect(sent).toHaveLength(7)
202+
}),
203+
)
204+
205+
it.effect("tells the session when a later tick fails", () =>
206+
Effect.gen(function* () {
207+
const { loop, wait, sent, notices } = yield* start()
208+
yield* loop("1m /flaky")
209+
yield* wait("1 minute")
210+
yield* wait("5 minutes")
211+
expect(sent).toHaveLength(1)
212+
expect(notices.at(-1)).toBe("Loop stopped: Command not found: flaky")
155213
}),
156214
)
157215
})

‎packages/web/src/content/docs/tui.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,14 +165,14 @@ Guided setup for creating or updating `AGENTS.md`. [Learn more](/docs/rules).
165165

166166
### loop
167167

168-
Send a prompt now, then again on a fixed interval. The interval is optional and accepts `s`, `m`, or `h`; it defaults to `10m`. The prompt can also be another command.
168+
Send a prompt now, then again on a fixed interval. The interval is optional and accepts `s`, `m`, or `h`, with a minimum of `1m`; it defaults to `10m`. The prompt can also be another command.
169169

170170
```bash frame="none"
171171
/loop 5m check whether the deploy finished
172172
/loop 30m /review
173173
```
174174

175-
Ticks that land while the session is busy are skipped. Run `/loop stop` or interrupt the session to end the loop. Starting a new loop replaces the current one.
175+
Ticks that land while the session is busy are skipped. Run `/loop stop` or interrupt the session to end the loop. Starting a new loop replaces the current one. A loop ends on its own after 7 days, or when a run fails. The session shows a notice when a loop starts and when it stops.
176176

177177
---
178178

0 commit comments

Comments
 (0)