Files
baserow/web-frontend/modules/agent/components/AgentConversationList.vue
Davide Silvestri dcf2ce57b4 feat(agent): let people outside Baserow talk to an agent through a public chat (#6864)
* docs(agent): add ADR 016 on agent channels

A channel is a place outside the agent's own page where people talk to it and get its replies. It is its own concept beside triggers: a trigger reacts once to an event, a channel carries a conversation that continues.

* feat(agent): add channels and replies with no member behind them

A conversation a channel started is shared, has no owner and holds visitor messages. Its replies run on the channel's authority and stop once the channel is off, trashed or deleted. A reply that can call tools keeps its text out of the stream, so nothing written before a tool call reaches a visitor. Members can read such a conversation, filter for it and decide its held calls, but not write in it.

* feat(agent): add channel types, the visitor service and the channels API

Channel types are a registry and each type keeps its own data in a subclass. Builders list, add, change and delete an agent's channels, with audit actions and trash. One service holds everything an anonymous visitor may do.

* feat(agent): add the public chat channel with its visitor API

A public chat is a page with its own link and an optional password. Anyone with the link talks to the agent through an anonymous API that shows a message's text only; a signed token says which conversation is theirs.

* feat(agent): show visitor conversations to members

A conversation a channel started reads "Started by a visitor" in the list and can be filtered. The visitor's messages sit on the right under their label, and the composer gives way to a note, since members don't write in it.

* feat(agent): add the public chat page

The page a visitor opens from the link: the title and welcome text, the conversation, and a password form when the chat is protected. It keeps its tokens in local storage and recovers a reply through one sync path, so it never stays on the typing dots.

* feat(agent): add the Channels section to the agent configuration

A builder adds a public chat, copies its link, sets a title, a welcome text and a password, switches it off or deletes it. The link and password controls match the ones shared views and dashboards have.

* feat(agent): edit the public chat's welcome text with the rich text editor

The card shows the text formatted while it is written and saves it as markdown. The public page shows it read-only with the same component, so the builder sees what the visitor gets.

* feat(agent): give channels and visitor conversations their own icon

The person icon marks a private conversation and the globe the HTTP trigger, so channels use two bubbles: a conversation with someone outside the workspace.

* fix(agent): harden public chat replies, sends and exports after review

- A reply that can call tools keeps no draft: when it fails, is stopped or
  waits for approval, the visitor sees nothing rather than text it wrote
  before a tool call.
- One rule decides whether a channel can be used, for the visitor API and
  for the worker before a reply starts or resumes, licence included.
- Visitor sends can be repeated safely. A lost first message is recovered
  only with a secret key the page generated, never with ids members can read.
- Visitor conversations never become template examples, even when pinned.
- Visitor responses are never cached, and passwords are taken exactly as
  typed when set and when checked.

* fix(agent): harden the public chat page and Channels section after review

- The page sends a secret key with the first message and ids with the next
  ones, so a resend after a lost answer runs nothing twice, and shows each
  message once.
- It asks for a password when the chat became protected, retries a failed
  first load with backoff while saying so, and shows a stopped reply.
- The password modals wait for the server before the switch changes.
- In a workspace without Advanced or Enterprise a card only allows switching
  the chat off and deleting it.
- The welcome text is checked against its limit before it is saved.
- In a visitor's conversation the reject dialog says the visitor may see the
  reason, and the conversation filter is named Channels.

* fix(agent): fit the Permissions section description on one line

* fix(agent): open a protected public chat only once the server grants access

The page took a stored token as proof of access and guessed a refused one
from an empty title, so a failed info request after the password showed a
blank chat. The info endpoint now says whether the request has access, and
the page shows the chat only on that answer.

* fix(agent): open a protected public chat without flashing the password form

The server renders the page without the visitor's token, which only the
browser keeps, so a saved session showed the password form until the info
reloaded. The page now shows neither the form nor the chat until the
browser has checked its stored token.

* fix(agent): read the public chat from the primary database

A replica can lag behind a chat that was just switched off or given a
password, so visitors could keep using it until the replica caught up.

* fix(agent): cap the length of a public chat password guess

* fix(agent): back off syncing a public chat reply that waits for a member

A reply can wait for approval for hours, so the visitor page now checks
less often, up to once a minute, and right away when the tab is shown.

* fix(agent): refuse an agent message's uuid sent again by a visitor

A visitor and the agent both write without a sender, so a visitor resending
an agent message's uuid and text got it back as accepted, with no reply
after it, and a 500. The retry now also needs the role of the sender.

* fix(agent): keep syncing a resent public chat reply that waits for approval

A resend can get back a reply without a run, which opened no stream and
started no sync, so the page never showed the decision. Following a reply
now syncs whenever no stream follows it.

* fix(agent): send a heartbeat for each run record a visitor can't see

During a long tool run the visitor's stream dropped every record, so the
page saw nothing, reconnected every 15 seconds and replayed the hidden
records each time.

* fix(agent): word the approval and workspace access instructions for visitors

They told the agent that the reader approves held calls and can restore the
Run as identity, which is wrong for a visitor and shares internal
configuration with them.

* feat(agent): copy channels switched off with a link of their own

A copy of an agent now keeps its channels, so a builder doesn't have to set
them up again, but none answers before a member turns it on, and each gets
a new link. Only a duplicate or a snapshot restore keeps a public chat's
password; file exports and templates leave it out. Copied visitor
conversations stay on the copied channel.
2026-11-26 11:26:08 +00:00

507 lines
16 KiB
Vue

<template>
<aside class="agent-conversations" :aria-busy="loading">
<!-- The examples of a template are all shared and never wait or fail. -->
<Dropdown
v-if="!templatePreview"
class="agent-conversations__filter"
:model-value="filter"
:show-search="false"
:aria-label="$t('agent.filterConversations')"
@update:model-value="$emit('filter', $event)"
>
<DropdownItem
value="all"
:name="$t('agent.allConversations')"
icon="iconoir-filter-list"
/>
<DropdownItem
value="waiting"
:name="$t('agent.waiting')"
icon="iconoir-clock"
/>
<DropdownItem
value="failed"
:name="$t('agent.failed')"
icon="iconoir-warning-circle"
/>
<DropdownItem
value="pinned"
:name="$t('agent.pinned')"
icon="iconoir-pin"
/>
<DropdownItem
value="triggered"
:name="$t('agent.triggered')"
icon="iconoir-flash"
/>
<DropdownItem
value="visitors"
:name="$t('agent.channelsFilter')"
icon="iconoir-multi-bubble"
/>
<DropdownItem
value="private"
:name="$t('agent.private')"
icon="iconoir-user"
/>
<DropdownItem
value="shared"
:name="$t('agent.shared')"
icon="iconoir-community"
/>
</Dropdown>
<InfiniteScroll
ref="scroll"
class="agent-conversations__content"
:current-count="items.length"
:has-more-page="hasMore && !error"
:loading="loading"
:render-end="false"
fill
@load-next-page="$emit('load-more')"
>
<div class="agent-conversations__header">
{{
$t(
shownItems[0]?.pinned || filter === 'pinned'
? 'agent.pinned'
: 'agent.recent'
)
}}
</div>
<div
v-if="!error && loading && !items.length"
class="skeleton"
aria-hidden="true"
>
<div
v-for="width in ['75%', '55%', '85%', '65%']"
:key="width"
class="agent-conversations__skeleton-row"
>
<SkeletonBlock width="16px" height="16px" shape="circle" />
<SkeletonBlock :width="width" />
</div>
</div>
<ul v-if="shownItems.length" class="agent-conversations__list">
<template v-for="(item, index) in shownItems" :key="item.uuid">
<li
v-if="index > 0 && shownItems[index - 1].pinned && !item.pinned"
class="agent-conversations__header"
>
{{ $t('agent.recent') }}
</li>
<li
class="agent-conversations__row"
:class="{
'agent-conversations__row--manageable': hasOptions(item),
'agent-conversations__row--menu-open':
item.uuid === menuItem?.uuid,
}"
>
<div
v-if="item.uuid === renamingUuid"
class="agent-conversations__item agent-conversations__item--renaming"
>
<Icon
:icon="conversationIcon(item)"
type="secondary"
aria-hidden="true"
/>
<input
ref="renameInput"
v-model="renameTitle"
class="agent-conversations__rename"
maxlength="250"
:aria-label="$t('agent.conversationTitle')"
@keydown.enter="confirmRename($event, item)"
@keydown.esc.prevent="cancelRename(item)"
@blur="finishRename(item)"
/>
</div>
<button
v-else
:ref="(element) => setItemButton(item.uuid, element)"
type="button"
class="agent-conversations__item"
:class="{
'agent-conversations__item--selected': item.uuid === selected,
}"
:aria-current="item.uuid === selected ? 'true' : undefined"
@click="$emit('select', item)"
>
<span class="agent-conversations__origin">
<Icon
:icon="conversationIcon(item)"
type="secondary"
aria-hidden="true"
/>
<span
v-if="hasStatus(item)"
class="agent-conversations__status"
:class="`agent-conversations__status--${status(item)}`"
aria-hidden="true"
></span>
</span>
<span class="agent-conversations__text">
<span class="agent-conversations__title">
<span
class="agent-conversations__item-name"
:title="item.title"
>{{ item.title || $t('agent.newConversation') }}</span
>
<span
v-if="!item.shared"
class="agent-conversations__private"
role="img"
:aria-label="$t('agent.privateConversation')"
:title="$t('agent.privateConversation')"
><i class="iconoir-user" aria-hidden="true"></i
></span>
</span>
<span class="agent-conversations__meta">
<span
v-if="hasStatus(item)"
class="agent-conversations__status-label"
>{{ $t(`agent.${status(item)}`) }}</span
>
<span v-else class="agent-conversations__detail">{{
startedBy(item)
}}</span>
<span v-if="item.local" class="agent-conversations__draft">{{
$t('agent.draft')
}}</span>
<time
v-else-if="item.updated_on"
class="agent-conversations__age"
:datetime="item.updated_on"
>{{
getHumanAgoLabel(t, item.updated_on, now ?? undefined)
}}</time
>
</span>
</span>
</button>
<button
v-if="hasOptions(item) && item.uuid !== renamingUuid"
type="button"
class="agent-conversations__options"
:aria-label="$t('agent.conversationOptions')"
aria-haspopup="menu"
:aria-expanded="item.uuid === menuItem?.uuid ? 'true' : 'false'"
@click="toggleMenu($event.currentTarget, item)"
>
<i class="baserow-icon-more-vertical" aria-hidden="true"></i>
</button>
</li>
</template>
</ul>
<p v-else-if="!loading && !error" class="agent-conversations__empty">
{{
$t(
filter === 'all'
? 'agent.noConversations'
: 'agent.noMatchingConversations'
)
}}
</p>
<Alert v-if="error" type="error" class="margin-top-2">
{{ $t('agent.conversationsLoadError') }}
<template #actions
><Button
type="secondary"
size="small"
button-type="button"
@click="$emit('retry')"
>{{ $t('action.retry') }}</Button
></template
>
</Alert>
</InfiniteScroll>
<div v-if="canCreate" class="agent-conversations__footer">
<Button
type="secondary"
button-type="button"
icon="iconoir-plus"
full-width
:disabled="!readyToSend"
@click="$emit('create')"
>{{ $t('agent.newConversation') }}</Button
>
</div>
<Context ref="menu" @hidden="menuItem = null">
<ul v-if="menuItem" class="context__menu">
<li
v-if="canUpdateItem(menuItem) && !menuItem.shared"
class="context__menu-item"
>
<a class="context__menu-item-link" @click="share">
<i class="context__menu-item-icon iconoir-community"></i>
{{ $t('agent.share') }}
</a>
</li>
<li v-if="canUpdateItem(menuItem)" class="context__menu-item">
<a class="context__menu-item-link" @click="togglePin">
<i class="context__menu-item-icon iconoir-pin"></i>
{{ $t(menuItem?.pinned ? 'agent.unpin' : 'agent.pin') }}
</a>
</li>
<li v-if="canUpdateItem(menuItem)" class="context__menu-item">
<a class="context__menu-item-link" @click="startRename">
<i class="context__menu-item-icon iconoir-edit-pencil"></i>
{{ $t('action.rename') }}
</a>
</li>
<li
v-if="canDeleteItem(menuItem)"
class="context__menu-item"
:class="{
'context__menu-item--with-separator': canUpdateItem(menuItem),
}"
>
<a
class="context__menu-item-link context__menu-item-link--delete"
@click="remove"
>
<i class="context__menu-item-icon iconoir-bin"></i>
{{ $t('action.delete') }}
</a>
</li>
<li v-if="canLeaveItem(menuItem)" class="context__menu-item">
<a
class="context__menu-item-link context__menu-item-link--delete"
@click="leave"
>
<i class="context__menu-item-icon iconoir-bin"></i>
{{ $t('agent.deleteForMe') }}
</a>
</li>
</ul>
</Context>
<AgentShareConversationModal
ref="shareModal"
@share="$emit('share', $event)"
/>
<AgentDeleteConversationModal
ref="deleteModal"
@leave="$emit('leave', $event)"
@delete="$emit('delete', $event)"
/>
</aside>
</template>
<script setup>
import { inject, nextTick, ref, watch } from 'vue'
import { useStore } from 'vuex'
import Icon from '@baserow/modules/core/components/Icon'
import Context from '@baserow/modules/core/components/Context'
import InfiniteScroll from '@baserow/modules/core/components/helpers/InfiniteScroll'
import AgentShareConversationModal from '@baserow/modules/agent/components/AgentShareConversationModal'
import { useI18n } from 'vue-i18n'
import AgentDeleteConversationModal from '@baserow/modules/agent/components/AgentDeleteConversationModal'
import { managesConversation } from '@baserow/modules/agent/utils/conversations'
import { useNuxtApp } from '#app'
import { getHumanAgoLabel } from '@baserow/modules/core/utils/date'
import { injectNow } from '@baserow/modules/core/composables/useNow'
import { serviceTypeOf } from '@baserow/modules/agent/utils/triggers'
const props = defineProps({
items: { type: Array, required: true },
filter: { type: String, default: 'all' },
selected: { type: String, default: null },
loading: Boolean,
error: Boolean,
hasMore: Boolean,
canCreate: Boolean,
readyToSend: Boolean,
canUpdate: Boolean,
canDelete: Boolean,
/** Whether the viewer may update the agent, which shared conversations require. */
canUpdateAgent: Boolean,
})
const emit = defineEmits([
'select',
'filter',
'retry',
'load-more',
'create',
'update',
'share',
'leave',
'delete',
])
const { $registry } = useNuxtApp()
const { t } = useI18n()
const store = useStore()
const now = injectNow()
const templatePreview = inject('agentTemplatePreview', false)
const scroll = ref(null)
const menu = ref(null)
const menuItem = ref(null)
const shareModal = ref(null)
const deleteModal = ref(null)
const renameInput = ref([])
const renamingUuid = ref(null)
const renameTitle = ref('')
// Chrome blurs a focused input that the list moves, which would end the rename.
const shownItems = ref(props.items)
const itemButtons = {}
let renameOriginal = ''
function conversationIcon(item) {
if (item.started_by_channel) return 'iconoir-multi-bubble'
return (
serviceTypeOf($registry, item.trigger_type)?.icon || 'iconoir-chat-bubble'
)
}
/** The trigger, the visitor or the person that started the conversation. */
function startedBy(item) {
if (item.started_by_channel) return t('agent.startedByVisitor')
if (item.started_by_trigger) {
return (
item.trigger_name ||
serviceTypeOf($registry, item.trigger_type)?.name ||
t('agent.startedByTrigger')
)
}
if (!item.owner) {
// An example came with an import or a template, so it never had an owner.
if (item.is_example) return t('agent.exampleConversation')
return item.shared ? t('agent.deletedSender') : ''
}
return item.owner.id === store.getters['auth/getUserId']
? t('agent.you')
: item.owner.name
}
const managesItem = (item) =>
managesConversation(
item,
store.getters['auth/getUserId'],
props.canUpdateAgent
)
const canUpdateItem = (item) => props.canUpdate && managesItem(item)
const canDeleteItem = (item) => props.canDelete && managesItem(item)
// Those asked to approve may only remove it from their own list.
const canLeaveItem = (item) =>
props.canDelete && !item.shared && !managesItem(item)
// A draft exists only in this tab until its first message is sent.
const hasOptions = (item) =>
!item.local &&
(canUpdateItem(item) || canDeleteItem(item) || canLeaveItem(item))
const isListed = (uuid) => props.items.some((item) => item.uuid === uuid)
watch([() => props.items, renamingUuid], ([items, renaming]) => {
if (!renaming) shownItems.value = items
})
watch(
() => props.filter,
() => {
if (scroll.value) scroll.value.$el.scrollTop = 0
menu.value?.hide()
renamingUuid.value = null
}
)
// Another session can delete the conversation whose menu or rename is open.
watch(
() => props.items,
() => {
if (menuItem.value && !isListed(menuItem.value.uuid)) menu.value.hide()
if (renamingUuid.value && !isListed(renamingUuid.value)) {
renamingUuid.value = null
}
}
)
function setItemButton(uuid, element) {
if (element) itemButtons[uuid] = element
else delete itemButtons[uuid]
}
function status(item) {
if (item.pending_approval_count > 0) return 'waiting'
if (item.run_id) return 'replying'
return item.last_reply_failed ? 'failed' : null
}
function hasStatus(item) {
return status(item) !== null
}
function toggleMenu(target, item) {
if (menuItem.value?.uuid === item.uuid) return menu.value.hide()
menuItem.value = item
menu.value.show(target, 'bottom', 'right', 4)
}
async function startRename() {
const item = menuItem.value
menu.value.hide()
renameOriginal = item.title
renameTitle.value = item.title
renamingUuid.value = item.uuid
await nextTick()
renameInput.value[0]?.focus()
renameInput.value[0]?.select()
}
function finishRename(item) {
if (renamingUuid.value !== item.uuid || !isListed(item.uuid)) return
renamingUuid.value = null
const title = renameTitle.value.trim()
if (title && title !== renameOriginal) emit('update', item, { title })
}
async function confirmRename(event, item) {
// Enter also confirms an input method's composition.
if (event.isComposing || event.keyCode === 229) return
event.preventDefault()
finishRename(item)
await nextTick()
itemButtons[item.uuid]?.focus()
}
async function cancelRename(item) {
renamingUuid.value = null
await nextTick()
itemButtons[item.uuid]?.focus()
}
function togglePin() {
const item = menuItem.value
// Pinning a shared conversation is what makes it an example of exports.
const makesExample = !item.pinned && item.shared && !item.is_example
menu.value.hide()
emit('update', item, { pinned: !item.pinned })
if (makesExample) {
store.dispatch('toast/info', {
title: t('agent.pinnedSharedTitle'),
message: t('agent.pinnedSharedMessage'),
})
}
}
function share() {
const item = menuItem.value
menu.value.hide()
shareModal.value.show(item)
}
function remove() {
const item = menuItem.value
menu.value.hide()
if (!item.shared && item.participants.length > 1) deleteModal.value.show(item)
else emit('delete', item)
}
function leave() {
const item = menuItem.value
menu.value.hide()
deleteModal.value.show(item, { forEveryone: false })
}
</script>