Repository navigation
feat(content): write the Content Agent's runs step by step and stop them (CE-027, CE-035, server) - #1400
Conversation
The workspace's one AI budget (Improve, the Content Editor's AI and the Action Center's task writer) had no meter: the first sign of it was an "AI usage is used up" error. Migration 00242 records what each AI call was for (prompt_improve_usage.feature, backfilled) and sums the period's spend by feature (ai_usage_by_feature). GET /api/billing/ai-usage returns the shares of the plan's budget, and the Billing page shows the share used, when it resets and what used it, with Agent Chat noted as running on the workspace's own key. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The workspace's AI budget was checked by reading the period's spend; the call's cost was written once the model answered. Calls running at once (two tabs, a teammate, an Action Center sweep) all read the same spend and all ran past the budget. 00243's reserve_ai_usage takes a per-organization lock, reads the spend with the calls in flight, and holds the call's estimated cost; reserveAiBudget turns the hold into the real cost or releases it. Improve, the brief rebuild, Apply rules with Agent, Start Agent and the Action Center task writer use it in place of enforceImproveQuota, which goes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: - Apply rules with Agent and Start Agent charge an answer the provider billed but that missed the schema (NoObjectGeneratedError), as Improve, the brief and the task writer do; before, the hold was let go and the call ran free. - A call holds the org's median cost over its last 20 calls this period, never less than the model's typical cost, so calls in flight pass the budget by far less. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apply rules with Agent makes at most 8 small edits a run, which can't bring a long page to its Length (about 2% a run on prod). The Content Agent can now rewrite the whole page in one background call, left as ONE suggestion (kind 'page', migration 00247) to compare and accept or reject: - POST /api/content-drafts/:draftId/rewrite, through Start Agent's claim, budget hold and background run; - passages AI quotes today, tables, images, quotes and HTML blocks go to the model as [[KEEP n]] lines and come back as they were; a rewrite that drops one fails the run; - one H1, only the page's own links and the ones offered, the editor's tags; the page as it was is kept on the suggestion (before_html). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Length Review fixes: - Kept blocks are described under the page (a quoted passage's words, a table's rows, an image's alt) and their text counts toward Length, so a rewrite aims at the whole page's length; with Length off it keeps the page's own. A kept H1 stays first, and the page's language is kept. - The answer is taken out of a code fence, text left at its root goes in paragraphs, and an answer in Markdown fails the run. - The page's own links stay exactly as written (query and anchor too). - Kept blocks go back untouched (an empty table cell stays), only the page's first H1 counts as its title, a page that writes "[[KEEP" gets markers of its own, and a page that is only kept blocks isn't sent. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…compare it The Rules tab opens with the agent's two ways to meet its rules: Apply rules with Agent (small edits, up to 8 a run) and Rewrite the page to these rules (the whole page as one change). The rewrite is recommended, with a one-line reason, when the page is more than 30% off its Length or 4 rules or more are open. A rewritten page comes back as one suggestion with its own bar over the page: the characters before and after and the agent's reason, Compare (the page and the rewrite side by side), Accept (History keeps the page first), Reject, and Undo. A page that changed since the agent read it isn't written over. The page waits for the rewrite with its own steps, and a failed rewrite's Try again rewrites again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: - A page is compared with the one the agent read by its words, with a space between blocks, so stored line breaks and lists don't read as a change (Accept and Undo were refused on imported pages). - One agent run at a time from the page; a rewrite never starts before the locked passages are read, and sends the editor's own locked keys. - Accept holds the page still from the start and checks it again before putting the rewrite in; Undo puts the page back as it was (two H1s too), and the bar waits while the HTML view is open. - No rewrite advice for an empty page or one too long to send whole; the rewrite mark survives a reload; the waiting view says the rewrite waits in the editor; Compare's links don't navigate. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor v1.1, part 1 (CE-025, CE-026, §4): the agent row and the
rewrite bar become one card above the toolbar, in three states:
- waiting: "Content Agent has {n} suggestions for you", what they change
and the rules they gain ("Rules 5 → 6 of 13"), with Review (scrolls to
the first suggestion and marks it), Reject all and Accept all; a page
rewritten shows its characters, with Compare;
- all reviewed: what was accepted and the rules met and still open, with
Undo all and Run Agent;
- working: while Apply rules with Agent runs.
The tile moves a little (a soft ring, a blink, a spark; a sweep and a
breath while working), never a rotating ring, and not at all with reduced
motion. The card wraps on a narrow page; Accept all and Run Agent are the
primary buttons.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Run Agent on the card keeps to one agent run at a time and says why it waits; Apply rules never starts beside another run or before the locked passages are read. - Ghost buttons show their hover on the card's grey; the tile and its count are hidden from screen readers (the title says it) and the count is darker for contrast; "+N more" comes from en.json, the reason's first letter is upper-cased in the page's locale. - Review picks the first open suggestion in the page's order and focuses it; the sweep shows on the light tile in dark mode; the spark is slower once all are reviewed; without motion the working line is a faint full line; "0 still open" isn't said. - globals.css keeps its own lines; only the motion block is added. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…split Run Agent Content Editor v1.1 part 2 (CE-028–CE-031): the side panel's tabs become Instructions · Sources · Live page. Instructions holds Brief | Rules, with the rules still open on the tab and the segment. Each segment opens with a status card: Rules has one split Run Agent ▾ (Fix open rules, or Rewrite the whole page, which renames it "Rewrite page") in place of the two rule buttons; Brief has Run Agent while empty and Rebuild brief once written. Why the agent can't run is written under the card, and each card's ⓘ tip opens below it. The brief shows "Not set yet" and its Length in characters and about as many words; the toolbar counter adds the page's words. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Run Agent's choice is worked out once and falls back to Fix without a rewrite; once a rewrite starts, the button is back on Fix. - ▾'s choices are menu radio items; Fix is off when only rules the agent can't fix are open, and the card says what to do instead. - The reason line under the card stays mounted for screen readers; Rewrite from brief writes its reason too; the tab's count is read out. - Brief | Rules switch with the arrow keys, one tab stop. - An edited brief's rebuild question sits under the card; a brief without H2s says to rebuild it; an empty brief shows no origin line. - Plural copy for the open suggestions and the counter's words; rule names joined by the formatter; Run Agent's tip leaves ▾ out without a rewrite. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor v1.1 part 3 (CE-032, CE-034): under each Run Agent card, "Uses your data: 1 prompt · 21 fan-outs · 20 cited pages · 10 Search Console queries · Edit sources", counted as the Sources tab keeps them, so turning one off lowers it at once. The Sources tab carries its count, and its top says "N sources in use" and when the Content Agent last wrote from them (its latest suggestions or the brief it built). A first visit's note at the top of Instructions says the agent writes from the person's data; closing it is kept in their own user metadata. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- "Last used by Content Agent" also counts the agent writing the page (agent_state_at: Start with Agent, Rewrite from brief on a new page), not a run that failed; a value that isn't a date is skipped. - The latest batch's time is its first suggestion's, not a sort per render. - Tests: the Brief segment's line, no line while the sources can't be read, the tab's count, the note showing again after a failed write, and a suggestion read with its createdAt. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… name them Content Editor v1.1, CE-033 (server): Fix open rules, Start with Agent and Rewrite the whole page read the sources the Sources tab keeps, numbered S1, S2… (content-sources.js). Each suggestion keeps the sources it names and the words each supports (content_draft_suggestions.sources and source_marks, 00248); a page rewritten whole keeps its sources. No number without a source: the model reads a source by its words only, so a number the agent adds must be the page's, the brand's, the brief's, the rules', today's, or in a source's own words (then marked to it). A suggestion with any other number is not kept; a page written whole gets a placeholder in its place. Source numbers written into the words are taken out. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor v1.1, CE-033 (web) and the rest of CE-034: under each suggestion, "Based on" chips name the sources it used (number, kind, name; the Sources tab's details on hover), and a small number marks the words each supports. A click on either opens Sources on that row, scrolled to and ringed for a moment, once. The agent card adds "built from N of your sources · See sources". Fix open rules sends the kept sources, and the first-visit note says every change shows the sources it used. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor v1.1, CE-027/035 (server): each Content Agent run (Fix open
rules, Start with Agent, Rewrite the whole page, the brief) is written in
content_agent_runs (00249) with its steps named by the data it reads
("Reading 20 cited pages", "Matching 21 fan-outs", "Writing 3 changes") as
it reaches them. POST /api/content-drafts/:id/stop marks the run stopped
and aborts its model call; the run checks before it keeps anything, so a
stopped run changes nothing (no suggestions, page, brief or History).
A run that can't be written still runs; runs a stopped server left are
closed when the next starts, and Stop ignores them. Background runs are
written before Start answers, so Stop finds them at once.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk CE-027/035 server half. Stacked on #1399. Migration 00249 adds a
Worth a look:
Deploy: 00249 → server → web. The web PR comes next and is stacked on this one. Checks: server lint and 2,154 tests. |
Stop also clears the draft's 'writing' state at once: a background run lets go once it sees the stop, but one no server holds any more never would, and the waiting page would wait out the 10 minutes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk
left a comment
There was a problem hiding this comment.
A few fixes before merge:
-
A call stopped while it is out isn't charged. On Stop,
callSignalabortsgenerateObject. Nothing callsbudget.charge, and thefinallyreleases the hold (server/src/lib/content-agent.js:651-662,server/src/lib/content-brief.js:218-228,server/src/lib/content-writer.js:595-617). These are non-streaming requests: aborting our side of the connection doesn't stop the provider from finishing the call and billing it, so the budget misses that call's cost. When the run's own Stop aborts a call that was already sent, keep the hold as the charge. One way to do it:- add a
keep()to thereserveAiBudgethandle (server/src/lib/plan-guard.js:399-431) that marks the hold charged, sorelease()leaves the row at the hold's cost; - call
keep()in the stop branch; - add
await stopIfStopped(run)right before eachgenerateObject, so a run stopped before its call still releases the hold.
Simpler alternative: don't abort the call on Stop. Let it finish, charge its usage, and drop the result at
stopIfStopped, which is already what happens when the stop is made on another server. Either way, add a test where a Stop during the call leaves aprompt_improve_usagerow. (The call's own timeout has the same gap, but that predates this PR.) - add a
-
A stopped background run can clear a newer run's claim. The Stop route frees the draft at once (
server/src/routes/content-drafts.js:202-211), so the person can press Start again right away. A run stopped from another server instance isn't aborted, though. It only sees the stop when its call returns, up to 3 minutes later. Thenfinish(draft.id, { agent_state: null })(server/src/lib/content-writer.js:604) matches the new run's'writing'claim and clears it. After that, the new run's ownfinish(..., { openOnly: true })misses, so it drops its page or suggestions after they were charged, and another Start can claim the draft in the meantime. The same can happen with an old run whose Stop lands just after its laststopIfStopped. Tiefinishto the run's own claim: keep theagent_state_atthat the claim writes (server/src/lib/content-writer.js:420), pass it into the run, and add.eq('agent_state_at', claimedAt)tofinish(server/src/lib/content-writer.js:452-462). -
(low)
startRuncloses runs that are still going (server/src/lib/content-runs.js:85-94). It marks every unfinished run on the draftfailed, not only runs a stopped server left behind. Say a brief is rebuilt from a second tab, or by another member, while Fix runs. The Fix run is closed: its steps stop moving, and Stop can't reach it any more (stopDraftRunskips finished runs), so its suggestions still land after Stop. #1401 blocks Rebuild in the same editor, but not across tabs. Only close runs started beforenow - RUN_STALE_MS, the window Stop already uses. Stop then stops every run going on the draft.
Merge note: apply 00249 before the server deploy that carries this PR. Without the table, /stop answers 502; runs still work but log two warnings each. #1401 reads the table from the web, so 00249 must also be on prod before #1401 merges.
Checked and fine:
- 00249: RLS is on, and members read runs only through drafts they can read, as with 00217. There are no write policies; only the server writes. The index covers the latest-run read, Stop's update and the close on start. Runs are deleted with their draft.
schema.sqlmatches.supabase.tsgets the table in #1401, where the web first reads it. /stopchecks brand access and the draft's brand before anything else. It only marks runs that are still going and under 10 minutes old.- Every run checks for a stop before it keeps anything: suggestions, page, rewrite, brief or History. A timeout is told apart from a stop.
- A call answered before the Stop is still charged, and so is a schema miss.
- A run that can't be written still runs. Progress is a few small writes per run, and runs are bounded by the AI budget, so the table needs no retention.
# Conflicts: # server/src/lib/content-writer.js # server/src/lib/content-writer.test.js # supabase/schema.sql
…le it writes
content_drafts.agent_run ('write' or 'rewrite', in 00247 and its guard) is
set when Start or a rewrite claims the draft, so every device knows a failed
rewrite from a failed Start. Fix open rules and the MCP suggest call answer
409 'writing' while a run holds the draft, so its answer is never dropped
after it was charged.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…le it writes
content_drafts.agent_run ('write' or 'rewrite', in 00247 and its guard) is
set when Start or a rewrite claims the draft, so every device knows a failed
rewrite from a failed Start. Fix open rules and the MCP suggest call answer
409 'writing' while a run holds the draft, so its answer is never dropped
after it was charged.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-steps-server Main squash-merged ansvisor#1389 and ansvisor#1393–ansvisor#1399; its tree is ansvisor#1399's last head (b84e724), so this is that merge: this branch's changes on top of it.
ansvisor#1400 adds the column to 00249. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk Fixed, and main merged. A Stop lets go only of the claim the stopped run holds.
Main merge. Main's tree is #1399's last head (b84e724), so the merge is that one: this branch's own changes on top of it. Nothing conflicted beyond the squash itself. Deploy note. A run started by a server older than this has no |
gkhngyk
left a comment
There was a problem hiding this comment.
Looks good. The fix from the last review is done (7f6a445).
A Stop lets go only of the claim the stopped run holds:
- A Start or Rewrite run is written with the claim it holds:
startWritingRungets the held draft, soclaimed_atis the sameagent_state_atthe claim wrote. Fix and the brief writenull. stopDraftRunreturns the runs it stopped, withid, claimed_at.- The route clears
agent_stateonce for each stopped run that has a claim, filtered onagent_state_at = claimed_at. Stopping a named Fix or brief run leaves a Start's claim alone. - With no
runId(an older editor), it still stops every live run on the draft and lets go of the Start's claim, as before. - The route is the only place a Stop lets go of a draft.
- Tests cover the route (a named Fix leaves the claim, and the existing stop test checks the filter), the stored claim and its return in
content-runs, and the writer (the run's claim is the draft's).
Merge commit 55fb571: main's tree is #1399's last head (b84e724). Merging 7f6a445 with b84e724 gives exactly 55fb571's tree, so it hides no changes. Against main, the PR's diff is its own 14 files only.
The PR merges cleanly on main (main is its parent).
Migration 00249:
claimed_at timestamptzis in thecreate table. Theadd column if not existscovers a database that ran the old file.schema.sqlmatches a rebuild from the migrations.- It isn't on prod. It only depends on
content_drafts, which 00250 and 00251 don't touch, so it applies cleanly on top of prod now. - Apply order:
- 00249;
- then the server deploy that carries this PR;
- then #1401's web.
Summary
Content Editor v1.1, CE-027 and CE-035 (server): every Content Agent run writes its steps as it reaches them, named by the data it reads, and Stop ends a run without changing anything.
Runs, step by step (
content-runs.js,content_agent_runs)read_pages20 →match_fanouts21 →check_queries10 →write_changes(its count once done)read_sources52 →rewrite_page14 rules →check_rulesread_sources→pick_fanouts→write_outlineread_sources→write_page→check_rulesstepon as it gets there, and endsdone,stoppedorfailed.content_drafts: a step written there would move the draft'supdated_at, which the editor's saves check against.failedwhen the next starts on the draft, and Stop ignores runs older than 10 minutes.Stop
POST /api/content-drafts/:draftId/stop{ brandId }:{ stopped }.409 stopped. A background run lets go of the draft (agent_stateback to null), notfailed.callSignal). A timeout ends asfailed, not stopped.outcomeis what happened. A Stop that lands after a run's last check may leavestopped_aton a run that endeddone(noted in the migration).After review (2026-10-23): a Stop that names a run lets go only of that run's own claim. The run row's new nullable
claimed_at(in 00249, withadd column if not existsfor a database that ran the old file) is compared withagent_state_at. A run started by an older server has noclaimed_at: a Stop doesn't release its claim, and the run releases it when it sees the stop, or it goes stale after 10 minutes.Related issue
Content Editor v1.1 (Drive spec, 2026-10-23): CE-027 and CE-035, server half. No GitHub issue.
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
content_agent_runsgets afixrow, itsstepmoves to 3 while the model writes, and it endsdonewithwrite_changes' count.POST /api/content-drafts/:id/stop. The run endsstopped, Fix answers409 stopped, and nothing is added.agent_statenull), its page and History unchanged.Tests:
content-runs.test.js:content-agent.test.js: Fix keeps nothing once stopped; the call it made is still charged.content-writer.test.js: Start stopped lets go, writes no page and adds no History.content-brief.test.js: the brief isn't saved once stopped.content-drafts.test.js:/stopfor the draft, refused for another brand's draft or a bad request, and Fix's409 stopped.Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdnpm run lintpasses (run fromserver/)npm testpasses (run fromserver/) — 2,154 testsbash supabase/build-schema.shrun,supabase/schema.sqlincluded🤖 Generated with Claude Code