mirror of
https://github.com/baserow/baserow.git
synced 2026-12-04 08:18:42 +00:00
* Add ADR-013 for workspace level integrations * Add implementation * Improve context section and remove technical points * Move bulk replacement point to v2 * Remove workspace-level ownership on import since manual promotion should handle this. * Add a glossary section * Do Lazy creation + Celery migration * Remove demotion * Tighten the Options considered section * Add Decision describing where the integrations are managed * Update implementation plan after changes to ADR * Sync plan and adr * Rename adr and implementation * Add the shared application that owns workspace integrations * Create the shared application of every workspace * Let only workspace admins manage workspace integrations * Let applications use the integrations of their workspace. * Trash workspace integrations in their workspace. * Copy workspace integrations into exports and keep them in duplicates. * Workspace admins can share integrations with every application in the workspace. * Load the shared application of each workspace in the frontend and keep it out of application lists. * Manage workspace integrations from an Integrations page in workspace settings. * Offer workspace integrations in the integration dropdowns of every application. * Move promoted integrations to the workspace list in other open tabs. * Let admins make an app's integration available to the whole workspace from its integration settings. * Preselect a workspace integration for new nodes and data sources when the app has none of its own. * fix tests * Delete implementation file * More fixes after rebase * Fix tests * Let builders of an application see and use the workspace integrations from it. * Show the workspace integrations, read-only, in the integration settings of applications. * Keep a dashboard's integration out of promotion to the workspace. * Leave the shared applications out of the admin dashboard's application count. * Create the shared application of the workspaces made by the fill commands. * Say in the promotion modal that an integration nobody authorized will run as the promoting admin. * Say in the promotion modal that undoing it won't make the integration run as the previous person again. * Ignore integration ids in sample data when publishing copies the workspace integrations an app uses. * Let only undoing a promotion move an integration out of the workspace. * Let the shared application backfill stop itself after 5 minutes and skip workspaces another transaction has locked. * Say in the workspace integrations settings that published applications and workflows keep their own copy until they're published again. * Leave the shared application out of the assistant evals' application counts. * Refresh the workspace integrations when the Builder's data, events, users and integrations panels open. * Say that anything new using a promoted integration blocks undoing the promotion, even from its own application. * Warn when a database button sends through a workspace integration with no host or token. * Refuse roles and invitations on the shared application. * Fix tests * Show an application only the workspace integrations of types it can use. * Say in the promotion modal what builders of other applications can do as the integration. * Leave the shared application type out of the API docs for creating and updating applications. * Check who receives a workspace integration event in one permission call. * Say which workspaces have a shared application and who creates it. * Let a redone promotion record what uses the integration again. * Update docstrings * Stop template visitors from listing the integrations of the template's workspace. * Let database buttons find their own copy of a workspace integration after an import. * Say what holds the workspace row lock while a shared application is created. * Fix tests * Stop the workspace integration form component from being made reactive. * Make test runs use a new copy of the workflow after an integration it uses changes. * Hide the Members settings tab from members who can't list the workspace members. * Add changelog * Fix migration conflict * Fix migration conflict * Fix test * Update comments and ADR number * Link to the workspace integrations from the sidebar's Settings menu. * fix: refresh agent action errors when workspace integrations change * fix: move workspace integrations into workspace settings * fix: use share icon for workspace integration promotion * refactor: use explicit shared application relations * feat: centralize default integration selection * refactor: share integration change notifications * refactor: prepare integration mappings before import * refactor: collect integration references during export * refactor: prepare integration ownership changes without a new hook * test: restore registered service model after mocking * test: cover shared integration defaults in Builder * test: include Slack in Agent workspace integration choices * Fix migrations * Stop template visitors from listing the workspace integrations through an application of the template. * Only offer integrations of the user source's integration type when updating a user source. * Say the workspace integration copy means published Application Builder apps and automation workflows. * Use the same spacing under both integration settings sections and enlarge their headings. * Keep the shared application out of automatic snapshot schedules. * Fix test after rebase --------- Co-authored-by: Jeremie Pardou <571533+jrmi@users.noreply.github.com>
416 lines
13 KiB
JavaScript
416 lines
13 KiB
JavaScript
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
|
import { useNuxtApp } from '#app'
|
|
import { useStore } from 'vuex'
|
|
import { useI18n } from 'vue-i18n'
|
|
import cloneDeep from 'lodash/cloneDeep'
|
|
import debounce from 'lodash/debounce'
|
|
import isEqual from 'lodash/isEqual'
|
|
import { removeActionInputReferences } from '@baserow/modules/agent/utils/actionFormulas'
|
|
import AgentActionService from '@baserow/modules/agent/services/agentActions'
|
|
import { actionFieldLabel } from '@baserow/modules/agent/utils/actionLabels'
|
|
import { notifyIf } from '@baserow/modules/core/utils/error'
|
|
import { getRunAsStatus } from '@baserow/modules/agent/utils/runAs'
|
|
|
|
const EDITABLE_FIELDS = [
|
|
'name',
|
|
'description',
|
|
'inputs',
|
|
'enabled',
|
|
'ask_first',
|
|
]
|
|
const missing = (error) =>
|
|
error.response?.data?.error === 'ERROR_AGENT_ACTION_DOES_NOT_EXIST'
|
|
const isCallable = (action) =>
|
|
action.enabled && !Object.keys(action.errors || {}).length
|
|
|
|
/**
|
|
* Page-local drafts, with one serialized save per independently configured action.
|
|
*
|
|
* @param {import('vue').Ref<object>} agent The Agent whose actions are edited.
|
|
* @param {Function} onCallableChange Called when the Agent gains its first
|
|
* action the model can call, or loses its last one: the configuration
|
|
* depends on whether it has one.
|
|
* @param {Function} getRunAs Returns the Agent's run identity, whose change
|
|
* changes what an action that acts as it can choose and whether it's ready.
|
|
* @param {object} options
|
|
* @param {boolean} options.loadTypes False to show the forms without choices,
|
|
* for a template preview, which has no run identity to load them for.
|
|
*/
|
|
export function useAgentActions(
|
|
agent,
|
|
onCallableChange = () => {},
|
|
getRunAs = () => null,
|
|
{ loadTypes = true } = {}
|
|
) {
|
|
const { $client, $registry } = useNuxtApp()
|
|
const { t } = useI18n()
|
|
const store = useStore()
|
|
const service = AgentActionService($client)
|
|
const actions = ref([])
|
|
// By type: what its form may choose from for the run identity; null while loading.
|
|
const actionTypes = ref(null)
|
|
const loading = ref(false)
|
|
const loadError = ref(false)
|
|
const deletingIds = reactive(new Set())
|
|
const savingIds = reactive(new Set())
|
|
const saveErrors = reactive({})
|
|
const saved = new Map()
|
|
let scope = 0
|
|
let request = 0
|
|
let typesRequest = 0
|
|
let hadCallable = null
|
|
|
|
function reportCallable() {
|
|
const hasCallable = [...saved.values()].some(({ data }) => isCallable(data))
|
|
if (hadCallable !== null && hasCallable !== hadCallable) onCallableChange()
|
|
hadCallable = hasCallable
|
|
}
|
|
|
|
function track(action) {
|
|
const entry = {
|
|
agentId: agent.value.id,
|
|
data: cloneDeep(action),
|
|
busy: false,
|
|
}
|
|
// The list renders this same proxy, so what a save returns shows in the card.
|
|
const draft = reactive(action)
|
|
entry.schedule = debounce(() => flush(draft, null, entry), 500)
|
|
saved.set(action.id, entry)
|
|
}
|
|
|
|
function forget(id, keepSaving = false) {
|
|
const entry = saved.get(id)
|
|
if (entry) {
|
|
entry.cancelled = !keepSaving
|
|
entry.schedule.cancel()
|
|
}
|
|
saved.delete(id)
|
|
delete saveErrors[id]
|
|
savingIds.delete(id)
|
|
}
|
|
|
|
function remove(id) {
|
|
forget(id)
|
|
actions.value = actions.value.filter((action) => action.id !== id)
|
|
reportCallable()
|
|
}
|
|
|
|
function changes(action, baseline = saved.get(action.id)?.data) {
|
|
if (!baseline) return {}
|
|
const changed = Object.fromEntries(
|
|
EDITABLE_FIELDS.filter((key) => !isEqual(action[key], baseline[key])).map(
|
|
(key) => [key, cloneDeep(action[key])]
|
|
)
|
|
)
|
|
const serviceValues = Object.fromEntries(
|
|
Object.entries(action.service).filter(
|
|
([key, value]) => !isEqual(value, baseline.service[key])
|
|
)
|
|
)
|
|
if (Object.keys(serviceValues).length)
|
|
changed.service = cloneDeep(serviceValues)
|
|
return changed
|
|
}
|
|
|
|
// Retain edits made after a request began, or before another editor's event.
|
|
function adopt(
|
|
action,
|
|
data,
|
|
baseline = saved.get(action.id)?.data,
|
|
entry = saved.get(action.id)
|
|
) {
|
|
if (!entry) return
|
|
const draft = changes(action, baseline)
|
|
Object.assign(action, data, draft, {
|
|
service: { ...data.service, ...draft.service },
|
|
})
|
|
entry.data = cloneDeep(data)
|
|
}
|
|
|
|
async function fetchActions({ integrations = false } = {}) {
|
|
if (!agent.value?.id) return
|
|
const currentScope = scope
|
|
const currentRequest = ++request
|
|
const isCurrent = () => currentScope === scope && currentRequest === request
|
|
const application = agent.value
|
|
loading.value = true
|
|
loadError.value = false
|
|
try {
|
|
if (integrations)
|
|
await Promise.all([
|
|
store.dispatch('integration/fetch', { application }),
|
|
store.dispatch('integration/fetchWorkspaceIntegrationsOnce', {
|
|
application,
|
|
}),
|
|
])
|
|
const { data } = await service.list(application.id)
|
|
if (!isCurrent()) return
|
|
const existing = new Map(
|
|
actions.value.map((action) => [action.id, action])
|
|
)
|
|
actions.value = data.map((action) => {
|
|
const current = existing.get(action.id)
|
|
if (current) {
|
|
adopt(current, action)
|
|
return current
|
|
}
|
|
track(action)
|
|
return action
|
|
})
|
|
for (const id of saved.keys()) {
|
|
if (!data.some((action) => action.id === id)) forget(id)
|
|
}
|
|
reportCallable()
|
|
} catch {
|
|
if (isCurrent()) loadError.value = true
|
|
} finally {
|
|
if (isCurrent()) loading.value = false
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Loads what each action type's form may choose from for the Agent's run
|
|
* identity, ignoring a reply that a newer load replaced. When it fails, the
|
|
* forms open with nothing to choose from.
|
|
*/
|
|
async function fetchActionTypes() {
|
|
if (!agent.value?.id) return
|
|
if (!loadTypes) {
|
|
actionTypes.value = {}
|
|
return
|
|
}
|
|
const currentScope = scope
|
|
const currentRequest = ++typesRequest
|
|
try {
|
|
const { data } = await service.listTypes(agent.value.id)
|
|
if (currentScope !== scope || currentRequest !== typesRequest) return
|
|
actionTypes.value = Object.fromEntries(
|
|
data.map(({ type, ...options }) => [type, options])
|
|
)
|
|
} catch {
|
|
if (currentScope === scope && currentRequest === typesRequest)
|
|
actionTypes.value = {}
|
|
}
|
|
}
|
|
|
|
async function createAction(type) {
|
|
const currentScope = scope
|
|
try {
|
|
const { data } = await service.create(agent.value.id, { type })
|
|
if (currentScope !== scope) return
|
|
const existing = actions.value.find((action) => action.id === data.id)
|
|
if (existing) adopt(existing, data)
|
|
else {
|
|
track(data)
|
|
actions.value.push(data)
|
|
}
|
|
reportCallable()
|
|
return data
|
|
} catch (error) {
|
|
notifyIf(error, 'action')
|
|
}
|
|
}
|
|
|
|
async function flush(action, fields = null, entry = saved.get(action.id)) {
|
|
if (!entry || entry.cancelled) return
|
|
const isCurrent = () => saved.get(action.id) === entry
|
|
if (entry.busy) {
|
|
entry.changedWhileSaving = true
|
|
return
|
|
}
|
|
const pending = changes(action, entry.data)
|
|
// A draft changed back to what is saved has nothing left to be rejected.
|
|
if (!Object.keys(pending).length && isCurrent())
|
|
delete saveErrors[action.id]
|
|
const sent = Object.fromEntries(
|
|
Object.entries(pending).filter(([key]) => !fields || fields.includes(key))
|
|
)
|
|
if (!Object.keys(sent).length) return
|
|
const baseline = {
|
|
...cloneDeep(entry.data),
|
|
...sent,
|
|
service: { ...entry.data.service, ...sent.service },
|
|
}
|
|
entry.busy = true
|
|
if (isCurrent()) savingIds.add(action.id)
|
|
try {
|
|
const { data } = await service.update(entry.agentId, action.id, sent)
|
|
if (entry.cancelled) return
|
|
// Navigation detaches the card, but its last edits still belong to this save.
|
|
adopt(action, data, baseline, entry)
|
|
if (isCurrent()) reportCallable()
|
|
if (isCurrent() && !Object.keys(changes(action)).length)
|
|
delete saveErrors[action.id]
|
|
} catch (error) {
|
|
if (entry.cancelled) return
|
|
if (missing(error)) {
|
|
entry.cancelled = true
|
|
if (isCurrent()) remove(action.id)
|
|
} else if (!isCurrent()) {
|
|
notifyIf(error, 'action')
|
|
} else {
|
|
// Keep rejected drafts visible so they can be repaired without retyping.
|
|
const validation =
|
|
error.response?.data?.error === 'ERROR_REQUEST_BODY_VALIDATION'
|
|
const detail = error.response?.data?.detail
|
|
const messages = (value) => {
|
|
if (typeof value === 'string') return [value]
|
|
if (!value || typeof value !== 'object') return []
|
|
if (typeof value.error === 'string') return [value.error]
|
|
return Object.values(value).flatMap(messages)
|
|
}
|
|
saveErrors[action.id] =
|
|
validation && detail && typeof detail === 'object'
|
|
? Object.entries(detail)
|
|
.map(
|
|
([field, errors]) =>
|
|
`${actionFieldLabel($registry, action.type, field, t)}: ${messages(errors).join(' ')}`
|
|
)
|
|
.join(' ')
|
|
: t('agent.actionSaveError')
|
|
if (!validation) notifyIf(error, 'action')
|
|
}
|
|
} finally {
|
|
entry.busy = false
|
|
if (saved.get(action.id) === entry) savingIds.delete(action.id)
|
|
}
|
|
if (entry.changedWhileSaving) {
|
|
entry.changedWhileSaving = false
|
|
flush(action, null, entry)
|
|
}
|
|
}
|
|
|
|
function updateAction(action, values) {
|
|
const entry = saved.get(action.id)
|
|
if (!entry) return
|
|
if (values.inputs) {
|
|
const remaining = new Set(values.inputs.map(({ id }) => id))
|
|
const removed = action.inputs
|
|
.filter(({ id }) => !remaining.has(id))
|
|
.map(({ id }) => id)
|
|
if (removed.length)
|
|
values = {
|
|
...values,
|
|
service: removeActionInputReferences(
|
|
{ ...action.service, ...values.service },
|
|
removed
|
|
),
|
|
}
|
|
}
|
|
const previousService = action.service
|
|
Object.assign(action, cloneDeep(values))
|
|
if (values.service)
|
|
action.service = { ...previousService, ...values.service }
|
|
const immediate = ['enabled', 'ask_first'].filter(
|
|
(field) => field in values
|
|
)
|
|
if (immediate.length) flush(action, immediate)
|
|
else entry.schedule()
|
|
}
|
|
|
|
async function deleteAction(action) {
|
|
const entry = saved.get(action.id)
|
|
if (!entry || deletingIds.has(action.id)) return
|
|
deletingIds.add(action.id)
|
|
entry.schedule.cancel()
|
|
try {
|
|
await service.delete(entry.agentId, action.id)
|
|
if (saved.get(action.id) === entry) remove(action.id)
|
|
} catch (error) {
|
|
if (missing(error) && saved.get(action.id) === entry) remove(action.id)
|
|
else {
|
|
notifyIf(error, 'action')
|
|
if (saved.get(action.id) === entry) entry.schedule()
|
|
}
|
|
} finally {
|
|
deletingIds.delete(action.id)
|
|
}
|
|
}
|
|
|
|
function flushScheduledSaves() {
|
|
for (const entry of saved.values()) entry.schedule.flush()
|
|
}
|
|
|
|
onMounted(() => {
|
|
fetchActions({ integrations: true })
|
|
fetchActionTypes()
|
|
})
|
|
watch(
|
|
() => agent.value?.id,
|
|
() => {
|
|
flushScheduledSaves()
|
|
++scope
|
|
for (const id of saved.keys()) forget(id, true)
|
|
actions.value = []
|
|
actionTypes.value = null
|
|
hadCallable = null
|
|
fetchActions({ integrations: true })
|
|
fetchActionTypes()
|
|
}
|
|
)
|
|
watch(
|
|
() => {
|
|
const runAs = getRunAs()
|
|
return [runAs?.type, runAs?.id, getRunAsStatus(runAs)].join(':')
|
|
},
|
|
() => {
|
|
fetchActionTypes()
|
|
if (!loading.value) fetchActions()
|
|
}
|
|
)
|
|
watch(
|
|
() => agent.value?._?.actionUpdate,
|
|
(event) => {
|
|
if (!event) return
|
|
if (event.kind === 'deleted') remove(event.actionId)
|
|
else {
|
|
const existing = actions.value.find(
|
|
(action) => action.id === event.action.id
|
|
)
|
|
if (existing) adopt(existing, event.action)
|
|
else {
|
|
track(event.action)
|
|
actions.value.push(event.action)
|
|
}
|
|
reportCallable()
|
|
}
|
|
},
|
|
// A reconnect replays several events at once, and each one must be applied.
|
|
{ flush: 'sync' }
|
|
)
|
|
// Editing a connection can repair an unconfigured action without changing it.
|
|
watch(
|
|
[
|
|
() => store.state.integration.generation[agent.value?.id],
|
|
() => {
|
|
const workspace = agent.value?.workspace
|
|
const sharedApplication =
|
|
workspace &&
|
|
store.getters['application/getSharedApplication'](workspace)
|
|
return store.state.integration.generation[sharedApplication?.id]
|
|
},
|
|
],
|
|
() => {
|
|
if (!loading.value) fetchActions()
|
|
}
|
|
)
|
|
onBeforeUnmount(flushScheduledSaves)
|
|
|
|
return {
|
|
actions: computed(() =>
|
|
actions.value.filter((action) => !deletingIds.has(action.id))
|
|
),
|
|
allActions: actions,
|
|
actionTypes,
|
|
loading,
|
|
loadError,
|
|
savingIds,
|
|
saveErrors,
|
|
fetchActions,
|
|
createAction,
|
|
updateAction,
|
|
deleteAction,
|
|
flush,
|
|
}
|
|
}
|