Commit Graph
7 Commits
Author SHA1 Message Date
Davide Silvestri 74d6625a49 feat(assistant): run Kuma replies in the background (#6383)
* feat(assistant): stream Kuma background replies over HTTP

Behind assistant_background_runs, commit and enqueue the message then follow
Redis on the existing POST/200 cumulative JSON response. Resume the same run
without sending the prompt again. Keep refresh, multi-tab discovery, onboarding
and durable outcome recovery in the Kuma adapter and UI integration.

Part of #6346

* Remove unused Kuma chat run response header

* Register Kuma with the shared async streaming router

* Always execute Kuma messages in background runs

* Use chat run constant enums in Kuma

Kuma's model_unavailable error code moves to its own run constants,
because the engine no longer defines run type specific codes.

* Move the tool executor into Kuma

Kuma is its only user, and it is specific to pydantic-ai agents, so it does
not belong to the shared chat run engine.

* Return nothing from Kuma's interruption warning hook

The engine now prunes a run whatever the hook does, so it no longer reports
whether the warning was kept.

* Stop patching the removed ChatRunBuffer.finish

* Fix and simplify Kuma's background run adapter

- Save "nothing changed" when the model was unavailable or the prompt
  never reached it.
- Keep the progress line after a reconnect and build the compatibility
  records from their models, with the right text for runs that did nothing.
- Delete the in-request path, its cache-key Stop and the event bus.
- Map a second message to 409 directly and return one run shape in the
  chat API.
- Fix docstrings, help texts and the POST schema; drop overlapping tests and
  share run test helpers.

* Fix and simplify Kuma's run follower in the browser

- Keep local-only messages on refresh and show a queued run as queued.
- Settle a request aborted before it is sent and never show raw error pages.
- Fall back to the API for a new view whose broadcast is late.
- Stop a run through the engine.
- Delete the reader for the previous backend, the old cancel call and the
  UI location history.
- Share run test helpers and drop overlapping tests.

* Tighten Kuma's e2e tests, CI setup and docs

- Prove a live resume after a reload and drop a test that proved nothing new.
- Keep Kuma's panel closed in every browser context through the storage state.
- Drop the unused OpenAI key from the e2e setup.
- Rewrite the background replies section of the AI assistant docs.

* Handle Kuma runs whose sender lost access, and other review fixes

- A queued run whose sender can no longer use Kuma ends as access_lost
  without calling the model.
- A chat keeps asking runs for a title while its title is provisional.
- Test that a run captures and saves its onboarding target.
- Pass Phoenix settings to the dev export worker; pin CI's Kuma stub to
  Node 24.22.1.

* Fix Kuma's browser edge cases found in the re-review

- A send whose stream is refused after its run started re-reads the
  chat and counts as accepted.
- A chat read that ends after another chat was chosen is dropped, and
  only a 4xx forgets the tab's stored chat.
- An unsaved outcome stays shown while its run is the chat's latest.
- The status line shows that Kuma is answering.
- Empty stopped or failed answers show only their outcome.
- Logout clears Kuma's chats, messages and pending navigation.

* feat(assistant): follow Kuma replies through shared chat runs

* refactor(assistant): remove obsolete stream-limit recovery

* fix(assistant): simplify Kuma cutover and preserve legacy Stop

* fix(assistant): preserve existing Kuma API contracts

* refactor(assistant): match stream event kinds

* refactor(assistant): simplify execution and navigation

* fix(assistant): show that Kuma is cancelling after Stop

* test(assistant): cover the stale refresh guard and trashed workspaces

* refactor(assistant): close the run follower and drop the unused baseline

* refactor(chat-runs): share the run-in-progress error code

* docs(assistant): document the run limit and the deprecated chat status

* fix(assistant): give a duplicated tab its own Kuma tab id
2026-11-18 11:21:31 +01:00
Davide Silvestri 18ae3c06cb feat(agent): ask before running tools (#6602)
* feat(agent): retain reply execution details

* feat(agent): hold Ask first tool calls for the owner's approval

* feat(agent): approve or reject held tool calls in the chat

* fix(agent): tell the model that Ask first calls wait for the user

* refactor(agent): run the approval action through the action registry

* fix(agent): preserve approval state across reply transitions

Mark held calls waiting immediately and keep retry slots across durable
pauses. Keep stale history and run snapshots from undoing newer decisions.
Contain rejection dialog focus and localize its waiting announcement.

Add focused transition regressions and update the tool presentation contract.
Align approval fixtures with the parent conversation cursor contract.
Validation: 469 backend passed (one known xfail), 362 frontend passed;
query-growth, migration drift, lint and browser component checks passed.

* feat(agent): show partial results of approved calls in the approval card

* test(agent): cover web searches next to held tool calls

* fix(agent): drop retry slots, every tool call has its own card

A paused reply no longer saves which failed steps the next response may
continue. Transcripts drop text PostgreSQL can't store, like steps do.

* feat(agent): show a held call's named request while it waits

A held call is named as the Agent identity when it is held and sends
the request to its step like a running call, so the owner decides on
names. What can't be named keeps its ID; the call still waits.

* feat(agent): title held changes with their table

* fix(agent): end held calls by the owner's decision

A held call that a reply ends without resuming is rejected when the owner
rejected it, stopped when they approved it, since the resume may have run it,
and failed when undecided. Copies end held calls at export, where the
decisions are known. Rejected calls stay out of the interruption note.

* fix(agent): resume a paused reply as the run that paused

The transcript keeps whether the paused run offered web search and the
identity it acted as. A resume offers search only if the paused run did, so a
provider that refused it doesn't fail the reply after the approved change ran.
It runs approved calls only as the identity they were held under; when the
Agent no longer acts as it, they fail with a permission error. Every resume
tells the model that users approve these calls.

* chore(agent): clean up after the tool approval review

Drop the unreachable ChatRunAlreadyActive from the decide path, its API schema
and tests, and test the refused resume against the real run limit. Remove the
import branch for exports without ask_first_tools and the toolInputText
indirection, and add the decision audit strings to the agent catalog.

* fix(agent): end held calls that never ran as not run

A held call that a reply ends without running now fails with `not_run`:
undecided, or approved when the resume never started (not ready, cancelled
before it started). Only a resume that started stops its approved calls,
since it may have run them; `mark_reply_interrupted` now passes an empty
result, so `None` again means the run never started. The interruption note
leaves `not_run` calls out, like rejected ones, and the card says "It didn't
run."

* fix(agent): keep the IDs of what a held request can't name

A table, database or view the Agent identity can't see no longer empties the
whole request preview: it keeps its ID, like fields and rows already did.
Values of rows for a table that can't be named are all masked, since its
password fields are unknown. An approval for an unknown table now shows
`table_id` and the requested rows instead of nothing.

* fix(agent): tell the model why an approved call lost its identity

When the Agent no longer acts as the identity a call was held under, the
approved call is denied with a note saying so, and that tools are
unavailable for the rest of the reply, instead of "This tool is no longer
allowed."

* fix(agent): hold no change after a call with invalid arguments

pydantic-ai validates every call of a response before running any, and
reports invalid ones with `args_valid=False`. An ask first call that fails
validation is retried, never held, so it no longer holds the changes after
it: a change set to run without asking now runs.

* fix(agent): leave reply transcripts out of copies

Duplicates and snapshots no longer copy each reply's model messages and
usage. They hold every tool result, nothing reads them, and the export
loaded all of them at once. A copied reply can't resume anyway.

* feat(agent): title unfinished calls by their request

A call that isn't running or done is titled by what it asked for, so an
approved call that fails keeps "Update 1 row in Accounts". An approved card
item shows any outcome other than success next to the decision, now failed
too. Held reads keep their request and are titled with their table.
2026-11-10 18:06:58 +00:00
Davide Silvestri 68f8fed4c2 feat(agent): show tool inputs and why tool calls failed (#6631)
* feat(agent): show tool inputs and name known targets of failed calls

Moved out of the tool activity layer so the approvals layer can decide how long input values are kept.

* refactor(agent): drop duplicate checks on step resources and input previews

* refactor(agent): drop failed-call targets and row input previews

Failed calls show only the error, the input preview is a single size
check on the stored JSON, and row writes keep no preview because their
values can include passwords. Both are tracked in #6626.

* feat(tools): report database tool errors in one format

Every error has a code, a message written for people and an optional hint
for the model. Batch tools list failed items in errors, set changed, and
set error only when nothing was changed. MCP gets the hint after the
message.

* fix(assistant): read the shared tools' new error format

Formula repair finds invalid formulas by code and rechecks the outcome
after repairing. A repair that fails for another reason reports the real
cause. Hints reach Kuma as next steps.

* feat(agent): keep only tool calls that did something

A failed call shows the reason, a call that changed nothing is skipped,
a partly done call lists what failed, and a retry of a failed call
continues its card.

* feat(agent): show failure reasons and partial results in tool cards

* style(mcp): format the server test

* fix(tools): log unexpected errors and keep their text out of messages

Built-in errors are unexpected again: logged, with the generic message.
Tools raise ToolInputError with a message for people and a hint for the
model where they mean a user error, including linking to a table in
another database. create_views no longer turns any exception into a
message.

* fix(agent): give every tool call its own card

A result ends only its own call's card: no retry continues an earlier
card. Step text, reply text and streamed text are cleaned of characters
PostgreSQL can't store. The partial status is visible.
2026-11-09 22:49:21 +01:00
Davide SilvestriandClaude Opus 5.5 eec8247c0a feat(agent): show tool activity in conversations (#6551)
* feat(agent): show tool activity in conversations

* refactor(agent): centralize tool step statuses

* fix(agent): keep tool-step diagnostics free of private data

* fix(agent): retain Sentry details for tool errors

* feat(agent): show tool inputs and failed read attempts

* fix(agent): show individual tool outcomes in activity groups

* feat(agent): explain tool failures in translated tooltips

* feat(agent): name known targets in failed tool calls

* fix(agent): use shared tool errors after rebase

* fix(agent): show interrupted changes, announce tool steps and clear pre-tool text

* refactor(agent): move input previews and failed-call targets out of tool steps

* refactor(agent): log tool-step failures without the Sentry helper

* fix(agent): classify tool errors once and drop partial-failure steps

Calls to tools a reply never offered no longer get a step.

* refactor(agent): key tool presenters by tool name and drop unused step data

Drops presentation_type, the unused card icon, copy-time step cleanup and Kuma-visible chat CSS changes, and defers steps when loading reply history.

* test(agent): cover Stop during a change and merge overlapping step tests

* docs(agent): trim tool presentation guide to the step contract

* fix(agent): keep step facts JSON-safe and polish stopped cards

Restores the JSON check on step facts, keeps a stopped change's title readable at narrow widths, raises its warning contrast, and stops reopening a running reply from re-announcing its old steps.

* fix(agent): cap the Agent chat column at 900px

* fix(agent): name the executing tool call and keep step cards stable while text streams

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agent): name reused tables and views instead of showing zero created

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agent): tell the model which changes an interrupted reply started

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agent): continue a retried tool call on the step of its invalid attempt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agent): report views skipped by name collisions

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 10:53:05 +00:00
Davide Silvestri ca3d710b3b feat(agent): choose the identity an Agent runs as (#6540)
* feat(agent): choose the identity an Agent runs as

Agents can run as one of the workspace's Agent identities or with no
workspace access. The tools that act with the identity's permissions
come next.

* fix(agent): refresh the run-as identity label

* fix(agent): flag deleted run-as identities in configuration

* feat(agent): explain unavailable workspace identities

* refactor(agent): return a typed configuration object

* fix(agent): handle run-as identity permissions and lifecycle

* refactor(agent): use constants for readiness and state checks

* fix(agent): record before and after configuration values

* refactor(agent): move configuration transaction to API view

* fix(agent): batch run-as identity invalidations

* test: use real debounce in views admin tests

* fix(agent): keep run-as choices within the viewport

* perf: reuse permission data within batches
2026-11-05 09:16:14 +01:00
Davide Silvestri 362f690b9e feat(chat-runs): per-run-type limits and a core run stream (#6454)
* feat(chat-runs): limit active runs per run type, per user or workspace

Each run type now counts only its own runs. The per-user limit keeps its default of 2, and a run type can add a per-workspace limit.

* feat(chat-runs): follow any run over one core streaming endpoint

GET /api/chat-runs/<run_id>/stream/ relays the output of any run type behind its read check. Helm and the install guides route /api/chat-runs/ to the ASGI service; the guides also gain Kuma's /assistant/ route.

* feat(chat-runs): read the core run stream by default in the frontend

The base ChatRunType reads the core stream, applies the resume baseline and retries once after a token refresh.

* refactor(chat-runs): expose the output fold for lost runs

Run types rebuild a lost run's partial text from the buffered output with fold_output.

* perf(chat-runs): send heartbeat records and skip repeated run reads

While no output arrives, an open stream sends run.heartbeat as a JSON
record, so a follower can tell a quiet stream from a stalled one. The stream
view hands follow_run the run state it read for its permission check,
finish_run returns the ended run instead of letting callers read it again,
and a lease renewal takes one statement while the run goes on. The
per-workspace limit hook receives the workspace, so a run type can set the
limit per plan.

* perf(chat-runs): follow runs from their open stream in the frontend

The store reads a run's status only while it has no stream or the stream
lost its output, and restarts a stream that stays silent for 15 seconds,
also after the computer slept. Following a run opens its stream directly,
and Stop doesn't read a run whose stream is open. Each run type keeps one
chat subscription, released with unsubscribeFromChat; refreshChat runs only
when a subscription is confirmed on a new websocket, and window focus or a
regained network only re-attach followers. The developer guide documents
the subscription and heartbeat contract.

* perf(chat-runs): write a reply's first words at once

- The journal writes output after a quiet moment at once and batches
  what follows, so the first words no longer wait for the 250 ms timer.
- The stream adapter settles when aborted. Chrome can fire the last
  progress event after the request is done, where aborting fires no event.
- A stream refused with 503 is retried with the next status check
  instead of spending every reconnect attempt at once.

* refactor(chat-runs): register the stream route by URL name
2026-10-30 10:35:50 +01:00
Davide Silvestri 9eabe6b06b feat(core): add Redis-backed background chat runs (#6382)
* feat(core): add Redis-backed background chat runs

Run AI work once in Celery and follow bounded Redis Streams over HTTP. Keep
lifecycle, Stop, leases and final outcomes in Postgres without per-token writes.
Include the shared frontend follower, adapter registry, recovery API, migration,
queue/deployment wiring and adapter guide. No product uses it yet.

Part of #6346

* Remove unused chat run response header exposure

* Extract shared async streaming HTTP router

* Simplify chat run follower and group engine constants

- Check read access once when a stream opens; read run state from Postgres
  only after 5 s without output or on run.finished.
- Split follow_run into small steps around _OutputReader.
- Turn event kinds, error codes and stop reasons into StrEnums; the
  Kuma-only model_unavailable code moves to Kuma.
- Document ChatRunType hooks with param, return and raises fields.
- Add BASEROW_ASGI_HTTP_MAX_CONCURRENT_STREAMS and size the follower Redis
  pool by it.
- Give handler publish/recover calls their own event loop, so cleanup
  cannot close pools shared by HTTP followers.
- Update ADR 010 and the background chat runs docs.

* Clean up chat run interfaces and test setup

* Prune chat runs once after 7 days and skip overdue claims

- Delete each expired page with one statement. Incomplete runs get one more
  ensure_interruption_warning call first, and are deleted even if it fails,
  so run metadata never accumulates. The hook now returns None.
- Keep runs for 7 days instead of 30.
- Never claim a queued run older than NOT_STARTED_AFTER; the sweeper ends it.

* Retry brief Redis failures in chat run followers

- A connection error, or a buffer that does not exist yet, is retried with
  the same cursor, sending heartbeats meanwhile.
- run.replay_unavailable is only sent once the follower stops reading, so
  the browser can treat it as final.

* Let finished chat run output expire with the active TTL

Nothing reads a buffer once its run has finished: followers return the saved
outcome first and recovery only reads running runs. Drop finish() and the
24 h TTL, so a finished buffer expires an hour after its last append.
_publish_terminal now reuses _publish.

* Run the chat run scale tests on fakeredis

Build the buffer's real read and write pools on fakeredis connections, so
these tests always run and backend CI needs no Redis service. The Kuma e2e
tests cover a real Redis.

* Address the remaining chat run review comments

- Serialize the saved outcome after the transaction, so only a failed save
  is logged as one.
- Make the primary-pin test transactional; inside the test transaction the
  router always used the primary, so it could not fail.
- Cover the race past the per-user lock, a lost run after Stop and an old
  writer appending to a recreated buffer.
- End the admission test's request with a disconnect, so a regression fails
  instead of looping.
- Document that one worker process runs AI replies one at a time.

* Move the chat run migration after develop's core 0130

* Log only the class of an outcome serialization error

* Test that the run deadline asks a run to stop

* Keep a run's status when a resumed follower rebuilds its output

* Note that slow DNS lookups turn off a run's live output
2026-10-21 14:52:59 +02:00