diff --git a/assets/config.default.yaml b/assets/config.default.yaml
index 8659b28..292862f 100644
--- a/assets/config.default.yaml
+++ b/assets/config.default.yaml
@@ -13,3 +13,4 @@ wake:
llm:
base_url: "" # OpenAI-compatible endpoint (V12)
model: ""
+ stream: true # set false for endpoints that break on SSE
diff --git a/docs/llm-progress/decisions.md b/docs/llm-progress/decisions.md
new file mode 100644
index 0000000..4090b68
--- /dev/null
+++ b/docs/llm-progress/decisions.md
@@ -0,0 +1,216 @@
+# `llm-progress` — decisions this Matter made
+
+This file records the calls that adding a progress line to `retro`, `wake`, and
+`brief` forced. The wip Matter `llm-progress` set the intent. It left the
+details below to the Builder, or it required that this file record them.
+
+Status: Steps 01-05 are done. Step 06 records this file and the smoke check. The three verbs show a one-line
+status on stderr while they wait on the LLM. The line shows only on a terminal.
+The e2e suite needed no output changes. Two defaults are not confirmed by Beau
+yet. The first section lists them.
+
+## Two defaults wait for Beau
+
+Beau confirmed two calls on 2026-10-02 (the standard-library TTY check, and
+wake interactive phases only). The workplan set the rest at planning time, and
+the executor and verifier made the implementation calls. Beau has not confirmed
+these two:
+
+- `brief` shows phases only. It does not stream the brief text to stdout.
+- No progress shows when stderr is not a terminal, even with `--verbose`.
+
+The code follows both defaults. The `--verbose` rule is a small edit to change.
+Streaming the brief text to stdout is not. It is a real feature, which touches
+stdout against stderr, `--json`, and the order of `Clear` against the output.
+The workplan put it out of scope.
+
+## The reporter lives in `internal/progress`, behind a context
+
+`progress.New(streams, flags)` returns a `*Reporter`. `WithReporter` and
+`FromContext` carry it in the `context.Context`. `Summarize`, `RunAuto`,
+`RunInteractive`, and `Synthesize` keep their signatures, so no caller and no
+test needed an edit.
+
+Every method of `*Reporter` is safe on a nil receiver. `New` returns nil when
+progress is off. It also returns nil for nil streams or a nil `streams.Err`. A
+verb never checks for nil. This is also why no unit test or
+e2e test sees the reporter (see the test gap below).
+
+`llm-progress` waited only for `llm-streaming/step-01`. That Step added the
+observer seam. The phase events come from there. `Reporter.Observer()` returns
+an `llm.Observer` that only updates state under a mutex, as the `llm-streaming`
+brief requires.
+
+## The terminal check uses the standard library
+
+`New` returns a reporter only when `streams.Err` is an `*os.File` whose `Stat()`
+mode has `os.ModeCharDevice`. `TERM=dumb` also turns progress off. Beau chose
+the standard-library check on 2026-10-02. The repo takes no `golang.org/x/term`
+dependency for this.
+
+Observation, not a Beau decision: a character device is not always a terminal.
+`/dev/null` is one, so `2>/dev/null` turns the reporter on. It then writes
+harmlessly to `/dev/null`. A fix for the width limit below would need `x/term`
+or a `TIOCGWINSZ` call, so this call can come back.
+
+## No progress with `--json`, or without a terminal, even with `--verbose`
+
+`New` returns nil when `--json` is set. It also returns nil when stderr is not a
+terminal. `--verbose` does not override either rule. The e2e tests run the
+binary with stderr in a `bytes.Buffer`, so the reporter is off there. Their
+expected output did not change.
+
+The no-terminal rule with `--verbose` is one of the two unconfirmed defaults.
+A user who pipes stderr to a file and passes `--verbose` gets no status lines.
+
+## One line, redrawn in place
+
+The line is ` · · `. The frame is a braille
+spinner. The line starts with `\r\x1b[K` and has no newline.
+
+`Status` draws one frame at once, under the mutex. A short wait still shows a
+line. A goroutine redraws the line every 100 ms. It starts on the first
+`Status` and runs until `Stop`. `Clear` only stops the drawing. It does not end
+the goroutine, so a verb can alternate `Status` and `Clear` with no goroutine
+churn. Because of this, every verb that builds a reporter must `defer Stop`.
+
+`Stop` closes the quit channel once. It waits for the goroutine outside the
+mutex, and it does not wait when the goroutine never started. `Status` resets
+the phase and the delta count on every call, even when the label is the same.
+The reporter ignores an unknown `llm.Phase`.
+
+## A verb clears the line before it prints anything
+
+Each verb calls `Clear` before any output on the same stream and before any
+error return. The cleared line is `\r\x1b[K`. The next write then starts on a
+clean row. A first pty probe of `wake` showed that removing `Clear` puts the
+diagnostic on the status line, so the `Clear` is load-bearing.
+
+## Phase text, and the Delta count
+
+The phase shows after the label. `thinking` shows for reasoning deltas. The
+phase `receiving` shows a character count (`receiving · 1985 chars`) once Delta
+events arrive. A JSON reply, and any call before `llm-streaming/step-03`, shows
+`receiving` without a count. `connecting` and `connected` last less than one
+100 ms tick against a fast host, so they rarely show.
+
+## The width comes from `COLUMNS`
+
+`draw` reads `COLUMNS` on every draw. A value below 2, or one that is not a
+number, falls back to 80. The line is cut to `width-1` runes, frame included.
+
+This is a known risk (see the follow-ups). Most shells do not export `COLUMNS`
+to child processes, so the width is usually 80. On a narrower terminal, the line
+wraps.
+
+## retro shows a counter only
+
+`retro` shows `summarizing N/M`, with ` · K cached` added only when K is above
+zero. It shows no phases. Four workers run at once, so one phase line would
+flip between unrelated calls.
+
+The label comes from the unexported `statusLabel`. `Summarize` calls
+`defer rep.Clear()` right after it reads the reporter. Every return path, the
+first-error cancel included, clears the line before `RunE` prints. A failed job
+calls no `Status`. Jobs that are in flight and succeed after a failure still
+update the counter.
+
+`defer rep.Stop()` is inside the `HasEntries` block in `command.go`. It runs
+when `RunE` returns. This is harmless. `Summarize` has already cleared the line.
+
+## wake --auto shows the project and the call phases
+
+`wake --auto` shows `drafting N/M · ` and the call phases. The command
+builds the reporter after `llm.NewClient`, `Hostname`, and `ParseDay`, just
+before the auto or interactive branch. An empty working set returns earlier, so
+it never creates a reporter.
+
+`RunAuto` attaches `rep.Observer()` to the context of `Draft` only. It calls
+`Clear` right after `Draft` returns, before the error branch. The elapsed time
+restarts for each session. The command also stores the reporter in the context
+with `WithReporter`, which `RunInteractive` reads.
+
+## wake interactive shows phases only
+
+Beau chose this on 2026-10-02. `RunInteractive` shows `drafting · `
+with no N/M. The `== Session i/n ==` header already carries the count. The full
+draft still prints with the menu, as before. The draft text is not streamed.
+
+The Edit case of `disposition` shows `redrafting · `. It computes the
+label after the feedback-EOF return, so that path draws nothing. `Clear` runs
+right after each `Draft` or `DraftWithFeedback`, before the failure diagnostic
+and before the menu reprint. The draft and the menu reprint are byte-identical
+with and without a live reporter. A test covers success and a failed redraft.
+
+## brief shows phases only
+
+`brief` shows `synthesizing brief · ` and the call phases. The command
+builds the reporter after the empty-brief return and after `llm.NewClient`, so
+an empty brief or a bad config never creates one. It calls `Clear` before the
+error return and before the JSON or human output. The brief text goes to stdout
+as before.
+
+This is the other unconfirmed default (see the first section).
+
+## Verification came from pty probes, not from tests
+
+The reporter is nil in every unit test and e2e test, and `progress` has no
+writer seam. Probes with `script` on a stub, and the smoke check below on the
+live endpoint, are the only evidence for the verb wiring.
+
+Step 4 shows why this matters. The first pass reported an edit to `disposition`
+that never applied. A scripted string replace failed on indentation, and no test
+noticed. The verifier caught it from the diff and from a pty probe. Executors
+now confirm each edit with `git diff` and `grep` output.
+
+## Pty smoke check against the live endpoint
+
+On 2026-10-02, with `CLAST_LLM_API_KEY` set and `llm.base_url` from the user
+config, `script -qec '' /dev/null | cat -v` ran both commands. The cache
+was in a scratch `XDG_CACHE_HOME`.
+
+- `retro --since -7d --refresh` drew `\r\x1b[K` frames of `summarizing 0/30 · 0s`
+ up to `summarizing 30/30 · 26s`. The last write was a bare `\r\x1b[K`, and the
+ `# Retro:` heading started on that row. No residue.
+- `brief` drew `synthesizing brief · clast · 0s`, then
+ `... · receiving · 1985 chars · 0s`, then a bare `\r\x1b[K`, then the brief.
+ No `thinking` showed. The brief call's stream had no reasoning deltas: 0
+ Thinking events, about 0.1 s in all, the same bytes on each run, consistent
+ with a cached reply. A fresh prompt on the same endpoint streams reasoning, and
+ the reporter draws `thinking`.
+- `bin/clast brief 2>err.txt` wrote no bytes to `err.txt`. It has no `\x1b[K`.
+- At 40 columns the `brief` line (about 58 characters) wraps. `\r\x1b[K` erases
+ only the second row. The first row, `⠙ synthesizing brief · clast · receiving`,
+ stays on screen above the brief. This confirms the width risk. The verifier
+ reproduced the residue with the `pyte` terminal emulator on live bytes. With
+ `COLUMNS=40` exported, the frame is cut to 39 runes and leaves no residue.
+- The retro time varies with endpoint caching: 26 s in one run, 1.6 s in the
+ verifier's run.
+
+## Follow-ups outside this Matter
+
+- Narrow terminals. `COLUMNS` is usually not exported, so the width is 80. On a
+ terminal narrower than 80, a long line wraps and the clear leaves the first
+ row on screen (the 40-column smoke run shows it). A real fix needs the window
+ size from `x/term` or a `TIOCGWINSZ` call. Beau has this question.
+- Test gap. No unit test and no e2e test fails when the verb wiring is removed
+ (`Status`, `Clear`, or the observer). A possible fix is an exported test seam
+ in `internal/progress`, for example a context-injected writer, so verb tests
+ can assert that `Clear` comes before the next write. Three smaller gaps remain.
+ No test covers a non-terminal `*os.File` stderr (a regular file or a pipe). No
+ test checks that `Stop` waits for the goroutine. No in-package test covers
+ `statusLabel`.
+- Mutex held during the write. The draw loop holds the reporter mutex while it
+ writes to the terminal. The observer needs the same mutex, and observer time
+ counts toward `IdleTimeout`. A terminal that blocks for longer than 30s would
+ stall the call and trip `IdleTimeout`. Any fix must keep the write
+ order. A frame built before `Clear` must not reach the terminal after the
+ erase of `Clear`, or a status line stays under the next verb output. Two
+ options: a separate write mutex plus a generation check, or an observer that
+ updates the phase through its own lock or atomics, so it never waits on
+ terminal I/O.
+- Doubled verb prefix. Error lines repeat the verb, for example
+ `clast: brief: brief: synthesizing ...` and `clast: retro: retro: ...`. The
+ `clasterr` messages already start with the verb, and `Execute` adds it again.
+ This predates this Matter. It is not fixed here.
+- The two unconfirmed defaults in the first section.
diff --git a/docs/llm-streaming/decisions.md b/docs/llm-streaming/decisions.md
new file mode 100644
index 0000000..e3ba433
--- /dev/null
+++ b/docs/llm-streaming/decisions.md
@@ -0,0 +1,158 @@
+# `llm-streaming` — decisions this Matter made
+
+This file records the calls that adding SSE streaming and call-lifecycle events
+to `internal/llm` forced. The wip Matter `llm-streaming` set the intent. It left
+the details below to the Builder, or it required that this file record them.
+
+Status: all five Steps are locally complete. `Complete` streams by default and
+reports its phases to an optional observer. The Matter `llm-progress` reads the
+brief and builds the progress output on this seam.
+
+## The event seam lands first and travels in the context
+
+Step 1 added the observer before any SSE parsing. `llm-progress` waits only for
+this Step. Progress output can ship before the SSE parser does.
+
+`WithObserver(ctx, o)` stores an `Observer` in the context. `Complete` reads it
+from there. The `Complete` signature did not change, so the three verbs compile
+without edits. `WithObserver(ctx, nil)` returns the same context.
+
+`Complete` wraps the observer once with `serialize`, a per-call mutex. Every
+emit, `PhaseStart` and `PhaseDone` included, goes through it. Callbacks for one
+call never overlap, because `httptrace` callbacks can run on transport
+goroutines. An observer shared across concurrent calls must lock itself. No
+test covers the mutex. Review checks it.
+
+## The phase order is a contract
+
+`PhaseStart` comes first. `PhaseDone` comes last and only on success. An error
+ends the call with no `PhaseDone`. `PhaseFirstByte` comes before any
+`PhaseThinking` or `PhaseDelta`. `PhaseConnected` may repeat.
+
+`PhaseRequestSent` is not promised. When the server answers before it reads the
+whole request body, `WroteRequest` reports an error and the phase is skipped.
+The call can still succeed. A consumer must not wait for it.
+
+`PhaseDone` is emitted after the empty-choices check on the JSON path. A reply
+with no choices is a failure and emits no `PhaseDone`.
+
+## Streaming is on by default
+
+The request carries `"stream": true` unless `llm.stream` is `false`. Beau chose
+this on 2026-10-02. Streaming is what makes progress output possible, and the
+opt-out keeps an unusual endpoint usable.
+
+`llm.stream` is a new key under `llm:`, beside `base_url` and `model`. A value that is not a bool gives a plain
+error that names `llm.stream`. The error comes before the API key check.
+`ConfiguredModel` does not read the key.
+
+## A JSON reply falls back by Content-Type
+
+`Complete` chooses the reader from the reply `Content-Type`, not from what it
+asked for. `text/event-stream` (any parameters) on a 2xx reply takes the SSE
+reader. Anything else takes the JSON reader. A server that ignores
+`stream: true` therefore works. A non-2xx reply always takes the JSON reader, so
+its status and body appear in the error as before.
+
+## A clean EOF without `[DONE]` is success
+
+The SSE reader ends at `data: [DONE]` or at a clean end of the connection. Some
+proxies close the connection without `[DONE]`. The reader treats that as
+success, and it flushes an unterminated final event at EOF.
+
+The reader stops reading as soon as it sees `[DONE]`. A first version read one
+more line. A server that held the connection open made `Complete` wait, and the
+idle timeout would have reported it as stalled. A regression test pins the fix.
+
+An error event (`error.message` at the top level) ends the stream. The reader
+drops the content it collected and returns the message.
+
+## Reasoning deltas are reported, not returned
+
+The reader takes `choices[0].delta.content`, `reasoning_content`, and
+`reasoning`. Content becomes `PhaseDelta` and joins the reply. Reasoning becomes
+`PhaseThinking` and never joins the reply.
+
+`reasoning_content` wins over `reasoning`. One event gives one `PhaseThinking`.
+Empty strings emit nothing. The live endpoint (LiteLLM with a vllm Qwen
+reasoning model) sends many `reasoning_content` events before any content. Without
+`PhaseThinking`, the progress output would be silent through the whole think.
+
+The parser ignores the rest of the event. The parser does not handle bare CR line
+ends or a lone `data` line, which the SSE spec allows. The live endpoint does not
+use them.
+
+## A stream with no content returns an empty reply
+
+A stream that ends with no content returns `""` and no error. The JSON path
+does the same for empty or null content, and it errors only when `choices` is
+empty. A reasoning model that spends its whole budget on reasoning gets `""` on
+both paths. Both paths stay consistent. The verbs treat an empty reply as they did before
+on the JSON path. Retro caches it.
+
+## Three limits replace the one whole-request timeout
+
+`DefaultTimeout` and `http.Client.Timeout` are gone. A whole-request timeout cuts
+a long stream in the middle of the body.
+
+| Constant | Value | Limit | Error text |
+| --- | --- | --- | --- |
+| `FirstByteTimeout` | 30s | request sent to response headers | `timeout awaiting response headers`, wrapped in `llm: calling ` |
+| `IdleTimeout` | 30s | silence between two body reads | `llm: stalled: no data for 30s` |
+| `MaxDuration` | 5m | whole call, connect to last byte | `llm: exceeded 5m0s` |
+
+The first-byte limit is `ResponseHeaderTimeout` on the transport. The idle
+limit is a timer that starts after the headers arrive. Each body read that
+returns data resets it. It covers both the SSE and the JSON path. The total
+limit is a context deadline on the whole call.
+
+A cancel of the parent context passes the parent's error through (wrapped),
+so `errors.Is(err, context.Canceled)` holds. `classify` relabels an error only when
+it is a cancellation-shaped error and the parent is still live. A malformed
+event that arrives just after a timer fires keeps its own error.
+
+## Observer time counts toward the idle limit
+
+The observer runs inside the read loop. A slow observer delays the next read
+and can trip `IdleTimeout` on a healthy stream. The `Complete` doc comment says
+so. `llm-progress`'s observer only updates state under a mutex. The draw loop
+holds that mutex while it writes to the terminal, so a terminal blocked for
+longer than `IdleTimeout` would stall the call.
+
+## Each client owns its transport
+
+Each `NewClient` clones `http.DefaultTransport` so it can set
+`ResponseHeaderTimeout`. Each clone has its own keep-alive pool. This is
+harmless today, because each verb calls `NewClient` once. Share one transport if
+that changes. `SetTimeouts` in `export_test.go` rebuilds the client for tests.
+
+## The test stub gained stream modes and delays
+
+`llmtest` can answer with SSE (`SetStream`), with raw SSE bytes
+(`SetStreamRaw`), and with delays (`SetDelay`). The default behavior is
+byte-identical to before. The stub cannot send `text/event-stream; charset=utf-8`
+or SSE with a non-2xx status. The tests that need those use a local
+`httptest.NewServer`.
+
+`TestTimeout_LongStreamNotCut` uses a total limit of 5s, not 1s. The total limit
+also covers the dial, and one loopback stall of about 1s on the WSL2 development
+machine failed a 1s version. The test still proves that the first-byte and idle
+limits do not cut a long stream.
+
+## A rare 1s stall is a known flake source
+
+In about 1,100 stress runs, the verifier saw one unexplained failure and a few
+stalls of about 1.03s. 900 targeted runs gave no failure. The likely cause is a
+SYN retransmit on WSL2 loopback. It is not proven. A test with a tight time
+bound can flake for this reason.
+
+## Follow-ups outside this Matter
+
+- SURFACE V12 needs an amendment for streaming. It belongs in `clast-reboot`.
+ That step is Beau's. This repo does not hold it.
+- `assets/config.default.yaml` still says "SURFACE V31 — five knobs". `llm.stream`
+ adds a key that V31 does not list. This is a SURFACE matter, so this Matter left the file alone.
+- Retro caches an empty summary. A reasoning model that spends its whole budget
+ on reasoning leaves an empty cached summary for that session. This behavior
+ predates this Matter.
+- `README.md` does not document the `llm:` keys, so it did not change.
diff --git a/internal/llm/export_test.go b/internal/llm/export_test.go
new file mode 100644
index 0000000..6bc3c63
--- /dev/null
+++ b/internal/llm/export_test.go
@@ -0,0 +1,10 @@
+package llm
+
+import "time"
+
+// SetTimeouts overrides the first-byte, idle and total limits so tests
+// need not wait out the 30s and 5m production values.
+func SetTimeouts(c *Client, firstByte, idle, total time.Duration) {
+ c.firstByte, c.idle, c.max = firstByte, idle, total
+ c.buildHTTP()
+}
diff --git a/internal/llm/llm.go b/internal/llm/llm.go
index 9e8b114..e2f9c51 100644
--- a/internal/llm/llm.go
+++ b/internal/llm/llm.go
@@ -2,17 +2,22 @@
// wake/brief/retro verb forms speak to the configured LLM endpoint
// (SURFACE V12): one call shape — a system/user prompt pair in, the
// assistant's reply text out. No provider abstraction (V12 rejected a
-// second provider until one actually exists), no streaming, no retries,
-// no options struct beyond what the three verbs need.
+// second provider until one actually exists), no retries, no options
+// struct beyond what the three verbs need. By default the reply is read as
+// server-sent events (SSE) with a JSON fallback, and a context Observer
+// (WithObserver) reports the call's phases to a verb.
package llm
import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
+ "mime"
"net/http"
+ "net/http/httptrace"
"os"
"strings"
"time"
@@ -28,13 +33,23 @@ const APIKeyEnvVar = "CLAST_LLM_API_KEY"
// configKey is the tool-config section V31 carries the endpoint under.
const configKey = "llm"
-// DefaultTimeout bounds one Complete call end-to-end (connect through
-// response body fully read). 30s: generous enough for a real completion
-// (retro's summaries and wake's drafts are short generations, not
-// long-form), short enough that a verb never hangs a terminal
-// indefinitely on a stalled endpoint. Recorded as a wip finding per the
-// step brief — no SURFACE clause fixes this number.
-const DefaultTimeout = 30 * time.Second
+// FirstByteTimeout bounds the wait from sending the request to receiving
+// the response headers. 30s: a model may think a while before it answers,
+// but an endpoint silent for this long is down or unreachable.
+const FirstByteTimeout = 30 * time.Second
+
+// IdleTimeout bounds the silence between two reads of the response body.
+// A long stream is never cut while data keeps arriving; a stream that goes
+// quiet for this long fails as stalled.
+const IdleTimeout = 30 * time.Second
+
+// MaxDuration bounds one Complete call end-to-end (connect through
+// response body fully read), a backstop against a stream that trickles
+// forever.
+const MaxDuration = 5 * time.Minute
+
+// errStalled is the per-call cancel cause the idle timer sets.
+var errStalled = errors.New("stalled")
// chatCompletionsPath is the one endpoint path V12 names, joined onto
// llm.base_url.
@@ -47,7 +62,12 @@ type Client struct {
baseURL string
model string
apiKey string
+ stream bool
http *http.Client
+
+ firstByte time.Duration
+ idle time.Duration
+ max time.Duration
}
// NewClient resolves llm.base_url and llm.model from cfg (SURFACE V31)
@@ -83,20 +103,57 @@ func NewClient(cfg config.Config) (*Client, error) {
fmt.Sprintf("llm endpoint not configured: set %s in config.yaml", strings.Join(missing, " and ")))
}
+ stream, err := streamEnabled(cfg)
+ if err != nil {
+ return nil, err
+ }
+
apiKey := os.Getenv(APIKeyEnvVar)
if apiKey == "" {
return nil, clasterr.New("validation.llm-api-key-missing",
fmt.Sprintf("%s is not set", APIKeyEnvVar))
}
- return &Client{
- baseURL: strings.TrimSuffix(baseURL, "/"),
- model: model,
- apiKey: apiKey,
- http: &http.Client{Timeout: DefaultTimeout},
- }, nil
+ c := &Client{
+ baseURL: strings.TrimSuffix(baseURL, "/"),
+ model: model,
+ apiKey: apiKey,
+ stream: stream,
+ firstByte: FirstByteTimeout,
+ idle: IdleTimeout,
+ max: MaxDuration,
+ }
+ c.buildHTTP()
+ return c, nil
+}
+
+// buildHTTP (re)creates the http client with a transport whose
+// ResponseHeaderTimeout is the first-byte limit. There is no
+// http.Client.Timeout: it would cut a long stream mid-body.
+func (c *Client) buildHTTP() {
+ tr := http.DefaultTransport.(*http.Transport).Clone()
+ tr.ResponseHeaderTimeout = c.firstByte
+ c.http = &http.Client{Transport: tr}
}
+// idleReader wraps a response body and resets timer on every Read that
+// returns data.
+type idleReader struct {
+ rc io.ReadCloser
+ timer *time.Timer
+ idle time.Duration
+}
+
+func (r *idleReader) Read(p []byte) (int, error) {
+ n, err := r.rc.Read(p)
+ if n > 0 {
+ r.timer.Reset(r.idle)
+ }
+ return n, err
+}
+
+func (r *idleReader) Close() error { return r.rc.Close() }
+
// Model returns the resolved llm.model this Client was constructed with
// (SURFACE V31) — exported for a caller that needs the model string itself
// as a fact, not just to send it (llm-verbs seal sweep, F5: retro's cache
@@ -125,30 +182,53 @@ func ConfiguredModel(cfg config.Config) (string, error) {
// yaml.v3-decode-shape handling (nested mappings decode as either
// map[string]any or config.Config depending on caller, both accepted).
func llmConfigValues(cfg config.Config) (baseURL, model string, err error) {
+ section, err := llmSection(cfg)
+ if err != nil || section == nil {
+ return "", "", err
+ }
+ baseURL, err = stringField(section, "base_url")
+ if err != nil {
+ return "", "", err
+ }
+ model, err = stringField(section, "model")
+ if err != nil {
+ return "", "", err
+ }
+ return baseURL, model, nil
+}
+
+// llmSection returns cfg's "llm" mapping, nil when absent.
+func llmSection(cfg config.Config) (map[string]any, error) {
raw, present := cfg[configKey]
if !present || raw == nil {
- return "", "", nil
+ return nil, nil
}
-
- var section map[string]any
switch m := raw.(type) {
case map[string]any:
- section = m
+ return m, nil
case config.Config:
- section = m
+ return m, nil
default:
- return "", "", fmt.Errorf("llm: config key %q must be a mapping, got %T", configKey, raw)
+ return nil, fmt.Errorf("llm: config key %q must be a mapping, got %T", configKey, raw)
}
+}
- baseURL, err = stringField(section, "base_url")
- if err != nil {
- return "", "", err
+// streamEnabled reads llm.stream: absent or null means true (send
+// "stream": true and read SSE); a non-bool is a plain error.
+func streamEnabled(cfg config.Config) (bool, error) {
+ section, err := llmSection(cfg)
+ if err != nil || section == nil {
+ return true, err
}
- model, err = stringField(section, "model")
- if err != nil {
- return "", "", err
+ v, present := section["stream"]
+ if !present || v == nil {
+ return true, nil
}
- return baseURL, model, nil
+ b, ok := v.(bool)
+ if !ok {
+ return false, fmt.Errorf("llm: config key %q must be a bool, got %T", configKey+".stream", v)
+ }
+ return b, nil
}
func stringField(section map[string]any, key string) (string, error) {
@@ -175,6 +255,7 @@ type message struct {
type chatRequest struct {
Model string `json:"model"`
Messages []message `json:"messages"`
+ Stream bool `json:"stream,omitempty"`
}
// chatResponse is the slice of the OpenAI-compatible response this
@@ -195,15 +276,63 @@ type chatResponse struct {
// naming the endpoint and, for non-2xx, the status and response body —
// enough for a verb to report a clear failure without this package
// guessing at a clasterr code a later verb Matter hasn't chosen yet.
+//
+// By default the request carries "stream": true and a text/event-stream
+// reply is read as SSE (see readStream); an endpoint that answers with
+// plain JSON anyway, or llm.stream: false, takes the JSON path.
+//
+// Three limits apply instead of one whole-request timeout: FirstByteTimeout
+// (request sent to headers), IdleTimeout (silence between body reads) and
+// MaxDuration (the whole call). A parent context cancel passes the
+// parent's error through (wrapped), so errors.Is(err, context.Canceled) holds.
+//
+// An Observer runs inside the read loop, so the time it takes counts
+// toward IdleTimeout: a slow Observer can make a healthy stream stall.
func (c *Client) Complete(ctx context.Context, systemPrompt, userPrompt string) (string, error) {
+ parent := ctx
+ var emit Observer
+ if o := observerFrom(ctx); o != nil {
+ emit = serialize(o)
+ emit(Event{Phase: PhaseStart})
+ ctx = httptrace.WithClientTrace(ctx, traceFor(emit))
+ }
+
endpoint := c.baseURL + chatCompletionsPath
+ totalCtx, cancelTotal := context.WithTimeout(ctx, c.max)
+ defer cancelTotal()
+ callCtx, cancel := context.WithCancelCause(totalCtx)
+ defer cancel(nil)
+ ctx = callCtx
+
+ // classify maps a failure to the idle or total-cap error when that
+ // limit ended the call; a parent cancel and every other error pass
+ // through (nil return). Only a cancellation-shaped err qualifies, so a
+ // malformed-stream error is never relabeled because a timer fired just
+ // after it.
+ classify := func(err error) error {
+ if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, errStalled) {
+ return nil
+ }
+ if parent.Err() != nil {
+ return nil
+ }
+ if errors.Is(context.Cause(callCtx), errStalled) {
+ return fmt.Errorf("llm: %s stalled: no data for %s", endpoint, c.idle)
+ }
+ if totalCtx.Err() != nil {
+ return fmt.Errorf("llm: %s exceeded %s", endpoint, c.max)
+ }
+ return nil
+ }
+
reqBody, err := json.Marshal(chatRequest{
Model: c.model,
Messages: []message{
{Role: "system", Content: systemPrompt},
{Role: "user", Content: userPrompt},
},
+ Stream: c.stream,
})
if err != nil {
return "", fmt.Errorf("llm: encoding request to %s: %w", endpoint, err)
@@ -218,16 +347,45 @@ func (c *Client) Complete(ctx context.Context, systemPrompt, userPrompt string)
resp, err := c.http.Do(req)
if err != nil {
+ if cerr := classify(err); cerr != nil {
+ return "", cerr
+ }
return "", fmt.Errorf("llm: calling %s: %w", endpoint, err)
}
defer func() { _ = resp.Body.Close() }()
- respBody, err := io.ReadAll(resp.Body)
+ // The idle timer starts once the headers are in, and every Read that
+ // returns data resets it. Stopped on every return path.
+ idleTimer := time.AfterFunc(c.idle, func() { cancel(errStalled) })
+ defer idleTimer.Stop()
+ body := &idleReader{rc: resp.Body, timer: idleTimer, idle: c.idle}
+
+ ok2xx := resp.StatusCode >= 200 && resp.StatusCode < 300
+ if ok2xx {
+ if mt, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")); err == nil && mt == "text/event-stream" {
+ content, err := readStream(body, endpoint, emit)
+ if err != nil {
+ if cerr := classify(err); cerr != nil {
+ return "", cerr
+ }
+ return "", err
+ }
+ if emit != nil {
+ emit(Event{Phase: PhaseDone})
+ }
+ return content, nil
+ }
+ }
+
+ respBody, err := io.ReadAll(body)
if err != nil {
+ if cerr := classify(err); cerr != nil {
+ return "", cerr
+ }
return "", fmt.Errorf("llm: reading response from %s: %w", endpoint, err)
}
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ if !ok2xx {
return "", fmt.Errorf("llm: %s returned %s: %s", endpoint, resp.Status, strings.TrimSpace(string(respBody)))
}
@@ -239,5 +397,8 @@ func (c *Client) Complete(ctx context.Context, systemPrompt, userPrompt string)
return "", fmt.Errorf("llm: %s returned no choices", endpoint)
}
+ if emit != nil {
+ emit(Event{Phase: PhaseDone})
+ }
return parsed.Choices[0].Message.Content, nil
}
diff --git a/internal/llm/llmtest/llmtest.go b/internal/llm/llmtest/llmtest.go
index 55302e3..9e895fb 100644
--- a/internal/llm/llmtest/llmtest.go
+++ b/internal/llm/llmtest/llmtest.go
@@ -16,8 +16,10 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "strings"
"sync"
"testing"
+ "time"
)
// Message is one OpenAI chat-format message, as sent or received over the
@@ -38,6 +40,10 @@ type CapturedRequest struct {
Model string
Messages []Message
Authorization string
+
+ // Stream is the request's "stream" field: whether the client asked
+ // for an SSE reply.
+ Stream bool
}
// Server is a running OpenAI-compatible /chat/completions stub. Point a
@@ -59,6 +65,21 @@ type Server struct {
rawSet bool
rawStatus int
rawBody string
+
+ // streamChunks, when streamSet, is answered to a stream:true request
+ // as one SSE content delta per chunk, then [DONE].
+ streamSet bool
+ streamChunks []string
+
+ // streamLines, when streamRawSet, is answered to a stream:true
+ // request verbatim, one line each.
+ streamRawSet bool
+ streamLines []string
+
+ // delayFirst is slept before the response headers; delayBetween is
+ // slept between SSE writes.
+ delayFirst time.Duration
+ delayBetween time.Duration
}
// New starts a stub that answers every /chat/completions request with a
@@ -84,6 +105,59 @@ func (s *Server) SetResponse(content string) {
defer s.mu.Unlock()
s.canned = content
s.rawSet = false
+ s.clearStreamLocked()
+}
+
+// clearStreamLocked drops any stream mode. The caller holds s.mu.
+func (s *Server) clearStreamLocked() {
+ s.streamSet = false
+ s.streamChunks = nil
+ s.streamRawSet = false
+ s.streamLines = nil
+}
+
+// SetStream makes the stub answer a request with "stream": true as SSE:
+// one content delta per chunk, each flushed, then "data: [DONE]". A
+// request without stream:true gets the normal JSON reply with the chunks
+// joined. It replaces any earlier stream mode and any Fail/RespondRaw
+// override. With no SetStream or SetStreamRaw call, a stream:true request
+// still gets plain JSON (a server that ignores stream).
+func (s *Server) SetStream(chunks []string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.clearStreamLocked()
+ s.rawSet = false
+ s.streamSet = true
+ s.streamChunks = append([]string(nil), chunks...)
+}
+
+// SetStreamRaw makes the stub answer a request with "stream": true with
+// Content-Type text/event-stream and each line written verbatim plus a
+// newline, flushed after each. The caller supplies the blank lines that
+// end events. Use it for keepalive comments, error
+// events, reasoning deltas, or a missing [DONE]. A request without
+// stream:true gets the normal canned JSON reply. It replaces any earlier
+// stream mode and any Fail/RespondRaw override.
+func (s *Server) SetStreamRaw(lines []string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.clearStreamLocked()
+ s.rawSet = false
+ s.streamRawSet = true
+ s.streamLines = append([]string(nil), lines...)
+}
+
+// SetDelay makes the stub sleep beforeFirstByte before it writes the
+// response headers, and betweenChunks between SSE writes. betweenChunks
+// applies between every raw line, blank lines included. beforeFirstByte
+// applies to JSON and Fail/RespondRaw replies too, not only SSE. Both stop
+// early when the client goes away. SetResponse, Fail and RespondRaw do not
+// clear the delays.
+func (s *Server) SetDelay(beforeFirstByte, betweenChunks time.Duration) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.delayFirst = beforeFirstByte
+ s.delayBetween = betweenChunks
}
// Fail switches the stub to answer every subsequent request with
@@ -101,6 +175,7 @@ func (s *Server) RespondRaw(statusCode int, body string) {
s.mu.Lock()
defer s.mu.Unlock()
s.rawSet = true
+ s.clearStreamLocked()
s.rawStatus = statusCode
s.rawBody = body
}
@@ -119,6 +194,7 @@ func (s *Server) Requests() []CapturedRequest {
type wireRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
+ Stream bool `json:"stream"`
}
// wireChoice/wireResponse mirror the response shape internal/llm.Client
@@ -153,9 +229,13 @@ func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
Model: req.Model,
Messages: req.Messages,
Authorization: r.Header.Get("Authorization"),
+ Stream: req.Stream,
})
rawSet, rawStatus, rawBody := s.rawSet, s.rawStatus, s.rawBody
canned := s.canned
+ streamSet, streamChunks := s.streamSet, s.streamChunks
+ streamRawSet, streamLines := s.streamRawSet, s.streamLines
+ delayFirst, delayBetween := s.delayFirst, s.delayBetween
s.mu.Unlock()
if r.URL.Path != "/chat/completions" {
@@ -163,13 +243,63 @@ func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
return
}
+ if !sleepCtx(r, delayFirst) {
+ return
+ }
+
+ if req.Stream && (streamSet || streamRawSet) {
+ var lines []string
+ if streamSet {
+ for _, c := range streamChunks {
+ quoted, _ := json.Marshal(c)
+ lines = append(lines, `data: {"choices":[{"delta":{"content":`+string(quoted)+`}}]}`+"\n")
+ }
+ lines = append(lines, "data: [DONE]\n")
+ } else {
+ lines = streamLines
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ flusher, _ := w.(http.Flusher)
+ for i, line := range lines {
+ if i > 0 && !sleepCtx(r, delayBetween) {
+ return
+ }
+ if _, err := io.WriteString(w, line+"\n"); err != nil {
+ return
+ }
+ if flusher != nil {
+ flusher.Flush()
+ }
+ }
+ return
+ }
+
if rawSet {
w.WriteHeader(rawStatus)
_, _ = w.Write([]byte(rawBody))
return
}
+ if streamSet {
+ canned = strings.Join(streamChunks, "")
+ }
resp := wireResponse{Choices: []wireChoice{{Message: Message{Role: "assistant", Content: canned}}}}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
+
+// sleepCtx sleeps for d, returning false when the request context ends
+// first. A non-positive d returns true at once.
+func sleepCtx(r *http.Request, d time.Duration) bool {
+ if d <= 0 {
+ return true
+ }
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-t.C:
+ return true
+ case <-r.Context().Done():
+ return false
+ }
+}
diff --git a/internal/llm/llmtest/llmtest_test.go b/internal/llm/llmtest/llmtest_test.go
new file mode 100644
index 0000000..f5c83e4
--- /dev/null
+++ b/internal/llm/llmtest/llmtest_test.go
@@ -0,0 +1,215 @@
+package llmtest_test
+
+import (
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/procrastivity/clast/internal/llm/llmtest"
+)
+
+func post(t *testing.T, c *http.Client, url string, stream bool) (*http.Response, string, error) {
+ t.Helper()
+ body := `{"model":"m","messages":[{"role":"user","content":"hi"}]}`
+ if stream {
+ body = `{"model":"m","stream":true,"messages":[{"role":"user","content":"hi"}]}`
+ }
+ resp, err := c.Post(url+"/chat/completions", "application/json", strings.NewReader(body))
+ if err != nil {
+ return nil, "", err
+ }
+ defer func() { _ = resp.Body.Close() }()
+ b, err := io.ReadAll(resp.Body)
+ return resp, string(b), err
+}
+
+func TestSetStreamChunksAndDone(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ s.SetStream([]string{"a", `b"c`})
+ resp, body, err := post(t, http.DefaultClient, s.URL(), true)
+ noErr(t, err)
+ eq(t, "text/event-stream", resp.Header.Get("Content-Type"))
+ eq(t,
+ "data: {\"choices\":[{\"delta\":{\"content\":\"a\"}}]}\n\n"+
+ "data: {\"choices\":[{\"delta\":{\"content\":\"b\\\"c\"}}]}\n\n"+
+ "data: [DONE]\n\n", body)
+}
+
+func TestSetStreamNonStreamRequestGetsJoinedJSON(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ s.SetStream([]string{"a", "b"})
+ resp, body, err := post(t, http.DefaultClient, s.URL(), false)
+ noErr(t, err)
+ eq(t, "application/json", resp.Header.Get("Content-Type"))
+ if !strings.Contains(body, `"content":"ab"`) {
+ t.Fatalf("%q lacks %q", body, `"content":"ab"`)
+ }
+}
+
+func TestSetStreamNilSendsOnlyDone(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ s.SetStream(nil)
+ _, body, err := post(t, http.DefaultClient, s.URL(), true)
+ noErr(t, err)
+ eq(t, "data: [DONE]\n\n", body)
+}
+
+func TestStreamRequestedButNotConfiguredGetsJSON(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ resp, body, err := post(t, http.DefaultClient, s.URL(), true)
+ noErr(t, err)
+ eq(t, "application/json", resp.Header.Get("Content-Type"))
+ if !strings.Contains(body, `"content":"canned"`) {
+ t.Fatalf("%q lacks %q", body, `"content":"canned"`)
+ }
+ if !(s.Requests()[0].Stream) {
+ t.Fatal("want true: s.Requests()[0].Stream")
+ }
+}
+
+func TestSetStreamRawVerbatim(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ s.SetStreamRaw([]string{": keepalive", "", "data: {\"x\":1}"})
+ resp, body, err := post(t, http.DefaultClient, s.URL(), true)
+ noErr(t, err)
+ eq(t, "text/event-stream", resp.Header.Get("Content-Type"))
+ eq(t, ": keepalive\n\ndata: {\"x\":1}\n", body)
+}
+
+func TestRequestsRecordsStream(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ _, _, err := post(t, http.DefaultClient, s.URL(), false)
+ noErr(t, err)
+ _, _, err = post(t, http.DefaultClient, s.URL(), true)
+ noErr(t, err)
+ reqs := s.Requests()
+ if len(reqs) != 2 {
+ t.Fatalf("got %d requests", len(reqs))
+ }
+ if reqs[0].Stream {
+ t.Fatal("want false: reqs[0].Stream")
+ }
+ if !(reqs[1].Stream) {
+ t.Fatal("want true: reqs[1].Stream")
+ }
+}
+
+func TestOverridesClearStreamMode(t *testing.T) {
+ for name, clear := range map[string]func(*llmtest.Server){
+ "SetResponse": func(s *llmtest.Server) { s.SetResponse("plain") },
+ "Fail": func(s *llmtest.Server) { s.Fail(500, "boom") },
+ "RespondRaw": func(s *llmtest.Server) { s.RespondRaw(200, "raw") },
+ } {
+ t.Run(name, func(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ s.SetStream([]string{"a"})
+ clear(s)
+ resp, _, err := post(t, http.DefaultClient, s.URL(), true)
+ noErr(t, err)
+ if resp.Header.Get("Content-Type") == "text/event-stream" {
+ t.Fatal("stream mode still active")
+ }
+
+ s.SetStreamRaw([]string{"x"})
+ clear(s)
+ resp, _, err = post(t, http.DefaultClient, s.URL(), true)
+ noErr(t, err)
+ if resp.Header.Get("Content-Type") == "text/event-stream" {
+ t.Fatal("stream mode still active")
+ }
+ })
+ }
+}
+
+func TestDelayBeforeFirstByteHonorsClientTimeout(t *testing.T) {
+ t0 := time.Now()
+ // Registered before New so it runs after the server closes (LIFO):
+ // a handler that ignores the request context would stall Close.
+ t.Cleanup(func() {
+ if d := time.Since(t0); d >= time.Second {
+ t.Errorf("test took %v, want < 1s", d)
+ }
+ })
+ s := llmtest.New(t, "canned")
+ s.SetDelay(time.Second, 0)
+ start := time.Now()
+ _, _, err := post(t, &http.Client{Timeout: 50 * time.Millisecond}, s.URL(), true)
+ if err == nil {
+ t.Fatal("expected error")
+ }
+ if d := time.Since(start); d >= 500*time.Millisecond {
+ t.Fatalf("took %v, want < %v", d, 500*time.Millisecond)
+ }
+}
+
+func TestDelayBetweenChunks(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ s.SetStream([]string{"a", "b", "c"})
+ s.SetDelay(0, 40*time.Millisecond)
+ start := time.Now()
+ _, body, err := post(t, http.DefaultClient, s.URL(), true)
+ noErr(t, err)
+ if d := time.Since(start); d < 80*time.Millisecond {
+ t.Fatalf("took %v, want >= %v", d, 80*time.Millisecond)
+ }
+ if !strings.Contains(body, "[DONE]") {
+ t.Fatalf("%q lacks %q", body, "[DONE]")
+ }
+}
+
+func TestStreamFlushesEachWrite(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ s.SetStream([]string{"a", "b"})
+ s.SetDelay(0, 300*time.Millisecond)
+ start := time.Now()
+ resp, err := http.Post(s.URL()+"/chat/completions", "application/json",
+ strings.NewReader(`{"stream":true}`))
+ noErr(t, err)
+ defer func() { _ = resp.Body.Close() }()
+ buf := make([]byte, 8)
+ _, err = resp.Body.Read(buf)
+ noErr(t, err)
+ if d := time.Since(start); d >= 250*time.Millisecond {
+ t.Fatalf("took %v, want < %v", d, 250*time.Millisecond)
+ }
+}
+
+func TestConcurrentStreamsDoNotMixChunks(t *testing.T) {
+ s := llmtest.New(t, "canned")
+ s.SetStream([]string{"a", "b", "c"})
+ s.SetDelay(0, 5*time.Millisecond)
+ want := "data: {\"choices\":[{\"delta\":{\"content\":\"a\"}}]}\n\n" +
+ "data: {\"choices\":[{\"delta\":{\"content\":\"b\"}}]}\n\n" +
+ "data: {\"choices\":[{\"delta\":{\"content\":\"c\"}}]}\n\n" +
+ "data: [DONE]\n\n"
+ var wg sync.WaitGroup
+ bodies := make([]string, 2)
+ for i := range bodies {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, b, _ := post(t, http.DefaultClient, s.URL(), true)
+ bodies[i] = b
+ }()
+ }
+ wg.Wait()
+ eq(t, want, bodies[0])
+ eq(t, want, bodies[1])
+}
+
+func noErr(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+func eq(t *testing.T, want, got string) {
+ t.Helper()
+ if want != got {
+ t.Fatalf("want %q, got %q", want, got)
+ }
+}
diff --git a/internal/llm/observe.go b/internal/llm/observe.go
new file mode 100644
index 0000000..495a333
--- /dev/null
+++ b/internal/llm/observe.go
@@ -0,0 +1,98 @@
+package llm
+
+import (
+ "context"
+ "net/http/httptrace"
+ "sync"
+)
+
+// Phase names one point in the life of a Complete call.
+type Phase int
+
+// The Phase values, in the order a successful call reports them.
+const (
+ PhaseStart Phase = iota // Complete entered, before dialing
+ PhaseConnected // httptrace GotConn
+ PhaseRequestSent // httptrace WroteRequest with a nil error
+ PhaseFirstByte // httptrace GotFirstResponseByte
+ PhaseThinking // one streamed reasoning chunk (SSE only)
+ PhaseDelta // one streamed content chunk (SSE only)
+ PhaseDone // reply fully read and parsed
+)
+
+// String returns the phase's short lowercase name.
+func (p Phase) String() string {
+ switch p {
+ case PhaseStart:
+ return "start"
+ case PhaseConnected:
+ return "connected"
+ case PhaseRequestSent:
+ return "request-sent"
+ case PhaseFirstByte:
+ return "first-byte"
+ case PhaseThinking:
+ return "thinking"
+ case PhaseDelta:
+ return "delta"
+ case PhaseDone:
+ return "done"
+ default:
+ return "unknown"
+ }
+}
+
+// Event is one call-lifecycle notification handed to an Observer.
+type Event struct {
+ Phase Phase
+ Text string // the chunk, for PhaseThinking and PhaseDelta; "" otherwise
+}
+
+// Observer receives the lifecycle events of a Complete call. Contract:
+// PhaseStart comes first; PhaseDone comes last and only on success (an
+// error ends the call with no PhaseDone); PhaseFirstByte comes before any
+// PhaseThinking or PhaseDelta; PhaseConnected may repeat. Calls to one
+// Observer for one Complete never overlap, but an Observer shared across
+// concurrent Complete calls must do its own locking.
+type Observer func(Event)
+
+type observerKey struct{}
+
+// WithObserver returns a context carrying o, for Complete to report its
+// phases to. A nil o returns ctx unchanged.
+func WithObserver(ctx context.Context, o Observer) context.Context {
+ if o == nil {
+ return ctx
+ }
+ return context.WithValue(ctx, observerKey{}, o)
+}
+
+func observerFrom(ctx context.Context) Observer {
+ o, _ := ctx.Value(observerKey{}).(Observer)
+ return o
+}
+
+// serialize wraps o so its calls never overlap: httptrace callbacks can
+// run on transport goroutines.
+func serialize(o Observer) Observer {
+ var mu sync.Mutex
+ return func(e Event) {
+ mu.Lock()
+ defer mu.Unlock()
+ o(e)
+ }
+}
+
+// traceFor returns an httptrace.ClientTrace that reports the connection
+// phases to emit.
+func traceFor(emit Observer) *httptrace.ClientTrace {
+ return &httptrace.ClientTrace{
+ GotConn: func(httptrace.GotConnInfo) { emit(Event{Phase: PhaseConnected}) },
+ WroteRequest: func(i httptrace.WroteRequestInfo) {
+ if i.Err == nil {
+ emit(Event{Phase: PhaseRequestSent})
+ }
+ },
+ GotFirstResponseByte: func() { emit(Event{Phase: PhaseFirstByte}) },
+ }
+}
diff --git a/internal/llm/observe_test.go b/internal/llm/observe_test.go
new file mode 100644
index 0000000..43d4d6f
--- /dev/null
+++ b/internal/llm/observe_test.go
@@ -0,0 +1,163 @@
+package llm_test
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/llm/llmtest"
+)
+
+// recorder collects the phases an Observer sees.
+type recorder struct {
+ mu sync.Mutex
+ phases []llm.Phase
+}
+
+func (r *recorder) observe(e llm.Event) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.phases = append(r.phases, e.Phase)
+}
+
+func (r *recorder) seen() []llm.Phase {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return append([]llm.Phase(nil), r.phases...)
+}
+
+func contains(ps []llm.Phase, want llm.Phase) bool {
+ for _, p := range ps {
+ if p == want {
+ return true
+ }
+ }
+ return false
+}
+
+func TestPhase_String(t *testing.T) {
+ want := map[llm.Phase]string{
+ llm.PhaseStart: "start",
+ llm.PhaseConnected: "connected",
+ llm.PhaseRequestSent: "request-sent",
+ llm.PhaseFirstByte: "first-byte",
+ llm.PhaseThinking: "thinking",
+ llm.PhaseDelta: "delta",
+ llm.PhaseDone: "done",
+ }
+ for p, s := range want {
+ if got := p.String(); got != s {
+ t.Errorf("Phase(%d).String() = %q, want %q", int(p), got, s)
+ }
+ }
+}
+
+func TestComplete_ObserverPhases(t *testing.T) {
+ stub := llmtest.New(t, "ok")
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ client, err := llm.NewClient(cfgWith(stub.URL(), "gpt-test"))
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ var rec recorder
+ if _, err := client.Complete(llm.WithObserver(context.Background(), rec.observe), "sys", "usr"); err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+
+ got := rec.seen()
+ if len(got) < 5 {
+ t.Fatalf("phases = %v, want at least 5", got)
+ }
+ if got[0] != llm.PhaseStart {
+ t.Errorf("first phase = %v, want start", got[0])
+ }
+ if got[len(got)-1] != llm.PhaseDone {
+ t.Errorf("last phase = %v, want done", got[len(got)-1])
+ }
+ for _, p := range []llm.Phase{llm.PhaseConnected, llm.PhaseRequestSent, llm.PhaseFirstByte} {
+ if !contains(got[1:len(got)-1], p) {
+ t.Errorf("phases %v missing %v between start and done", got, p)
+ }
+ }
+}
+
+func TestComplete_ObserverNoDoneOnError(t *testing.T) {
+ stub := llmtest.New(t, "ok")
+ stub.Fail(500, "boom")
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ client, err := llm.NewClient(cfgWith(stub.URL(), "gpt-test"))
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ var rec recorder
+ if _, err := client.Complete(llm.WithObserver(context.Background(), rec.observe), "sys", "usr"); err == nil {
+ t.Fatal("Complete: want an error on a 500")
+ }
+ got := rec.seen()
+ if len(got) == 0 || got[0] != llm.PhaseStart {
+ t.Errorf("phases = %v, want start first", got)
+ }
+ if contains(got, llm.PhaseDone) {
+ t.Errorf("phases = %v, want no done after an error", got)
+ }
+}
+
+func TestComplete_ObserverCancelNoDone(t *testing.T) {
+ stub := llmtest.New(t, "ok")
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ client, err := llm.NewClient(cfgWith(stub.URL(), "gpt-test"))
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ var rec recorder
+ obs := func(e llm.Event) {
+ rec.observe(e)
+ if e.Phase == llm.PhaseConnected {
+ cancel()
+ }
+ }
+ if _, err := client.Complete(llm.WithObserver(ctx, obs), "sys", "usr"); err == nil {
+ t.Fatal("Complete: want an error after cancel")
+ }
+ if contains(rec.seen(), llm.PhaseDone) {
+ t.Errorf("phases = %v, want no done after cancel", rec.seen())
+ }
+}
+
+func TestComplete_ObserverConcurrent(t *testing.T) {
+ stub := llmtest.New(t, "ok")
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ client, err := llm.NewClient(cfgWith(stub.URL(), "gpt-test"))
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ const n = 8
+ recs := make([]recorder, n)
+ var wg sync.WaitGroup
+ for i := range n {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if _, err := client.Complete(llm.WithObserver(ctx, recs[i].observe), "sys", "usr"); err != nil {
+ t.Errorf("Complete %d: %v", i, err)
+ }
+ }()
+ }
+ wg.Wait()
+
+ for i := range recs {
+ got := recs[i].seen()
+ if len(got) == 0 || got[0] != llm.PhaseStart || got[len(got)-1] != llm.PhaseDone {
+ t.Errorf("call %d phases = %v, want start first and done last", i, got)
+ }
+ }
+}
diff --git a/internal/llm/sse.go b/internal/llm/sse.go
new file mode 100644
index 0000000..3f86e39
--- /dev/null
+++ b/internal/llm/sse.go
@@ -0,0 +1,109 @@
+package llm
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// maxSSELine caps one SSE line. A single content delta from a real
+// endpoint is far smaller; the cap only guards against a runaway line.
+const maxSSELine = 1 << 20
+
+// streamEvent is the slice of one OpenAI-compatible chat.completion.chunk
+// event this client reads. Events a proxy sends with an empty choices
+// array (usage chunks), a role-only delta, or a finish_reason and no
+// content decode to the zero value and are ignored.
+type streamEvent struct {
+ Choices []struct {
+ Delta struct {
+ Content string `json:"content"`
+ ReasoningContent string `json:"reasoning_content"`
+ Reasoning string `json:"reasoning"`
+ } `json:"delta"`
+ } `json:"choices"`
+ Error *struct {
+ Message string `json:"message"`
+ } `json:"error"`
+}
+
+// readStream reads an SSE reply from body and returns the joined content
+// deltas. Each content delta is reported to emit as PhaseDelta and each
+// reasoning delta as PhaseThinking (emit may be nil). The stream ends at a
+// "data: [DONE]" event or at a clean EOF: some proxies close the
+// connection without [DONE], and that is success, not an error.
+func readStream(body io.Reader, endpoint string, emit Observer) (string, error) {
+ var (
+ result strings.Builder
+ data []string
+ done bool
+ )
+
+ // flush handles the collected data lines as one event.
+ flush := func() error {
+ if len(data) == 0 {
+ return nil
+ }
+ payload := strings.Join(data, "\n")
+ data = data[:0]
+ if payload == "[DONE]" {
+ done = true
+ return nil
+ }
+ var ev streamEvent
+ if err := json.Unmarshal([]byte(payload), &ev); err != nil {
+ return fmt.Errorf("llm: %s returned malformed stream event: %w", endpoint, err)
+ }
+ if ev.Error != nil {
+ return fmt.Errorf("llm: %s stream error: %s", endpoint, ev.Error.Message)
+ }
+ if len(ev.Choices) == 0 {
+ return nil
+ }
+ d := ev.Choices[0].Delta
+ if d.Content != "" {
+ result.WriteString(d.Content)
+ if emit != nil {
+ emit(Event{Phase: PhaseDelta, Text: d.Content})
+ }
+ }
+ thinking := d.ReasoningContent
+ if thinking == "" {
+ thinking = d.Reasoning
+ }
+ if thinking != "" && emit != nil {
+ emit(Event{Phase: PhaseThinking, Text: thinking})
+ }
+ return nil
+ }
+
+ sc := bufio.NewScanner(body)
+ sc.Buffer(make([]byte, 0, 64*1024), maxSSELine)
+ for !done && sc.Scan() {
+ line := strings.TrimSuffix(sc.Text(), "\r")
+ switch {
+ case line == "":
+ if err := flush(); err != nil {
+ return "", err
+ }
+ case strings.HasPrefix(line, ":"):
+ // keepalive comment
+ case strings.HasPrefix(line, "data:"):
+ v := strings.TrimPrefix(line, "data:")
+ data = append(data, strings.TrimPrefix(v, " "))
+ }
+ // event:, id:, retry: and unknown fields are ignored.
+ }
+ if err := sc.Err(); err != nil {
+ return "", fmt.Errorf("llm: reading stream from %s: %w", endpoint, err)
+ }
+ if !done {
+ // EOF with an event still open: treat it as complete.
+ if err := flush(); err != nil {
+ return "", err
+ }
+ }
+ return result.String(), nil
+}
diff --git a/internal/llm/sse_test.go b/internal/llm/sse_test.go
new file mode 100644
index 0000000..e8825db
--- /dev/null
+++ b/internal/llm/sse_test.go
@@ -0,0 +1,417 @@
+package llm_test
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/procrastivity/clast/internal/config"
+ "github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/llm/llmtest"
+)
+
+// eventLog collects full events an Observer sees.
+type eventLog struct {
+ mu sync.Mutex
+ ev []llm.Event
+}
+
+func (l *eventLog) observe(e llm.Event) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.ev = append(l.ev, e)
+}
+
+func (l *eventLog) all() []llm.Event {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return append([]llm.Event(nil), l.ev...)
+}
+
+func (l *eventLog) phases() []llm.Phase {
+ var ps []llm.Phase
+ for _, e := range l.all() {
+ ps = append(ps, e.Phase)
+ }
+ return ps
+}
+
+func (l *eventLog) texts(p llm.Phase) []string {
+ var out []string
+ for _, e := range l.all() {
+ if e.Phase == p {
+ out = append(out, e.Text)
+ }
+ }
+ return out
+}
+
+func streamClient(t *testing.T, baseURL string) *llm.Client {
+ t.Helper()
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ c, err := llm.NewClient(cfgWith(baseURL, "gpt-test"))
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+ return c
+}
+
+func completeLogged(c *llm.Client) (string, *eventLog, error) {
+ var log eventLog
+ got, err := c.Complete(llm.WithObserver(context.Background(), log.observe), "sys", "usr")
+ return got, &log, err
+}
+
+func sseData(js string) []string { return []string{"data: " + js, ""} }
+
+func TestComplete_StreamDeltas(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStream([]string{"Hel", "lo"})
+ got, log, err := completeLogged(streamClient(t, stub.URL()))
+ if err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if got != "Hello" {
+ t.Errorf("content = %q, want Hello", got)
+ }
+ if want := []string{"Hel", "lo"}; !reflect.DeepEqual(log.texts(llm.PhaseDelta), want) {
+ t.Errorf("delta texts = %v, want %v", log.texts(llm.PhaseDelta), want)
+ }
+ ps := log.phases()
+ first, d1, d2, done := -1, -1, -1, -1
+ for i, p := range ps {
+ switch {
+ case p == llm.PhaseFirstByte:
+ first = i
+ case p == llm.PhaseDelta && d1 < 0:
+ d1 = i
+ case p == llm.PhaseDelta:
+ d2 = i
+ case p == llm.PhaseDone:
+ done = i
+ }
+ }
+ if first < 0 || first >= d1 || d1 >= d2 || d2 >= done || done != len(ps)-1 {
+ t.Errorf("phase order = %v", ps)
+ }
+ if !stub.Requests()[0].Stream {
+ t.Error("request Stream = false, want true")
+ }
+}
+
+func TestComplete_StreamFallsBackToJSON(t *testing.T) {
+ stub := llmtest.New(t, "canned text")
+ got, log, err := completeLogged(streamClient(t, stub.URL()))
+ if err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if got != "canned text" {
+ t.Errorf("content = %q", got)
+ }
+ if !stub.Requests()[0].Stream {
+ t.Error("request Stream = false, want true (default)")
+ }
+ if n := len(log.texts(llm.PhaseDelta)); n != 0 {
+ t.Errorf("JSON reply produced %d delta events", n)
+ }
+}
+
+func TestComplete_StreamDisabledByConfig(t *testing.T) {
+ stub := llmtest.New(t, "plain")
+ stub.SetStream([]string{"sse"})
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ cfg := config.Config{"llm": map[string]any{
+ "base_url": stub.URL(), "model": "m", "stream": false,
+ }}
+ c, err := llm.NewClient(cfg)
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+ got, err := c.Complete(context.Background(), "s", "u")
+ if err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if got != "sse" {
+ // The stub joins chunks into JSON for a non-stream request.
+ t.Errorf("content = %q, want sse", got)
+ }
+ if stub.Requests()[0].Stream {
+ t.Error("request Stream = true, want false")
+ }
+}
+
+func TestNewClient_StreamConfig(t *testing.T) {
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ mk := func(v any, set bool) config.Config {
+ sec := map[string]any{"base_url": "http://x", "model": "m"}
+ if set {
+ sec["stream"] = v
+ }
+ return config.Config{"llm": sec}
+ }
+ for name, cfg := range map[string]config.Config{
+ "absent": mk(nil, false), "null": mk(nil, true), "true": mk(true, true), "false": mk(false, true),
+ } {
+ if _, err := llm.NewClient(cfg); err != nil {
+ t.Errorf("%s: NewClient: %v", name, err)
+ }
+ }
+ _, err := llm.NewClient(mk("yes", true))
+ if err == nil || !strings.Contains(err.Error(), "llm.stream") {
+ t.Fatalf("non-bool stream err = %v, want one naming llm.stream", err)
+ }
+}
+
+func TestComplete_StreamRaw(t *testing.T) {
+ const chunk = `{"choices":[{"delta":{"content":"%s"}}]}`
+ join := func(parts ...[]string) []string {
+ var out []string
+ for _, p := range parts {
+ out = append(out, p...)
+ }
+ return out
+ }
+ tests := []struct {
+ name string
+ lines []string
+ want string
+ wantErr string
+ thinking []string
+ wantDelta []string
+ }{
+ {
+ name: "keepalive comments skipped",
+ lines: join([]string{": keepalive", ""}, sseData(fmt.Sprintf(chunk, "a")),
+ []string{": ping", ""}, sseData(fmt.Sprintf(chunk, "b")), []string{"data: [DONE]", ""}),
+ want: "ab", wantDelta: []string{"a", "b"},
+ },
+ {
+ name: "reasoning stays out of result",
+ lines: join(
+ sseData(`{"choices":[{"delta":{"reasoning_content":"hmm"}}]}`),
+ sseData(`{"choices":[{"delta":{"reasoning":"ok"}}]}`),
+ sseData(fmt.Sprintf(chunk, "ans")), []string{"data: [DONE]", ""}),
+ want: "ans", thinking: []string{"hmm", "ok"}, wantDelta: []string{"ans"},
+ },
+ {
+ name: "contentless events ignored",
+ lines: join(
+ sseData(`{"choices":[{"delta":{"role":"assistant","content":""}}]}`),
+ sseData(`{"choices":[]}`),
+ sseData(`{"choices":[{"delta":{"content":null}}]}`),
+ sseData(fmt.Sprintf(chunk, "x")),
+ sseData(`{"choices":[{"delta":{},"finish_reason":"stop"}]}`),
+ sseData(`{"choices":[],"usage":{"total_tokens":3}}`),
+ []string{"data: [DONE]", ""}),
+ want: "x", wantDelta: []string{"x"},
+ },
+ {
+ name: "error event",
+ lines: join(sseData(fmt.Sprintf(chunk, "a")), sseData(`{"error":{"message":"rate limited"}}`)),
+ wantErr: "stream error: rate limited",
+ },
+ {
+ name: "malformed event",
+ lines: sseData(`{not json`),
+ wantErr: "returned malformed stream event:",
+ },
+ {
+ name: "missing DONE is success",
+ lines: join(sseData(fmt.Sprintf(chunk, "tail"))),
+ want: "tail", wantDelta: []string{"tail"},
+ },
+ {
+ name: "unterminated final event still counts",
+ lines: []string{"data: " + fmt.Sprintf(chunk, "last")},
+ want: "last", wantDelta: []string{"last"},
+ },
+ {
+ name: "no space after data colon and CRLF-free event field",
+ lines: []string{"event: message", "data:" + fmt.Sprintf(chunk, "n"), "", "data: [DONE]", ""},
+ want: "n", wantDelta: []string{"n"},
+ },
+ {
+ name: "event split over two data lines",
+ lines: []string{
+ `data: {"choices":[{"delta":`, `data: {"content":"split"}}]}`, "",
+ "data: [DONE]", "",
+ },
+ want: "split", wantDelta: []string{"split"},
+ },
+ {
+ name: "stops at DONE",
+ lines: join([]string{"data: [DONE]", ""},
+ sseData(fmt.Sprintf(chunk, "after"))),
+ want: "",
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStreamRaw(tc.lines)
+ got, log, err := completeLogged(streamClient(t, stub.URL()))
+ if tc.wantErr != "" {
+ if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
+ t.Fatalf("err = %v, want containing %q", err, tc.wantErr)
+ }
+ if contains(log.phases(), llm.PhaseDone) {
+ t.Error("PhaseDone emitted on error")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if got != tc.want {
+ t.Errorf("content = %q, want %q", got, tc.want)
+ }
+ if !reflect.DeepEqual(log.texts(llm.PhaseThinking), tc.thinking) {
+ t.Errorf("thinking = %v, want %v", log.texts(llm.PhaseThinking), tc.thinking)
+ }
+ if !reflect.DeepEqual(log.texts(llm.PhaseDelta), tc.wantDelta) {
+ t.Errorf("deltas = %v, want %v", log.texts(llm.PhaseDelta), tc.wantDelta)
+ }
+ if ps := log.phases(); ps[len(ps)-1] != llm.PhaseDone {
+ t.Errorf("last phase = %v, want done", ps[len(ps)-1])
+ }
+ })
+ }
+}
+
+func TestComplete_StreamNoObserver(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStreamRaw(append(sseData(`{"choices":[{"delta":{"reasoning_content":"r"}}]}`),
+ append(sseData(`{"choices":[{"delta":{"content":"c"}}]}`), "data: [DONE]", "")...))
+ got, err := streamClient(t, stub.URL()).Complete(context.Background(), "s", "u")
+ if err != nil || got != "c" {
+ t.Fatalf("got %q, %v", got, err)
+ }
+}
+
+func TestComplete_StreamLargeDelta(t *testing.T) {
+ big := strings.Repeat("x", 200*1024)
+ stub := llmtest.New(t, "unused")
+ stub.SetStream([]string{big, "!"})
+ got, log, err := completeLogged(streamClient(t, stub.URL()))
+ if err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if got != big+"!" {
+ t.Errorf("content length = %d, want %d", len(got), len(big)+1)
+ }
+ if d := log.texts(llm.PhaseDelta); len(d) != 2 || len(d[0]) != len(big) {
+ t.Errorf("delta lengths wrong: %d deltas", len(d))
+ }
+}
+
+func TestComplete_StreamLineTooLong(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStream([]string{strings.Repeat("x", 2<<20)})
+ _, _, err := completeLogged(streamClient(t, stub.URL()))
+ if err == nil || !strings.Contains(err.Error(), "reading stream") {
+ t.Fatalf("err = %v, want reading stream error", err)
+ }
+}
+
+// sseServer answers every request with status, Content-Type ct and body.
+func sseServer(t *testing.T, status int, ct, body string) *httptest.Server {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", ct)
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(body))
+ }))
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+func TestComplete_StreamContentTypeCharset(t *testing.T) {
+ srv := sseServer(t, 200, "text/event-stream; charset=utf-8",
+ "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: [DONE]\n\n")
+ got, err := streamClient(t, srv.URL).Complete(context.Background(), "s", "u")
+ if err != nil || got != "hi" {
+ t.Fatalf("got %q, %v", got, err)
+ }
+}
+
+func TestComplete_StreamNon2xxKeepsErrorPath(t *testing.T) {
+ srv := sseServer(t, 500, "text/event-stream",
+ "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n")
+ got, log, err := completeLogged(streamClient(t, srv.URL))
+ if err == nil || !strings.Contains(err.Error(), "500") || !strings.Contains(err.Error(), "returned") {
+ t.Fatalf("err = %v, want non-2xx error", err)
+ }
+ if got != "" || len(log.texts(llm.PhaseDelta)) != 0 {
+ t.Errorf("non-2xx SSE was parsed: %q", got)
+ }
+}
+
+func TestComplete_StreamReturnsAtDoneWithoutWaiting(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStreamRaw([]string{`data: {"choices":[{"delta":{"content":"x"}}]}` + "\n", "data: [DONE]\n", ": held open"})
+ stub.SetDelay(0, 300*time.Millisecond)
+ start := time.Now()
+ got, err := streamClient(t, stub.URL()).Complete(context.Background(), "s", "u")
+ if err != nil || got != "x" {
+ t.Fatalf("got %q, %v", got, err)
+ }
+ if d := time.Since(start); d >= 500*time.Millisecond {
+ t.Errorf("Complete took %v, want it to return at [DONE]", d)
+ }
+}
+
+func TestComplete_StreamRequestBodyKey(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ cfg any
+ want bool
+ }{{"default", nil, true}, {"false", false, false}} {
+ t.Run(tc.name, func(t *testing.T) {
+ var body string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ body = string(b)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":"ok"}}]}`))
+ }))
+ defer srv.Close()
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ sec := map[string]any{"base_url": srv.URL, "model": "m"}
+ if tc.cfg != nil {
+ sec["stream"] = tc.cfg
+ }
+ c, err := llm.NewClient(config.Config{"llm": sec})
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+ if _, err := c.Complete(context.Background(), "s", "u"); err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if tc.want && !strings.Contains(body, `"stream":true`) {
+ t.Errorf("body %s lacks \"stream\":true", body)
+ }
+ if !tc.want && strings.Contains(body, `"stream"`) {
+ t.Errorf("body %s carries a stream key", body)
+ }
+ })
+ }
+}
+
+func TestComplete_StreamReasoningPrecedence(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStreamRaw(append(sseData(`{"choices":[{"delta":{"reasoning_content":"RC","reasoning":"R"}}]}`), "data: [DONE]", ""))
+ _, log, err := completeLogged(streamClient(t, stub.URL()))
+ if err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if got, want := log.texts(llm.PhaseThinking), []string{"RC"}; !reflect.DeepEqual(got, want) {
+ t.Errorf("thinking = %v, want %v", got, want)
+ }
+}
diff --git a/internal/llm/timeout_test.go b/internal/llm/timeout_test.go
new file mode 100644
index 0000000..0c28955
--- /dev/null
+++ b/internal/llm/timeout_test.go
@@ -0,0 +1,289 @@
+package llm_test
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/llm/llmtest"
+)
+
+func timeoutClient(t *testing.T, stub *llmtest.Server, firstByte, idle, total time.Duration) *llm.Client {
+ t.Helper()
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ c, err := llm.NewClient(cfgWith(stub.URL(), "gpt-test"))
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+ llm.SetTimeouts(c, firstByte, idle, total)
+ return c
+}
+
+func chunks(n int) []string {
+ out := make([]string, n)
+ for i := range out {
+ out[i] = "x"
+ }
+ return out
+}
+
+func TestTimeout_LongStreamNotCut(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStream(chunks(5))
+ stub.SetDelay(0, 40*time.Millisecond)
+ c := timeoutClient(t, stub, 100*time.Millisecond, 100*time.Millisecond, 5*time.Second)
+
+ got, err := c.Complete(context.Background(), "s", "u")
+ if err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if got != "xxxxx" {
+ t.Fatalf("content = %q, want %q", got, "xxxxx")
+ }
+}
+
+func TestTimeout_FirstByteStream(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStream(chunks(3))
+ stub.SetDelay(500*time.Millisecond, 0)
+ c := timeoutClient(t, stub, 100*time.Millisecond, time.Second, 5*time.Second)
+
+ start := time.Now()
+ _, err := c.Complete(context.Background(), "s", "u")
+ if err == nil || !strings.Contains(err.Error(), "calling") || !strings.Contains(err.Error(), "timeout awaiting response headers") {
+ t.Fatalf("err = %v, want first-byte transport error", err)
+ }
+ if d := time.Since(start); d > 400*time.Millisecond {
+ t.Fatalf("took %v, want under 400ms", d)
+ }
+}
+
+func TestTimeout_FirstByteJSON(t *testing.T) {
+ stub := llmtest.New(t, "ok")
+ stub.SetDelay(500*time.Millisecond, 0)
+ c := timeoutClient(t, stub, 100*time.Millisecond, time.Second, 5*time.Second)
+
+ start := time.Now()
+ _, err := c.Complete(context.Background(), "s", "u")
+ if err == nil || !strings.Contains(err.Error(), "timeout awaiting response headers") {
+ t.Fatalf("err = %v, want first-byte transport error", err)
+ }
+ if d := time.Since(start); d > 400*time.Millisecond {
+ t.Fatalf("took %v, want under 400ms", d)
+ }
+}
+
+func TestTimeout_IdleStall(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStream(chunks(3))
+ stub.SetDelay(0, 500*time.Millisecond)
+ c := timeoutClient(t, stub, time.Second, 100*time.Millisecond, 5*time.Second)
+
+ var rec phaseRecorder
+ start := time.Now()
+ _, err := c.Complete(rec.ctx(), "s", "u")
+ if err == nil || !strings.Contains(err.Error(), "stalled: no data for 100ms") {
+ t.Fatalf("err = %v, want stalled error", err)
+ }
+ rec.requireNoDone(t)
+ if d := time.Since(start); d > 400*time.Millisecond {
+ t.Fatalf("took %v, want under 400ms", d)
+ }
+}
+
+func TestTimeout_TotalCap(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStream(chunks(40))
+ stub.SetDelay(0, 20*time.Millisecond)
+ c := timeoutClient(t, stub, time.Second, 500*time.Millisecond, 150*time.Millisecond)
+
+ var rec phaseRecorder
+ _, err := c.Complete(rec.ctx(), "s", "u")
+ if err == nil || !strings.Contains(err.Error(), "exceeded 150ms") {
+ t.Fatalf("err = %v, want exceeded error", err)
+ }
+ rec.requireNoDone(t)
+ if strings.Contains(err.Error(), "stalled") {
+ t.Fatalf("err = %v, must not read as stalled", err)
+ }
+}
+
+func TestTimeout_ParentCancelPassesThrough(t *testing.T) {
+ stub := llmtest.New(t, "unused")
+ stub.SetStream(chunks(40))
+ stub.SetDelay(0, 20*time.Millisecond)
+ c := timeoutClient(t, stub, time.Second, time.Second, 5*time.Second)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ time.AfterFunc(80*time.Millisecond, cancel)
+ _, err := c.Complete(ctx, "s", "u")
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("err = %v, want context.Canceled", err)
+ }
+ if strings.Contains(err.Error(), "stalled") || strings.Contains(err.Error(), "exceeded") {
+ t.Fatalf("err = %v, parent cancel must not read as a limit", err)
+ }
+}
+
+func TestTimeout_SuccessLeavesNoTimerOrGoroutine(t *testing.T) {
+ stub := llmtest.New(t, "ok")
+ stub.SetStream(chunks(3))
+ c := timeoutClient(t, stub, time.Second, 50*time.Millisecond, 5*time.Second)
+
+ if _, err := c.Complete(context.Background(), "s", "u"); err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ // Outlive the idle limit: a leaked timer would fire here, harmlessly,
+ // but the goroutine count must settle back.
+ before := runtime.NumGoroutine()
+ for i := 0; i < 5; i++ {
+ if _, err := c.Complete(context.Background(), "s", "u"); err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ }
+ time.Sleep(200 * time.Millisecond)
+ if after := runtime.NumGoroutine(); after > before+2 {
+ t.Fatalf("goroutines %d -> %d, leak suspected", before, after)
+ }
+}
+
+// phaseRecorder collects observed phases for a Complete call.
+type phaseRecorder struct {
+ mu sync.Mutex
+ ps []llm.Phase
+}
+
+func (r *phaseRecorder) ctx() context.Context {
+ return llm.WithObserver(context.Background(), func(e llm.Event) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.ps = append(r.ps, e.Phase)
+ })
+}
+
+func (r *phaseRecorder) requireNoDone(t *testing.T) {
+ t.Helper()
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if contains(r.ps, llm.PhaseDone) {
+ t.Fatalf("phases %v include PhaseDone on a failed call", r.ps)
+ }
+}
+
+// jsonClient serves handler on a local httptest server and returns a
+// Client pointed at it with the given limits.
+func jsonClient(t *testing.T, handler http.HandlerFunc, firstByte, idle, total time.Duration) *llm.Client {
+ t.Helper()
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ c, err := llm.NewClient(cfgWith(srv.URL, "gpt-test"))
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+ llm.SetTimeouts(c, firstByte, idle, total)
+ return c
+}
+
+func TestTimeout_JSONIdleStall(t *testing.T) {
+ c := jsonClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"choices":[{"message":`))
+ w.(http.Flusher).Flush()
+ <-r.Context().Done()
+ }, time.Second, 100*time.Millisecond, 5*time.Second)
+
+ var rec phaseRecorder
+ _, err := c.Complete(rec.ctx(), "s", "u")
+ if err == nil || !strings.Contains(err.Error(), "stalled: no data for 100ms") {
+ t.Fatalf("err = %v, want stalled error", err)
+ }
+ rec.requireNoDone(t)
+}
+
+func TestTimeout_JSONTotalCap(t *testing.T) {
+ c := jsonClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ body := `{"choices":[{"message":{"role":"assistant","content":"` + strings.Repeat("a", 200) + `"}}]}`
+ for i := 0; i < len(body); i++ {
+ if _, err := w.Write([]byte{body[i]}); err != nil {
+ return
+ }
+ w.(http.Flusher).Flush()
+ select {
+ case <-r.Context().Done():
+ return
+ case <-time.After(20 * time.Millisecond):
+ }
+ }
+ }, time.Second, 500*time.Millisecond, 150*time.Millisecond)
+
+ var rec phaseRecorder
+ _, err := c.Complete(rec.ctx(), "s", "u")
+ if err == nil || !strings.Contains(err.Error(), "exceeded 150ms") {
+ t.Fatalf("err = %v, want exceeded error", err)
+ }
+ rec.requireNoDone(t)
+}
+
+func TestTimeout_JSONTrickleNotCut(t *testing.T) {
+ const body = `{"choices":[{"message":{"role":"assistant","content":"trickled"}}]}`
+ c := jsonClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ for i := 0; i < len(body); i++ {
+ if _, err := w.Write([]byte{body[i]}); err != nil {
+ return
+ }
+ w.(http.Flusher).Flush()
+ select {
+ case <-r.Context().Done():
+ return
+ case <-time.After(10 * time.Millisecond):
+ }
+ }
+ }, time.Second, 100*time.Millisecond, 5*time.Second)
+
+ // The body outlasts the idle limit several times over; only a read
+ // that goes through the idle reader keeps resetting the timer.
+ got, err := c.Complete(context.Background(), "s", "u")
+ if err != nil {
+ t.Fatalf("Complete: %v", err)
+ }
+ if got != "trickled" {
+ t.Fatalf("content = %q, want %q", got, "trickled")
+ }
+}
+
+func TestTimeout_MalformedAfterIdleNotMislabeled(t *testing.T) {
+ c := jsonClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ // One write: the delta and the malformed event are both buffered
+ // before the observer below stalls the parser.
+ _, _ = w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: {not json\n\n"))
+ w.(http.Flusher).Flush()
+ <-r.Context().Done()
+ }, time.Second, 50*time.Millisecond, 5*time.Second)
+
+ // Observer time counts toward IdleTimeout: no body Read happens while
+ // the observer runs, so the idle timer fires here. The malformed
+ // event that follows must still surface as itself, not as "stalled".
+ ctx := llm.WithObserver(context.Background(), func(e llm.Event) {
+ if e.Phase == llm.PhaseDelta {
+ time.Sleep(200 * time.Millisecond)
+ }
+ })
+ _, err := c.Complete(ctx, "s", "u")
+ if err == nil || !strings.Contains(err.Error(), "returned malformed stream event") {
+ t.Fatalf("err = %v, want malformed stream event error", err)
+ }
+ if strings.Contains(err.Error(), "stalled") {
+ t.Fatalf("err = %v, must not be mislabeled stalled", err)
+ }
+}
diff --git a/internal/progress/progress.go b/internal/progress/progress.go
new file mode 100644
index 0000000..ddf84a3
--- /dev/null
+++ b/internal/progress/progress.go
@@ -0,0 +1,240 @@
+// Package progress draws one status line on stderr while a verb waits on the
+// LLM. The line shows a label, the call phase, and the elapsed time. It is
+// off unless stderr is a terminal, so piped output and e2e runs never see it.
+package progress
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "strconv"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ "github.com/procrastivity/clast/internal/cliflags"
+ "github.com/procrastivity/clast/internal/iostreams"
+ "github.com/procrastivity/clast/internal/llm"
+)
+
+const (
+ tickInterval = 100 * time.Millisecond
+ eraseLine = "\r\x1b[K"
+ defaultWidth = 80
+ sep = " · "
+)
+
+var frames = []rune("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")
+
+type contextKey struct{}
+
+// Reporter draws and clears one status line. The zero value is not usable;
+// build one with New. A nil *Reporter is valid and every method on it does
+// nothing, so callers never need to check for "progress off".
+type Reporter struct {
+ w io.Writer
+ tick time.Duration
+ now func() time.Time
+
+ mu sync.Mutex
+ label string
+ phase string
+ chars int // runes of Delta text since the last Status
+ start time.Time // first Status after the last Clear
+ active bool // a label is set and the line is being drawn
+ drawn bool // a line is on screen
+ frame int
+ stopped bool
+ started bool // the draw goroutine has been launched
+
+ quit chan struct{}
+ done chan struct{} // closed when the draw goroutine returns
+}
+
+// New returns a Reporter that draws on streams.Err, or nil when progress
+// must stay off: --json is set, TERM is dumb, or stderr is not a terminal.
+func New(streams *iostreams.Streams, flags cliflags.Flags) *Reporter {
+ if flags.JSON || os.Getenv("TERM") == "dumb" || streams == nil {
+ return nil
+ }
+ f, ok := streams.Err.(*os.File)
+ if !ok {
+ return nil
+ }
+ fi, err := f.Stat()
+ if err != nil || fi.Mode()&os.ModeCharDevice == 0 {
+ return nil
+ }
+ return newReporter(f, tickInterval, time.Now)
+}
+
+// newReporter builds an enabled Reporter that draws on w, for tests.
+func newReporter(w io.Writer, tick time.Duration, now func() time.Time) *Reporter {
+ return &Reporter{
+ w: w,
+ tick: tick,
+ now: now,
+ quit: make(chan struct{}),
+ done: make(chan struct{}),
+ }
+}
+
+// WithReporter returns a context carrying r, for verbs to read via
+// FromContext.
+func WithReporter(ctx context.Context, r *Reporter) context.Context {
+ return context.WithValue(ctx, contextKey{}, r)
+}
+
+// FromContext returns the Reporter stored by WithReporter, or nil if none
+// was stored.
+func FromContext(ctx context.Context) *Reporter {
+ r, _ := ctx.Value(contextKey{}).(*Reporter)
+ return r
+}
+
+// Status sets the label and starts drawing if the reporter is idle. A new
+// call keeps the elapsed time and resets the phase and the character count.
+func (r *Reporter) Status(label string) {
+ if r == nil {
+ return
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.stopped {
+ return
+ }
+ r.label = label
+ r.phase = ""
+ r.chars = 0
+ if !r.active {
+ r.active = true
+ r.start = r.now()
+ }
+ if !r.started {
+ r.started = true
+ go r.loop()
+ }
+ r.draw()
+}
+
+// Observer returns an llm.Observer that updates the phase text. It is safe
+// to call from several goroutines.
+func (r *Reporter) Observer() llm.Observer {
+ if r == nil {
+ return func(llm.Event) {}
+ }
+ return func(e llm.Event) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ switch e.Phase {
+ case llm.PhaseStart:
+ r.phase = "connecting"
+ case llm.PhaseConnected:
+ r.phase = "connected"
+ case llm.PhaseRequestSent:
+ r.phase = "waiting for the model"
+ case llm.PhaseFirstByte:
+ r.phase = "receiving"
+ case llm.PhaseThinking:
+ r.phase = "thinking"
+ case llm.PhaseDelta:
+ r.chars += utf8.RuneCountInString(e.Text)
+ r.phase = "receiving · " + strconv.Itoa(r.chars) + " chars"
+ case llm.PhaseDone:
+ r.phase = "done"
+ }
+ }
+}
+
+// Clear erases the line, stops drawing, and resets the elapsed time. The
+// next Status starts a fresh count.
+func (r *Reporter) Clear() {
+ if r == nil {
+ return
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.clear()
+}
+
+// Stop clears the line and ends the draw goroutine. It is idempotent, and a
+// Status after Stop does nothing.
+func (r *Reporter) Stop() {
+ if r == nil {
+ return
+ }
+ r.mu.Lock()
+ r.clear()
+ wasStopped := r.stopped
+ r.stopped = true
+ started := r.started
+ r.mu.Unlock()
+ if !wasStopped {
+ close(r.quit)
+ }
+ if started {
+ <-r.done
+ }
+}
+
+// clear erases the line when one is on screen. The caller holds r.mu.
+func (r *Reporter) clear() {
+ if r.drawn {
+ _, _ = io.WriteString(r.w, eraseLine)
+ r.drawn = false
+ }
+ r.active = false
+ r.label = ""
+ r.phase = ""
+ r.chars = 0
+}
+
+// loop redraws the line on every tick until Stop.
+func (r *Reporter) loop() {
+ defer close(r.done)
+ t := time.NewTicker(r.tick)
+ defer t.Stop()
+ for {
+ select {
+ case <-r.quit:
+ return
+ case <-t.C:
+ r.mu.Lock()
+ r.frame++
+ r.draw()
+ r.mu.Unlock()
+ }
+ }
+}
+
+// draw writes the current line when a label is active. The caller holds r.mu.
+func (r *Reporter) draw() {
+ if !r.active || r.stopped {
+ return
+ }
+ line := string(frames[r.frame%len(frames)]) + " " + r.label
+ if r.phase != "" {
+ line += sep + r.phase
+ }
+ line += fmt.Sprintf("%s%ds", sep, int(r.now().Sub(r.start).Seconds()))
+ _, _ = io.WriteString(r.w, eraseLine+truncate(line, width()-1))
+ r.drawn = true
+}
+
+// width returns the terminal width from COLUMNS, or 80 when it is unset or
+// invalid.
+func width() int {
+ if n, err := strconv.Atoi(os.Getenv("COLUMNS")); err == nil && n > 1 {
+ return n
+ }
+ return defaultWidth
+}
+
+// truncate cuts s to at most n runes.
+func truncate(s string, n int) string {
+ if utf8.RuneCountInString(s) <= n {
+ return s
+ }
+ return string([]rune(s)[:n])
+}
diff --git a/internal/progress/progress_test.go b/internal/progress/progress_test.go
new file mode 100644
index 0000000..fbab62a
--- /dev/null
+++ b/internal/progress/progress_test.go
@@ -0,0 +1,361 @@
+package progress
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+ "unicode/utf8"
+
+ "github.com/procrastivity/clast/internal/cliflags"
+ "github.com/procrastivity/clast/internal/iostreams"
+ "github.com/procrastivity/clast/internal/llm"
+)
+
+// syncBuf is a bytes.Buffer safe for the draw goroutine and the test.
+type syncBuf struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (s *syncBuf) Write(p []byte) (int, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.Write(p)
+}
+
+func (s *syncBuf) String() string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.String()
+}
+
+func (s *syncBuf) Reset() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.b.Reset()
+}
+
+type fakeClock struct {
+ mu sync.Mutex
+ t time.Time
+}
+
+func (c *fakeClock) Now() time.Time {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.t
+}
+
+func (c *fakeClock) Advance(d time.Duration) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.t = c.t.Add(d)
+}
+
+// newTest returns a reporter whose goroutine never ticks on its own, so the
+// test drives every redraw through redraw.
+func newTest(t *testing.T) (*Reporter, *syncBuf, *fakeClock) {
+ t.Helper()
+ buf := &syncBuf{}
+ clk := &fakeClock{t: time.Unix(1000, 0)}
+ r := newReporter(buf, time.Hour, clk.Now)
+ t.Cleanup(r.Stop)
+ return r, buf, clk
+}
+
+// redraw forces one tick and returns what it wrote.
+func redraw(r *Reporter, buf *syncBuf) string {
+ buf.Reset()
+ r.mu.Lock()
+ r.draw()
+ r.mu.Unlock()
+ return buf.String()
+}
+
+func TestNewDisabled(t *testing.T) {
+ t.Setenv("TERM", "xterm")
+ var stderr bytes.Buffer
+ if r := New(&iostreams.Streams{Err: &stderr}, cliflags.Flags{}); r != nil {
+ t.Error("bytes.Buffer stderr: want nil")
+ }
+
+ tty, err := os.Open("/dev/null") // a char device, so only the flag can disable it
+ if err != nil {
+ t.Skip("no /dev/null")
+ }
+ defer func() { _ = tty.Close() }()
+ if r := New(&iostreams.Streams{Err: tty}, cliflags.Flags{JSON: true}); r != nil {
+ t.Error("JSON: want nil")
+ }
+ t.Setenv("TERM", "dumb")
+ if r := New(&iostreams.Streams{Err: tty}, cliflags.Flags{}); r != nil {
+ t.Error("TERM=dumb: want nil")
+ }
+}
+
+func TestNewEnabledOnCharDevice(t *testing.T) {
+ t.Setenv("TERM", "xterm")
+ tty, err := os.OpenFile("/dev/null", os.O_WRONLY, 0)
+ if err != nil {
+ t.Skip("no /dev/null")
+ }
+ defer func() { _ = tty.Close() }()
+ r := New(&iostreams.Streams{Err: tty}, cliflags.Flags{})
+ if r == nil {
+ t.Fatal("char device stderr: want a reporter")
+ }
+ r.Stop()
+}
+
+func TestNilReceiver(t *testing.T) {
+ var r *Reporter
+ r.Status("x")
+ r.Observer()(llm.Event{Phase: llm.PhaseStart})
+ r.Clear()
+ r.Stop()
+ if FromContext(context.Background()) != nil {
+ t.Error("FromContext on empty ctx: want nil")
+ }
+ if FromContext(WithReporter(context.Background(), nil)) != nil {
+ t.Error("FromContext with nil reporter: want nil")
+ }
+}
+
+func TestContextRoundTrip(t *testing.T) {
+ r, _, _ := newTest(t)
+ if got := FromContext(WithReporter(context.Background(), r)); got != r {
+ t.Error("FromContext did not return the stored reporter")
+ }
+}
+
+func TestDrawPhasesAndElapsed(t *testing.T) {
+ r, buf, clk := newTest(t)
+ r.Status("summarizing 1/3")
+ obs := r.Observer()
+
+ cases := []struct {
+ e llm.Event
+ want string
+ }{
+ {llm.Event{Phase: llm.PhaseStart}, "connecting"},
+ {llm.Event{Phase: llm.PhaseConnected}, "connected"},
+ {llm.Event{Phase: llm.PhaseRequestSent}, "waiting for the model"},
+ {llm.Event{Phase: llm.PhaseFirstByte}, "receiving"},
+ {llm.Event{Phase: llm.PhaseThinking, Text: "hm"}, "thinking"},
+ {llm.Event{Phase: llm.PhaseDelta, Text: "abc"}, "receiving · 3 chars"},
+ {llm.Event{Phase: llm.PhaseDone}, "done"},
+ }
+ for i, c := range cases {
+ clk.Advance(2 * time.Second)
+ obs(c.e)
+ out := redraw(r, buf)
+ if !strings.HasPrefix(out, "\r\x1b[K") {
+ t.Errorf("%v: redraw %q lacks the erase prefix", c.e.Phase, out)
+ }
+ wantTail := " summarizing 1/3 · " + c.want + " · " + strconv.Itoa(2*(i+1)) + "s"
+ if !strings.HasSuffix(out, wantTail) {
+ t.Errorf("%v: got %q, want suffix %q", c.e.Phase, out, wantTail)
+ }
+ }
+}
+
+func TestFrameAdvances(t *testing.T) {
+ r, buf, _ := newTest(t)
+ r.Status("x")
+ a := redraw(r, buf)
+ r.mu.Lock()
+ r.frame++
+ r.mu.Unlock()
+ b := redraw(r, buf)
+ if a == b || !strings.Contains(a, "⠋") || !strings.Contains(b, "⠙") {
+ t.Errorf("frames did not advance: %q then %q", a, b)
+ }
+}
+
+func TestClearResetsElapsed(t *testing.T) {
+ r, buf, clk := newTest(t)
+ r.Status("a")
+ clk.Advance(5 * time.Second)
+ if out := redraw(r, buf); !strings.HasSuffix(out, "5s") {
+ t.Fatalf("before Clear: %q", out)
+ }
+ buf.Reset()
+ r.Clear()
+ if got := buf.String(); got != "\r\x1b[K" {
+ t.Errorf("Clear wrote %q, want the erase sequence", got)
+ }
+ if out := redraw(r, buf); out != "" {
+ t.Errorf("draw after Clear wrote %q, want nothing", out)
+ }
+ clk.Advance(7 * time.Second)
+ buf.Reset()
+ r.Status("b")
+ if out := buf.String(); !strings.HasSuffix(out, "b · 0s") {
+ t.Errorf("Status after Clear: %q, want elapsed 0s", out)
+ }
+}
+
+func TestClearIdleWritesNothing(t *testing.T) {
+ r, buf, _ := newTest(t)
+ r.Clear()
+ if buf.String() != "" {
+ t.Errorf("Clear on idle reporter wrote %q", buf.String())
+ }
+}
+
+func TestStatusKeepsElapsedResetsPhase(t *testing.T) {
+ r, buf, clk := newTest(t)
+ r.Status("one")
+ r.Observer()(llm.Event{Phase: llm.PhaseDelta, Text: "xyz"})
+ clk.Advance(4 * time.Second)
+ r.Status("two")
+ out := redraw(r, buf)
+ if strings.Contains(out, "receiving") || !strings.HasSuffix(out, " two · 4s") {
+ t.Errorf("got %q, want phase reset and elapsed 4s", out)
+ }
+ r.Observer()(llm.Event{Phase: llm.PhaseDelta, Text: "q"})
+ if out := redraw(r, buf); !strings.Contains(out, "receiving · 1 chars") {
+ t.Errorf("char count not reset by Status: %q", out)
+ }
+}
+
+func TestDeltaCountsRunes(t *testing.T) {
+ r, buf, _ := newTest(t)
+ r.Status("x")
+ obs := r.Observer()
+ obs(llm.Event{Phase: llm.PhaseDelta, Text: "ab"})
+ obs(llm.Event{Phase: llm.PhaseDelta, Text: "cdé"})
+ if out := redraw(r, buf); !strings.Contains(out, "receiving · 5 chars") {
+ t.Errorf("got %q, want 5 chars", out)
+ }
+}
+
+func TestTruncate(t *testing.T) {
+ t.Setenv("COLUMNS", "40")
+ r, buf, _ := newTest(t)
+ r.Status(strings.Repeat("é", 200))
+ out := redraw(r, buf)
+ line := strings.TrimPrefix(out, "\r\x1b[K")
+ if n := utf8.RuneCountInString(line); n != 39 {
+ t.Errorf("line is %d runes, want 39", n)
+ }
+ if strings.Count(out, "\r") != 1 {
+ t.Errorf("want exactly one redraw in %q", out)
+ }
+}
+
+func TestWidthFallback(t *testing.T) {
+ for _, v := range []string{"", "abc", "0", "-5"} {
+ t.Setenv("COLUMNS", v)
+ if got := width(); got != 80 {
+ t.Errorf("COLUMNS=%q: width %d, want 80", v, got)
+ }
+ }
+}
+
+func TestLoopDrawsOnTick(t *testing.T) {
+ buf := &syncBuf{}
+ clk := &fakeClock{t: time.Unix(0, 0)}
+ r := newReporter(buf, time.Millisecond, clk.Now)
+ defer r.Stop()
+ r.Status("tick")
+ deadline := time.Now().Add(2 * time.Second)
+ for strings.Count(buf.String(), "\r\x1b[K") < 3 {
+ if time.Now().After(deadline) {
+ t.Fatalf("goroutine never redrew: %q", buf.String())
+ }
+ time.Sleep(time.Millisecond)
+ }
+}
+
+func TestStopEndsGoroutine(t *testing.T) {
+ buf := &syncBuf{}
+ r := newReporter(buf, time.Millisecond, time.Now)
+ r.Status("x")
+ select {
+ case <-r.done:
+ t.Fatal("goroutine ended before Stop")
+ default:
+ }
+ r.Stop()
+ select {
+ case <-r.done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("Stop left the goroutine running")
+ }
+ if !strings.HasSuffix(buf.String(), "\r\x1b[K") {
+ t.Errorf("Stop did not clear the line: %q", buf.String())
+ }
+}
+
+func TestStopLeavesNoGoroutine(t *testing.T) {
+ before := runtime.NumGoroutine()
+ for i := 0; i < 20; i++ {
+ r := newReporter(&syncBuf{}, time.Millisecond, time.Now)
+ r.Status("x")
+ r.Stop()
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for runtime.NumGoroutine() > before {
+ if time.Now().After(deadline) {
+ t.Fatalf("goroutines: %d before, %d after", before, runtime.NumGoroutine())
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+func TestStopTwiceAndStatusAfterStop(t *testing.T) {
+ buf := &syncBuf{}
+ r := newReporter(buf, time.Millisecond, time.Now)
+ r.Status("x")
+ r.Stop()
+ r.Stop() // must not panic on a double close
+
+ n := runtime.NumGoroutine()
+ buf.Reset()
+ r.Status("again")
+ r.Observer()(llm.Event{Phase: llm.PhaseStart})
+ r.Clear()
+ time.Sleep(20 * time.Millisecond)
+ if buf.String() != "" {
+ t.Errorf("drew after Stop: %q", buf.String())
+ }
+ if got := runtime.NumGoroutine(); got > n {
+ t.Errorf("Status after Stop started a goroutine: %d -> %d", n, got)
+ }
+}
+
+func TestStopWithoutStatus(_ *testing.T) {
+ r := newReporter(&syncBuf{}, time.Millisecond, time.Now)
+ r.Stop() // goroutine never started; must not block
+ r.Stop()
+}
+
+func TestObserverConcurrent(t *testing.T) {
+ r := newReporter(&syncBuf{}, time.Millisecond, time.Now)
+ defer r.Stop()
+ r.Status("x")
+ obs := r.Observer()
+ var wg sync.WaitGroup
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for j := 0; j < 100; j++ {
+ obs(llm.Event{Phase: llm.PhaseDelta, Text: "ab"})
+ }
+ }()
+ }
+ wg.Wait()
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.chars != 1600 {
+ t.Errorf("chars = %d, want 1600", r.chars)
+ }
+}
diff --git a/internal/verbs/briefverb/command.go b/internal/verbs/briefverb/command.go
index 4f8748f..439ec44 100644
--- a/internal/verbs/briefverb/command.go
+++ b/internal/verbs/briefverb/command.go
@@ -14,6 +14,7 @@ import (
"github.com/procrastivity/clast/internal/iostreams"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/progress"
"github.com/procrastivity/clast/internal/query"
"github.com/procrastivity/clast/internal/surface"
briefplumbing "github.com/procrastivity/clast/internal/verbs/brief"
@@ -119,8 +120,19 @@ func Command(streams *iostreams.Streams) *cobra.Command {
return err
}
+ // Status line and call phases while Synthesize waits. Built only
+ // here, past the empty stop and a good client, so an empty brief
+ // never creates one; a nil reporter (progress off) makes every
+ // call below a no-op.
+ rep := progress.New(streams, flags)
+ defer rep.Stop()
+ rep.Status("synthesizing brief · " + result.ProjectSlug)
+
// flows/brief.md §3 — synthesize the working brief.
- text, err := Synthesize(ctx, result, client)
+ text, err := Synthesize(llm.WithObserver(ctx, rep.Observer()), result, client)
+ // Clear before any output or error return, so neither lands on
+ // a half-drawn status line.
+ rep.Clear()
if err != nil {
return err
}
diff --git a/internal/verbs/retroverb/command.go b/internal/verbs/retroverb/command.go
index 128ae40..2a44b5d 100644
--- a/internal/verbs/retroverb/command.go
+++ b/internal/verbs/retroverb/command.go
@@ -13,6 +13,7 @@ import (
"github.com/procrastivity/clast/internal/iostreams"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/progress"
"github.com/procrastivity/clast/internal/retrocache"
"github.com/procrastivity/clast/internal/surface"
retroplumbing "github.com/procrastivity/clast/internal/verbs/retro"
@@ -98,7 +99,12 @@ func Command(streams *iostreams.Streams) *cobra.Command {
return clasterr.New("validation.config", fmt.Sprintf("resolving retro cache directory: %v", err))
}
- summaries, stats, err = Summarize(ctx, result, client, cacheDir, refresh)
+ // Counter on stderr while the summaries run; nil (a no-op)
+ // when stderr is not a terminal or --json is set.
+ rep := progress.New(streams, flags)
+ defer rep.Stop()
+
+ summaries, stats, err = Summarize(progress.WithReporter(ctx, rep), result, client, cacheDir, refresh)
if err != nil {
return err
}
diff --git a/internal/verbs/retroverb/retroverb.go b/internal/verbs/retroverb/retroverb.go
index 2b8afa5..39a5e93 100644
--- a/internal/verbs/retroverb/retroverb.go
+++ b/internal/verbs/retroverb/retroverb.go
@@ -32,6 +32,7 @@ import (
"github.com/procrastivity/clast/internal/clasterr"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/progress"
"github.com/procrastivity/clast/internal/prompt"
"github.com/procrastivity/clast/internal/retrocache"
retroplumbing "github.com/procrastivity/clast/internal/verbs/retro"
@@ -132,6 +133,14 @@ func Summarize(ctx context.Context, result retroplumbing.Result, client *llm.Cli
ctx, cancel := context.WithCancel(ctx)
defer cancel()
+ // The status line shows a done/total counter only: four workers run at
+ // once, so attaching the reporter's phase observer would mix their
+ // phases. A nil reporter (progress off) makes every call a no-op.
+ rep := progress.FromContext(ctx)
+ defer rep.Clear()
+ total := len(jobs)
+ rep.Status(statusLabel(0, total, 0))
+
var (
mu sync.Mutex
summaries = map[string]string{}
@@ -161,6 +170,9 @@ func Summarize(ctx context.Context, result retroplumbing.Result, client *llm.Cli
summaries[j.row.Item.Key.DirName()] = text
stats.Requests++
}
+ if err == nil {
+ rep.Status(statusLabel(stats.CacheHits+stats.Requests, total, stats.CacheHits))
+ }
mu.Unlock()
}
}()
@@ -185,6 +197,16 @@ dispatch:
return summaries, stats, nil
}
+// statusLabel renders Summarize's status line text. The cached part is
+// omitted while no job has been served from the cache.
+func statusLabel(done, total, cached int) string {
+ label := fmt.Sprintf("summarizing %d/%d", done, total)
+ if cached > 0 {
+ label += fmt.Sprintf(" · %d cached", cached)
+ }
+ return label
+}
+
// summarizeConcurrency caps Summarize's in-flight endpoint requests: enough
// to cut a cold window's wall time several-fold, few enough to stay polite
// to a local or rate-limited endpoint.
diff --git a/internal/verbs/retroverb/retroverb_test.go b/internal/verbs/retroverb/retroverb_test.go
index ec96d44..17089d4 100644
--- a/internal/verbs/retroverb/retroverb_test.go
+++ b/internal/verbs/retroverb/retroverb_test.go
@@ -12,11 +12,14 @@ import (
"time"
"github.com/procrastivity/clast/internal/clasterr"
+ "github.com/procrastivity/clast/internal/cliflags"
"github.com/procrastivity/clast/internal/config"
"github.com/procrastivity/clast/internal/entry"
+ "github.com/procrastivity/clast/internal/iostreams"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/llm"
"github.com/procrastivity/clast/internal/llm/llmtest"
+ "github.com/procrastivity/clast/internal/progress"
retroplumbing "github.com/procrastivity/clast/internal/verbs/retro"
"github.com/procrastivity/clast/internal/verbs/retroverb"
)
@@ -339,6 +342,62 @@ func TestSummarize_ManyEntries_AllSummarized(t *testing.T) {
}
}
+// TestSummarize_NoReporter_Succeeds covers the nil-reporter path, which is
+// the e2e path: a context with no reporter must summarize as before.
+func TestSummarize_NoReporter_Succeeds(t *testing.T) {
+ stub := llmtest.New(t, "- Shipped: something")
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ client, err := llm.NewClient(cfgWith(stub.URL(), "gpt-test"))
+ if err != nil {
+ t.Fatalf("llm.NewClient: %v", err)
+ }
+
+ result := oneEntryResult(journal.Day("2026-09-11"), "body")
+ summaries, stats, err := retroverb.Summarize(context.Background(), result, client, t.TempDir(), false)
+ if err != nil {
+ t.Fatalf("Summarize: %v", err)
+ }
+ if len(summaries) != 1 || stats.Requests != 1 {
+ t.Errorf("got %d summaries, stats %+v; want 1 summary, 1 request", len(summaries), stats)
+ }
+}
+
+// TestSummarize_WithReporter_Succeeds runs Summarize with a live reporter
+// (stderr on /dev/null, a character device) over a cold run and a cached
+// run, under -race, to cover the reporter calls from the worker goroutines.
+func TestSummarize_WithReporter_Succeeds(t *testing.T) {
+ stub := llmtest.New(t, "- Shipped: something")
+ t.Setenv("CLAST_LLM_API_KEY", "sk-test-key")
+ t.Setenv("TERM", "xterm")
+ client, err := llm.NewClient(cfgWith(stub.URL(), "gpt-test"))
+ if err != nil {
+ t.Fatalf("llm.NewClient: %v", err)
+ }
+ null, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
+ if err != nil {
+ t.Fatalf("open %s: %v", os.DevNull, err)
+ }
+ defer func() { _ = null.Close() }()
+ rep := progress.New(&iostreams.Streams{Err: null}, cliflags.Flags{})
+ if rep == nil {
+ t.Skip("/dev/null is not a character device here")
+ }
+ defer rep.Stop()
+ ctx := progress.WithReporter(context.Background(), rep)
+
+ result := oneEntryResult(journal.Day("2026-09-11"), "body")
+ cacheDir := t.TempDir()
+ for i, wantHits := range []int{0, 1} {
+ _, stats, err := retroverb.Summarize(ctx, result, client, cacheDir, false)
+ if err != nil {
+ t.Fatalf("Summarize (run %d): %v", i, err)
+ }
+ if stats.CacheHits != wantHits {
+ t.Errorf("run %d stats = %+v, want %d cache hit(s)", i, stats, wantHits)
+ }
+ }
+}
+
// TestSummarize_LLMRequestFailure_WrapsAsRetroCode confirms a failed
// request surfaces as retro.llm-request-failed (mirroring briefverb's own
// TestSynthesize_LLMRequestFailure_WrapsAsBriefCode) — this code had no
diff --git a/internal/verbs/wakeverb/auto.go b/internal/verbs/wakeverb/auto.go
index 9645862..21b0222 100644
--- a/internal/verbs/wakeverb/auto.go
+++ b/internal/verbs/wakeverb/auto.go
@@ -9,6 +9,7 @@ import (
"github.com/procrastivity/clast/internal/iostreams"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/progress"
"github.com/procrastivity/clast/internal/verbs/curate"
wakeplumbing "github.com/procrastivity/clast/internal/verbs/wake"
)
@@ -43,8 +44,20 @@ func RunAuto(ctx context.Context, streams *iostreams.Streams, root string, cutof
var summary Summary
summary.Considered = len(rows)
- for _, row := range rows {
- raw, err := Draft(ctx, root, cutoff, yesterday, row.Item, client)
+ // Status line and call phases while each draft runs; a nil reporter
+ // (progress off) makes every call below a no-op.
+ rep := progress.FromContext(ctx)
+
+ for i, row := range rows {
+ project := unprojectedLabel
+ if row.Item.Session.Project != nil {
+ project = row.Item.Session.Project.Slug
+ }
+ rep.Status(fmt.Sprintf("drafting %d/%d · %s", i+1, len(rows), project))
+ raw, err := Draft(llm.WithObserver(ctx, rep.Observer()), root, cutoff, yesterday, row.Item, client)
+ // Clear before any stderr write, so the diagnostic below never
+ // lands on a half-drawn status line.
+ rep.Clear()
if err != nil {
// A draft that fails to generate is skipped, not retried —
// there is no reviewer to ask in Auto mode (the flow's own
diff --git a/internal/verbs/wakeverb/auto_test.go b/internal/verbs/wakeverb/auto_test.go
index 5c69f33..810d571 100644
--- a/internal/verbs/wakeverb/auto_test.go
+++ b/internal/verbs/wakeverb/auto_test.go
@@ -3,16 +3,19 @@ package wakeverb_test
import (
"bytes"
"context"
+ "os"
"strings"
"testing"
"time"
+ "github.com/procrastivity/clast/internal/cliflags"
"github.com/procrastivity/clast/internal/entry"
"github.com/procrastivity/clast/internal/iostreams"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/journal/journaltest"
"github.com/procrastivity/clast/internal/llm"
"github.com/procrastivity/clast/internal/llm/llmtest"
+ "github.com/procrastivity/clast/internal/progress"
wakeplumbing "github.com/procrastivity/clast/internal/verbs/wake"
"github.com/procrastivity/clast/internal/verbs/wakeverb"
)
@@ -245,6 +248,52 @@ func TestRunAuto_DraftFailure_PrintsDiagnosticAndCountsSeparately(t *testing.T)
}
}
+// TestRunAuto_WithReporter_DiagnosticStillPrints runs RunAuto with a live
+// reporter (a character device standing in for the terminal, under -race
+// for the observer's calls from the HTTP goroutines) over a failing draft:
+// the run, the summary, and the stderr diagnostic on the separate Err
+// stream must match the reporter-off case.
+func TestRunAuto_WithReporter_DiagnosticStillPrints(t *testing.T) {
+ fx := journaltest.New(t)
+ key := journal.SessionKey{Harness: "claude", NativeID: "draft-fail-rep"}
+ started := time.Date(2026, 9, 11, 9, 0, 0, 0, time.UTC)
+ fx.Captured("2026-09-11", key, journal.TranscriptFingerprint{Format: "claude-jsonl", Lines: 1, SHA256: "a"}, started).
+ WithTranscript("2026-09-11", key, []byte(`{"type":"user","uuid":"u1","message":{"content":"hi"}}`+"\n"))
+
+ stub := llmtest.New(t, "unused")
+ stub.Fail(500, `{"error":"boom"}`)
+ client := mustClient(t, stub.URL())
+ t.Setenv("TERM", "xterm")
+
+ null, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
+ if err != nil {
+ t.Fatalf("open %s: %v", os.DevNull, err)
+ }
+ defer func() { _ = null.Close() }()
+ rep := progress.New(&iostreams.Streams{Err: null}, cliflags.Flags{})
+ if rep == nil {
+ t.Skip("/dev/null is not a character device here")
+ }
+ defer rep.Stop()
+ ctx := progress.WithReporter(context.Background(), rep)
+
+ rows, err := wakeplumbingRun(t, fx.Root())
+ if err != nil {
+ t.Fatalf("wake.Run: %v", err)
+ }
+ streams, errBuf := autoStreams()
+ summary, err := wakeverb.RunAuto(ctx, streams, fx.Root(), mustCutoff(t), journal.Day("2026-09-10"), rows, client, 60)
+ if err != nil {
+ t.Fatalf("RunAuto: %v", err)
+ }
+ if summary.SkippedDraftFailed != 1 {
+ t.Fatalf("summary = %+v, want 1 draft-failed skip", summary)
+ }
+ if !strings.Contains(errBuf.String(), "draft generation failed") {
+ t.Errorf("stderr = %q, want the draft-generation-failed diagnostic", errBuf.String())
+ }
+}
+
// wakeplumbingRun is a thin wrapper over internal/verbs/wake's own Run
// (no --since restriction) — every test in this file needs the exact
// same working-set rows RunAuto/RunInteractive consume in production.
diff --git a/internal/verbs/wakeverb/command.go b/internal/verbs/wakeverb/command.go
index 61fadf7..803ae6d 100644
--- a/internal/verbs/wakeverb/command.go
+++ b/internal/verbs/wakeverb/command.go
@@ -13,6 +13,7 @@ import (
"github.com/procrastivity/clast/internal/iostreams"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/progress"
"github.com/procrastivity/clast/internal/query"
"github.com/procrastivity/clast/internal/surface"
wakeplumbing "github.com/procrastivity/clast/internal/verbs/wake"
@@ -111,6 +112,13 @@ func Command(streams *iostreams.Streams) *cobra.Command {
return err
}
+ // Status line on stderr while drafts run; nil (a no-op) when
+ // stderr is not a terminal or --json is set. Put in ctx before
+ // the mode branch so RunAuto and RunInteractive both read it.
+ rep := progress.New(streams, flags)
+ defer rep.Stop()
+ ctx = progress.WithReporter(ctx, rep)
+
var summary Summary
if auto {
summary, err = RunAuto(ctx, streams, root, cutoff, yesterday, rows, client, autoMinChars)
diff --git a/internal/verbs/wakeverb/interactive.go b/internal/verbs/wakeverb/interactive.go
index d08b9b0..4a211be 100644
--- a/internal/verbs/wakeverb/interactive.go
+++ b/internal/verbs/wakeverb/interactive.go
@@ -13,6 +13,7 @@ import (
"github.com/procrastivity/clast/internal/iostreams"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/llm"
+ "github.com/procrastivity/clast/internal/progress"
"github.com/procrastivity/clast/internal/verbs/curate"
"github.com/procrastivity/clast/internal/verbs/dismiss"
wakeplumbing "github.com/procrastivity/clast/internal/verbs/wake"
@@ -62,6 +63,10 @@ func RunInteractive(ctx context.Context, streams *iostreams.Streams, root string
scanner := bufio.NewScanner(streams.In)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ // Status line and call phases while each draft runs; a nil reporter
+ // (progress off) makes every call below a no-op.
+ rep := progress.FromContext(ctx)
+
for i, row := range rows {
label := unprojectedLabel
if row.Item.Session.Project != nil {
@@ -72,7 +77,12 @@ func RunInteractive(ctx context.Context, streams *iostreams.Streams, root string
return summary, err
}
- raw, err := Draft(ctx, root, cutoff, yesterday, row.Item, client)
+ rep.Status("drafting · " + label)
+ raw, err := Draft(llm.WithObserver(ctx, rep.Observer()), root, cutoff, yesterday, row.Item, client)
+ // Clear before any stderr write (the diagnostic below, or the draft
+ // and menu in disposition), so none lands on a half-drawn status
+ // line.
+ rep.Clear()
if err != nil {
if _, werr := fmt.Fprintf(streams.Err, " draft generation failed: %v — skipping\n", err); werr != nil {
return summary, werr
@@ -151,7 +161,16 @@ func disposition(ctx context.Context, streams *iostreams.Streams, scanner *bufio
summary.Skipped++
return false, nil
}
- revised, err := DraftWithFeedback(ctx, root, cutoff, yesterday, item, client, feedback)
+ label := unprojectedLabel
+ if item.Session.Project != nil {
+ label = item.Session.Project.Slug
+ }
+ rep := progress.FromContext(ctx)
+ rep.Status("redrafting · " + label)
+ revised, err := DraftWithFeedback(llm.WithObserver(ctx, rep.Observer()), root, cutoff, yesterday, item, client, feedback)
+ // Clear before the diagnostic below or the next loop
+ // iteration's draft reprint writes to stderr.
+ rep.Clear()
if err != nil {
if _, werr := fmt.Fprintf(streams.Err, " draft generation failed: %v — skipping\n", err); werr != nil {
return false, werr
diff --git a/internal/verbs/wakeverb/interactive_test.go b/internal/verbs/wakeverb/interactive_test.go
index 56aa969..9e69879 100644
--- a/internal/verbs/wakeverb/interactive_test.go
+++ b/internal/verbs/wakeverb/interactive_test.go
@@ -7,15 +7,20 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "os"
+ "reflect"
+ "regexp"
"strings"
"sync"
"testing"
"time"
+ "github.com/procrastivity/clast/internal/cliflags"
"github.com/procrastivity/clast/internal/iostreams"
"github.com/procrastivity/clast/internal/journal"
"github.com/procrastivity/clast/internal/journal/journaltest"
"github.com/procrastivity/clast/internal/llm/llmtest"
+ "github.com/procrastivity/clast/internal/progress"
"github.com/procrastivity/clast/internal/verbs/wakeverb"
)
@@ -27,6 +32,9 @@ import (
// exactly that: a first draft, then a distinguishable regenerated one.
type sequencedStub struct {
responses []string
+ // failFrom, when > 0, answers every request from that zero-based index
+ // on with a 500.
+ failFrom int
srv *httptest.Server
mu sync.Mutex
@@ -76,7 +84,12 @@ func (s *sequencedStub) handle(w http.ResponseWriter, r *http.Request) {
if idx < len(s.responses) {
resp = s.responses[idx]
}
+ failing := s.failFrom > 0 && idx >= s.failFrom
s.mu.Unlock()
+ if failing {
+ http.Error(w, `{"error":"boom"}`, http.StatusInternalServerError)
+ return
+ }
var out struct {
Choices []struct {
@@ -485,3 +498,62 @@ func TestRunInteractive_Promotion_FoldsSectionIntoEntry(t *testing.T) {
}
_ = key
}
+
+// TestRunInteractive_WithReporter_OutputUnchanged runs the Edit flow, and
+// an Edit whose regeneration fails, with a live reporter (a character
+// device standing in for the terminal, under -race for the observer's calls
+// from the HTTP goroutines): the draft, menu, and diagnostic bytes on the
+// separate Err stream must match the reporter-off run exactly.
+func TestRunInteractive_WithReporter_OutputUnchanged(t *testing.T) {
+ t.Setenv("TERM", "xterm")
+ null, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
+ if err != nil {
+ t.Fatalf("open %s: %v", os.DevNull, err)
+ }
+ defer func() { _ = null.Close() }()
+ rep := progress.New(&iostreams.Streams{Err: null}, cliflags.Flags{})
+ if rep == nil {
+ t.Skip("/dev/null is not a character device here")
+ }
+ defer rep.Stop()
+
+ stubPort := regexp.MustCompile(`127\.0\.0\.1:\d+`)
+ run := func(ctx context.Context, failRedraft bool) (string, wakeverb.Summary) {
+ started := time.Date(2026, 9, 11, 9, 0, 0, 0, time.UTC)
+ root, _ := oneSessionFixture(t, "int-rep", started)
+ rows, err := wakeplumbingRun(t, root)
+ if err != nil {
+ t.Fatalf("wake.Run: %v", err)
+ }
+ stub := newSequencedStub(t, interactiveDraft, editedWakeDraft)
+ if failRedraft {
+ stub.failFrom = 1
+ }
+ client := mustClient(t, stub.URL())
+ errBuf := &bytes.Buffer{}
+ streams := &iostreams.Streams{In: strings.NewReader("2\nshorter\n4\n"), Out: &bytes.Buffer{}, Err: errBuf}
+ summary, err := wakeverb.RunInteractive(ctx, streams, root, mustCutoff(t), journal.Day("2026-09-10"), rows, client, "framework")
+ if err != nil {
+ t.Fatalf("RunInteractive: %v", err)
+ }
+ // Each run has its own stub server; mask the port in diagnostics.
+ return stubPort.ReplaceAllString(errBuf.String(), "127.0.0.1:PORT"), summary
+ }
+
+ for _, failRedraft := range []bool{false, true} {
+ want, wantSum := run(context.Background(), failRedraft)
+ got, gotSum := run(progress.WithReporter(context.Background(), rep), failRedraft)
+ if got != want {
+ t.Errorf("failRedraft=%v: stderr with reporter differs:\n got: %q\nwant: %q", failRedraft, got, want)
+ }
+ if !reflect.DeepEqual(gotSum, wantSum) {
+ t.Errorf("failRedraft=%v: summary = %+v, want %+v", failRedraft, gotSum, wantSum)
+ }
+ if failRedraft && !strings.Contains(got, "draft generation failed") {
+ t.Errorf("stderr = %q, want the draft-generation-failed diagnostic", got)
+ }
+ if strings.Contains(got, "\x1b[K") || strings.Contains(got, "drafting ·") {
+ t.Errorf("stderr = %q, want no status text in the verb's own stream", got)
+ }
+ }
+}