Files
baserow/web-frontend/test/unit/agent/helpers.js
Tsering PaljorandJeremie Pardou 250748c8dc feat: Workspace level integrations (#6547)
* 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>
2026-11-27 15:49:32 +04:00

435 lines
12 KiB
JavaScript

import { vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { ref } from 'vue'
import { matchedRouteKey } from 'vue-router'
import { TestApp } from '@baserow/test/helpers/testApp'
import Context from '@baserow/modules/core/components/Context'
import { clone } from '@baserow/modules/core/utils/object'
import AgentApplicationContent from '@baserow/modules/agent/components/AgentApplicationContent'
export const workspace = {
id: 1,
name: 'Workspace',
generative_ai_models_enabled: { openai: ['model-one', 'model-two'] },
ai_features: { ai_agent: { models: { openai: ['model-one', 'model-two'] } } },
}
export const agentData = {
id: 10,
name: 'Support agent',
type: 'agent',
readiness: 'ready',
workspace: { id: 1 },
}
export const completeConfiguration = (extra = {}) => ({
instructions: 'Be helpful.',
provider_type: 'openai',
model_identifier: 'model-one',
readiness: 'ready',
errors: {},
...extra,
})
const triggerSchema = {
type: 'object',
properties: {
triggered_at: { type: 'string', title: 'Previous scheduled run' },
next_run_at: { type: 'string', title: 'Next scheduled run' },
},
}
export const periodicTrigger = (extra = {}) => ({
id: 1,
type: 'periodic',
name: '',
enabled: true,
message: { formula: "'Periodic trigger'", mode: 'simple', version: '0.1' },
service: {
id: 5,
type: 'periodic',
interval: 'HOUR',
minute: 0,
hour: 0,
day_of_week: 0,
day_of_month: 1,
timezone: 'UTC',
schema: triggerSchema,
},
on_overlap: 'skip',
may_ask_person: true,
last_fired_on: null,
last_skipped_on: null,
last_skipped_reason: '',
...extra,
})
export const incompleteConfiguration = (field) =>
completeConfiguration({
[field]: field === 'instructions' ? '' : null,
readiness: 'incomplete',
errors: { [field]: 'required' },
})
export const unavailableModel = (model) =>
completeConfiguration({
model_identifier: model,
readiness: 'unavailable',
errors: { model_identifier: 'unavailable' },
})
export const deferredReply = () => {
let resolve
return {
reply: () =>
new Promise((r) => {
resolve = r
}),
resolve: (status, data) => resolve([status, data]),
}
}
export const withoutConfiguration = (operation) =>
!['agent_application.read_configuration', 'application.update'].includes(
operation
)
// One handler per route, because axios-mock-adapter matches an earlier reply first.
function respond(handler, ...responses) {
const queue = [...responses]
handler.reply((config) => {
const response = queue.length > 1 ? queue.shift() : queue[0]
if (typeof response === 'function') return response(config)
const isTuple = Array.isArray(response) && typeof response[0] === 'number'
return isTuple ? response : [200, response]
})
}
export const mockAgent = (testApp, ...responses) =>
respond(testApp.mock.onGet('/applications/10/'), ...responses)
export const mockRename = (testApp, ...responses) =>
respond(testApp.mock.onPatch('/applications/10/'), ...responses)
export const mockConfiguration = (testApp, ...responses) =>
respond(testApp.mock.onGet('/agent/10/configuration/'), ...responses)
export const mockSaves = (testApp, ...responses) =>
respond(testApp.mock.onPatch('/agent/10/configuration/'), ...responses)
export const mockAvailability = (testApp, ...responses) =>
respond(testApp.mock.onGet('/workspaces/'), ...responses)
export const mockConversations = (testApp, ...responses) =>
respond(testApp.mock.onGet('/agent/10/conversations/'), ...responses)
export const mockStartConversation = (testApp, ...responses) =>
respond(testApp.mock.onPost('/agent/10/conversations/'), ...responses)
export const mockMessages = (testApp, uuid, ...responses) =>
respond(
testApp.mock.onGet(`/agent/10/conversations/${uuid}/messages/`),
...responses
)
export const mockSendMessage = (testApp, uuid, ...responses) =>
respond(
testApp.mock.onPost(`/agent/10/conversations/${uuid}/messages/`),
...responses
)
export const mockApprovals = (testApp, uuid, ...responses) =>
respond(
testApp.mock.onPost(`/agent/10/conversations/${uuid}/approvals/`),
...responses
)
const sharedApplication = {
id: 99,
name: '__shared__',
type: 'shared',
order: 0,
workspace: { id: workspace.id },
}
/**
* Mocks the integrations of the Agent and of its workspace, which the action
* forms offer too. The workspace's shared application is put in the store, as
* the application listing would.
*/
export async function mockIntegrations(testApp) {
await testApp.store.dispatch(
'application/forceCreate',
clone(sharedApplication)
)
mockAgentIntegrations(testApp, agentData.id)
}
/**
* Mocks the integrations an Agent loads with its actions, its own and the
* workspace ones, which every Agent fetches for itself. For an Agent of the
* workspace `mockIntegrations` has already set up.
*/
export function mockAgentIntegrations(testApp, agentId) {
testApp.mock
.onGet(`application/${agentId}/workspace-integrations/`)
.reply(200, {
shared_application: clone(sharedApplication),
integration_types: ['smtp'],
integrations: [],
})
testApp.mock.onGet(`application/${agentId}/integrations/`).reply(200, [])
}
export const sentBodies = (testApp) =>
testApp.mock.history.post.map(({ data }) => JSON.parse(data))
export const savedValues = (testApp) =>
testApp.mock.history.patch
.filter(({ url }) => url === '/agent/10/configuration/')
.map(({ data }) => JSON.parse(data))
export const viewer = { id: 1, name: 'Viewer' }
export async function createAgentPage() {
const testApp = new TestApp()
testApp.authenticate({ id: viewer.id, first_name: viewer.name })
const allowed = ref(() => true)
await testApp.store.dispatch('workspace/forceCreate', clone(workspace))
const agent = await testApp.store.dispatch(
'application/forceCreate',
clone(agentData)
)
mockAvailability(testApp, [workspace])
mockAgent(testApp, agentData)
mockConfiguration(testApp, completeConfiguration())
mockConversations(testApp, conversationsPage([]))
mockStartConversation(testApp, acceptConversation)
// Nuxt's $hasPermission is a non-configurable getter, so override a child.
const permissionApp = Object.create(testApp.nuxtApp)
Object.defineProperty(permissionApp, '$hasPermission', {
value: (operation) => allowed.value(operation),
})
const route = { leaveGuards: new Set(), updateGuards: new Set() }
return {
testApp,
agent,
allowed,
mount: ({ mixins = [], stubs = {} } = {}) =>
testApp.mount(AgentApplicationContent, {
props: { agent },
global: {
provide: { [matchedRouteKey]: ref(route) },
plugins: [{ install: (app) => (app.$nuxt = permissionApp) }],
mixins,
stubs,
},
}),
leave: () => [...route.leaveGuards][0](),
update: (to, from) => [...route.updateGuards][0](to, from),
}
}
export async function destroyAgentPage(testApp) {
await testApp.store.dispatch('chatRuns/disconnect')
await testApp.afterEach()
vi.restoreAllMocks()
vi.clearAllTimers()
vi.useRealTimers()
}
export const useFakeTimers = () =>
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
export const warning = (wrapper) => wrapper.find('.agent-chat__warning')
export const saving = (wrapper) =>
wrapper.find('.agent-configuration__header [role="status"]')
export const openSection = (wrapper, key) =>
wrapper
.findAll('.menu-list__item-button')
.find((button) => button.text().includes(key))
.trigger('click')
export const instructions = (wrapper) =>
wrapper.get('.agent-configuration textarea')
export async function editInstructions(wrapper, value) {
await instructions(wrapper).setValue(value)
await instructions(wrapper).trigger('blur')
await flushPromises()
}
const field = (wrapper, label) =>
wrapper
.findAll('.agent-configuration__body .control')
.find((control) => control.get('.control__label').text().includes(label))
export const nameInput = (wrapper) => field(wrapper, 'agent.name').get('input')
export const providerDropdown = (wrapper) =>
field(wrapper, 'agent.provider').get('.dropdown')
export const modelDropdown = (wrapper) =>
field(wrapper, 'agent.model').get('.dropdown')
export const reasoningEffortDropdown = (wrapper) =>
field(wrapper, 'agent.reasoningEffort').get('.dropdown')
export const reasoningEffortWarning = (wrapper) =>
field(wrapper, 'agent.reasoningEffort').find('.control__messages--warning')
export const modelError = (wrapper) =>
field(wrapper, 'agent.model').find('.control__messages--error')
export async function choose(dropdown, text) {
await dropdown.get('.dropdown__selected').trigger('click')
await dropdown
.findAll('.select__item-link')
.find((item) => item.text().includes(text))
.trigger('click')
}
export const page = (results, next = null) => ({
count: results.length,
next,
previous: null,
results,
})
export const conversationsPage = (results, nextCursor = null) => ({
results,
next_cursor: nextCursor,
})
const conversationIds = new Map()
// The API lists equal moments by descending id, so the first one seen sorts first.
const conversationId = (uuid) => {
if (!conversationIds.has(uuid)) {
conversationIds.set(uuid, 1000 - conversationIds.size)
}
return conversationIds.get(uuid)
}
export const conversation = (
uuid,
title,
updatedOn = '2026-10-14T10:00:00Z',
id = conversationId(uuid)
) => ({
id,
uuid,
title,
shared: false,
started_by_trigger: false,
owner: viewer,
participants: [viewer],
created_on: '2026-10-14T10:00:00Z',
updated_on: updatedOn,
})
export const sharedConversation = (uuid, title, triggerType = 'periodic') => ({
...conversation(uuid, title),
shared: true,
started_by_trigger: true,
owner: null,
participants: [],
trigger_type: triggerType,
})
export const message = (
uuid,
content,
{
id,
role = 'user',
status = null,
errorCode = '',
runId = null,
steps = null,
sender = viewer,
} = {}
) => ({
id,
uuid,
role,
sender,
content,
created_on: '2026-10-14T10:00:00Z',
status,
error_code: errorCode,
run_id: runId,
steps,
})
export const acceptConversation = (config) => {
const body = JSON.parse(config.data)
return [
200,
{
conversation: conversation(body.uuid, body.content),
message: message(body.message_uuid, body.content),
},
]
}
export const composer = (wrapper) =>
wrapper.get('.agent-chat__composer textarea')
export const send = (wrapper) => wrapper.get('.agent-chat__composer button')
export const stop = (wrapper) => wrapper.get('.chat-composer__button--stop')
export async function sendMessage(wrapper, content) {
await composer(wrapper).setValue(content)
await send(wrapper).trigger('click')
await flushPromises()
}
export const composerExists = (wrapper) =>
wrapper.find('.agent-chat__composer').exists()
export async function selectConversation(wrapper, title) {
await wrapper
.findAll('.agent-conversations__item')
.find((item) => item.text().includes(title))
.trigger('click')
await flushPromises()
}
export const selected = (wrapper) =>
wrapper.get('.agent-conversations__item[aria-current="true"]')
export const messages = (wrapper) =>
wrapper
.findAll('.chat-message__bubble:not(.chat-message__bubble--error)')
.map((item) => item.text())
export const conversationTitles = (wrapper) =>
wrapper.findAll('.agent-conversations__item-name').map((item) => item.text())
/** Open a conversation's ⋮ menu and choose an action by its label. */
export async function chooseFromMenu(wrapper, title, action) {
await wrapper
.findAll('.agent-conversations__row')
.find((row) => row.text().includes(title))
.get('.agent-conversations__options')
.trigger('click')
await wrapper
.findAllComponents(Context)
.flatMap((menu) => menu.findAll('.context__menu-item-link'))
.find((link) => link.text().includes(action))
.trigger('click')
await flushPromises()
}
export async function filterConversations(wrapper, label) {
const dropdown = wrapper.get('.agent-conversations__filter')
await dropdown.get('.dropdown__selected').trigger('click')
await dropdown
.findAll('.select__item-link')
.find((item) => item.text() === label)
.trigger('click')
await flushPromises()
}