Files
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

95 lines
2.9 KiB
JavaScript

import axios from 'axios'
import { createRecordReader } from '@baserow/modules/core/chatRuns/recordReader'
/**
* Reads the body of a failed response, or describes it when it is not a JSON
* object, such as a proxy's HTML page.
*
* @param {XMLHttpRequest} xhr The finished request.
* @returns {object} The error data.
*/
function parseErrorBody(xhr) {
let data
try {
data = JSON.parse(xhr.responseText)
} catch {
data = null
}
return data && typeof data === 'object' && !Array.isArray(data)
? data
: { error: 'REQUEST_FAILED', detail: xhr.responseText || xhr.statusText }
}
/**
* An axios adapter handing each record of a streamed response to `onRecord` as
* it arrives, so the request keeps the client's headers and interceptors.
*
* @param {Function} onRecord Called with each parsed record.
* @param {AbortSignal} [signal] Aborting closes the response; the run continues.
* @returns {Function} The axios adapter.
*/
export function createStreamAdapter(onRecord, signal) {
return (config) =>
new Promise((resolve, reject) => {
// Like AxiosError, keep the config so the token refresh interceptor can retry.
const failure = (message, values = {}) =>
Object.assign(new Error(message), {
isAxiosError: true,
config,
...values,
})
const cancelled = () => failure('Request cancelled', { cancelled: true })
if (signal?.aborted) {
reject(cancelled())
return
}
const xhr = new XMLHttpRequest()
const reader = createRecordReader(() => xhr.responseText, onRecord)
const abort = () => {
xhr.abort()
// Aborting a request that is already done fires no event.
reject(cancelled())
}
const settle = () => signal?.removeEventListener('abort', abort)
signal?.addEventListener('abort', abort, { once: true })
xhr.open(config.method.toUpperCase(), axios.getUri(config), true)
Object.keys(config.headers).forEach((key) => {
xhr.setRequestHeader(key, config.headers[key])
})
const succeeded = () => xhr.status >= 200 && xhr.status < 300
xhr.onprogress = () => succeeded() && reader.read()
xhr.onload = () => {
settle()
if (succeeded()) {
reader.flush().then(() =>
resolve({
data: '',
status: xhr.status,
statusText: xhr.statusText,
headers: {},
config,
request: xhr,
})
)
return
}
const data = parseErrorBody(xhr)
reject(
failure(data.detail || xhr.statusText, {
response: { data, status: xhr.status, statusText: xhr.statusText },
})
)
}
xhr.onerror = () => {
settle()
reject(failure('Network error occurred'))
}
xhr.onabort = () => {
settle()
reject(cancelled())
}
xhr.send()
})
}