Files
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

255 lines
7.3 KiB
JavaScript

import { StoreItemLookupError } from '@baserow/modules/core/errors'
import { BuilderApplicationType } from '@baserow/modules/builder/applicationTypes'
import PageService from '@baserow/modules/builder/services/page'
import { generateHash } from '@baserow/modules/core/utils/hashing'
import { pageFinished } from '@baserow/modules/core/utils/routing'
import { nextTick } from '#imports'
import { BUILDER_ACTION_SCOPES } from '@baserow/modules/builder/utils/undoRedoConstants'
export function populatePage(page) {
return {
...page,
graph: page.graph || {},
_: {
selected: false,
dataSourceContentLoading: false,
dataSourceLoading: false,
dataSourceFetched: false,
},
dataSources: [],
elements: [],
elementMap: {},
orderedElements: [],
workflowActions: [],
elementTree: [],
contents: null,
formData: {},
}
}
const state = () => ({
// Holds the value of which page is currently selected
selected: {},
// By default, the device type will be desktop. This will be overridden
// in the editor, and in the public page. We set a default as otherwise
// in the public page, we can trigger a repaint, causing some layouts to
// redraw.
deviceTypeSelected: 'desktop',
// A job object that tracks the progress of a page duplication currently running
duplicateJob: null,
})
const mutations = {
ADD_ITEM(state, { builder, page }) {
// Kuma's navigation can fetch a page before its `page_created` broadcast.
if (builder.pages.some((item) => item.id === page.id)) {
return
}
builder.pages.push(populatePage(page))
},
UPDATE_ITEM(state, { page, values }) {
Object.assign(page, page, values)
},
DELETE_ITEM(state, { builder, id }) {
const index = builder.pages.findIndex((item) => item.id === id)
if (index === -1) return
// Clear the elements to void the page and prevent errors
builder.pages[index].elements = []
builder.pages[index].elementMap = {}
builder.pages[index].orderedElements = []
builder.pages.splice(index, 1)
},
SET_SELECTED(state, { builder, page }) {
Object.values(builder.pages).forEach((item) => {
item._.selected = false
})
page._.selected = true
state.selected = page
},
UNSELECT(state) {
if (state.selected?._?.selected) {
state.selected._.selected = false
}
state.selected = {}
},
SET_DUPLICATE_JOB(state, job) {
state.duplicateJob = job
},
ORDER_PAGES(state, { builder, order, isHashed = false }) {
builder.pages.forEach((page) => {
const pageId = isHashed ? generateHash(page.id) : page.id
const index = order.findIndex((value) => value === pageId)
page.order = index === -1 ? 0 : index + 1
})
},
SET_DEVICE_TYPE_SELECTED(state, deviceType) {
state.deviceTypeSelected = deviceType
},
}
const actions = {
forceUpdate({ commit }, { page, values }) {
commit('UPDATE_ITEM', { page, values })
},
forceCreate({ commit }, { builder, page }) {
commit('ADD_ITEM', { builder, page })
},
selectById({ commit, getters, dispatch }, { builder, pageId }) {
const type = BuilderApplicationType.getType()
// Check if the just selected application is a builder
if (builder.type !== type) {
throw new StoreItemLookupError(
`The application doesn't have the required ${type} type.`
)
}
// Check if the provided page id is found in the just selected builder.
const page = getters.getById(builder, pageId)
// Send the shared page id alongside the content page id so that edits to
// shared (header/footer) elements remain undoable while editing this page.
const sharedPage = getters.getSharedPage(builder)
dispatch(
'undoRedo/updateCurrentScopeSet',
BUILDER_ACTION_SCOPES.page(page.id, sharedPage?.id ?? null),
{ root: true }
)
commit('UNSELECT')
commit('SET_SELECTED', { builder, page })
return page
},
unselect({ commit, dispatch }) {
commit('UNSELECT')
dispatch(
'undoRedo/updateCurrentScopeSet',
BUILDER_ACTION_SCOPES.page(null),
{ root: true }
)
},
async forceDelete({ commit }, { builder, page }) {
if (page._.selected) {
commit('UNSELECT')
// Redirect back to the workspace homepage because the builder page doesn't
// exist anymore.
await this.$router.push({
name: 'workspace',
params: { workspaceId: builder.workspace.id },
})
await pageFinished(this.app)
await nextTick()
}
commit('DELETE_ITEM', { builder, id: page.id })
},
async create(
{ commit, dispatch },
{ builder, name, path, pathParams, queryParams }
) {
const { $registry, $i18n, $client, $config } = this
const { data: page } = await PageService($client).create(
builder.id,
name,
path,
pathParams,
queryParams
)
commit('ADD_ITEM', { builder, page })
await dispatch('selectById', { builder, pageId: page.id })
return page
},
async update({ dispatch }, { builder, page, values }) {
const { $registry, $i18n, $client, $config } = this
const { data } = await PageService($client).update(page.id, values)
const update = Object.keys(values).reduce((result, key) => {
result[key] = data[key]
return result
}, {})
await dispatch('forceUpdate', { builder, page, values: update })
},
async delete({ dispatch }, { builder, page }) {
const { $registry, $i18n, $client, $config } = this
await PageService($client).delete(page.id)
await dispatch('forceDelete', { builder, page })
},
async order(
{ commit, getters },
{ builder, order, oldOrder, isHashed = false }
) {
const { $registry, $i18n, $client, $config } = this
commit('ORDER_PAGES', { builder, order, isHashed })
try {
await PageService($client).order(builder.id, order)
} catch (error) {
commit('ORDER_PAGES', { builder, order: oldOrder, isHashed })
throw error
}
},
setDeviceTypeSelected({ commit }, deviceType) {
commit('SET_DEVICE_TYPE_SELECTED', deviceType)
},
async duplicate({ commit, dispatch }, { page }) {
const { $registry, $i18n, $client, $config } = this
const { data: job } = await PageService($client).duplicate(page.id)
await dispatch('job/create', job, { root: true })
commit('SET_DUPLICATE_JOB', job)
},
}
const getters = {
getAllPages: (state) => (builder) => {
return builder.pages
},
getById: (state, getters) => (builder, pageId) => {
const index = getters
.getAllPages(builder)
.findIndex((item) => item.id === pageId)
if (index === -1) {
throw new StoreItemLookupError(
'The page is not found in the selected application.'
)
}
return getters.getAllPages(builder)[index]
},
getVisiblePages: (state, getters) => (builder) => {
return getters
.getAllPages(builder)
.filter((page) => page.shared === false)
.sort((a, b) => a.order - b.order)
},
getSharedPage: (state, getters) => (builder) => {
return getters.getAllPages(builder).find((page) => page.shared === true)
},
getSelected(state) {
return state.selected
},
getDeviceTypeSelected(state) {
return state.deviceTypeSelected
},
getDuplicateJob(state) {
return state.duplicateJob
},
}
export default {
namespaced: true,
state,
getters,
actions,
mutations,
}