🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(channel): message kinds and Agent ask cards (#23611)
Arvin Xuc35647e2360d
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex 8cd55eafbe1..aa5c3bc9aa1 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -1,5 +1,5 @@import type { BotWakeDecisionPage } from '@lobechat/types';-import { CHANNEL_LIMITS, SIGNAL_DECISION_OUTCOMES } from '@lobechat/types';+import { CHANNEL_ASK_LIMITS, CHANNEL_LIMITS, SIGNAL_DECISION_OUTCOMES } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -496,6 +496,29 @@ export const channelRouter = router({data: await ctx.channelService.retryRouting(input.channelId, input.messageId),success: true,})),+ answerAsk: channelProcedure+ .input(+ z.object({+ answers: z+ .array(+ z.object({+ other: z.string().max(CHANNEL_ASK_LIMITS.otherLength).optional(),+ selected: z+ .array(z.string().max(CHANNEL_ASK_LIMITS.labelLength))+ .max(CHANNEL_ASK_LIMITS.maxOptions),+ }),+ )+ .min(1)+ .max(CHANNEL_ASK_LIMITS.maxQuestions),+ channelId,+ messageId: z.uuid(),+ requestKey: z.string().min(1).max(200),+ }),+ )+ .mutation(async ({ ctx, input }) => ({+ data: await ctx.channelService.answerAsk(input.channelId, input),+ success: true,+ })),send: externalChannelProcedure.input(z.object({diff --git a/apps/server/src/services/channel/ChannelCoordinator.silence.test.ts b/apps/server/src/services/channel/ChannelCoordinator.silence.test.tsindex dcbfb866a87..6fd8682013a 100644--- a/apps/server/src/services/channel/ChannelCoordinator.silence.test.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.silence.test.ts@@ -110,4 +110,19 @@ describe('Channel completion of a wake that may stay silent', () => {expect(findLatest).not.toHaveBeenCalled();expect(executions.publish).not.toHaveBeenCalled();});++ it('still posts a question the run asked, even when it ended in silence or a tool call', async () => {+ const ask = { questions: [{ options: [{ label: 'A' }, { label: 'B' }], question: 'Which?' }] };+ findLatest.mockResolvedValue({ content: 'NO_REPLY' });+ await coordinator({ ask, wake: { kind: 'followup' } }).complete('channel', 'job', 'op');+ expect(executions.silence).not.toHaveBeenCalled();+ expect(executions.saveDraft).toHaveBeenCalledWith('channel', 'job', '');+ expect(executions.publish).toHaveBeenCalled();++ vi.clearAllMocks();+ findLatest.mockResolvedValue({ content: '', tools: [{ id: 'call' }] });+ await coordinator({ ask, wake: null }).complete('channel', 'job', 'op');+ expect(executions.saveDraft).toHaveBeenCalledWith('channel', 'job', '');+ expect(executions.publish).toHaveBeenCalled();+ });});diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.tsindex ff619633241..a5c4f3f6c2a 100644--- a/apps/server/src/services/channel/ChannelCoordinator.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.ts@@ -535,22 +535,26 @@ export class ChannelCoordinator {const content = final?.tools?.length ? undefined : extractTextFromMessage(final);// A wake nobody asked for may end in silence. Settled like a reply, not a failure.// A run that stopped on a tool call (out of steps) did not choose silence: it failed.- const silence = final?.tools?.length- ? undefined- : detectNoReply({ content, wakeKind: job.wake?.kind });+ // A run that asked its requester something always posts the questions, whatever it+ // wrote around them: a card nobody sees cannot be answered.+ const silence =+ final?.tools?.length || job.ask+ ? undefined+ : detectNoReply({ content, wakeKind: job.wake?.kind });if (silence && (await this.executions.silence(channelId, jobId, silence.reason))) {await this.stopWriters([job]);await notifyChannel(this.db, channelId);return;}- if (!content?.trim()) {+ const text = job.ask && detectNoReply({ content, wakeKind: 'followup' }) ? '' : content;+ if (!text?.trim() && !job.ask) {await this.stopWriters([job]);await notifyChannel(this.db, channelId);return;}await this.executions.accepted(channelId, jobId);- await this.executions.saveDraft(channelId, jobId, content);- reply = content;+ await this.executions.saveDraft(channelId, jobId, text ?? '');+ reply = text ?? '';}const replyMessageId = await this.executions.publish(channelId, jobId);await this.stopWriters([job]);diff --git a/apps/server/src/services/channel/ChannelHistoryService.ts b/apps/server/src/services/channel/ChannelHistoryService.tsindex e3f9620abef..d72a7bad6c8 100644--- a/apps/server/src/services/channel/ChannelHistoryService.ts+++ b/apps/server/src/services/channel/ChannelHistoryService.ts@@ -1,5 +1,7 @@import { getOfficialMcpServerById, resolveConnectorCatalogItem } from '@lobechat/const';import type {+ ChannelAskedUser,+ ChannelAskUserParams,ChannelConnectorRequest,ChannelConnectorRequestResult,ChannelListThreadsParams,@@ -7,6 +9,7 @@ import type {ChannelReadMessagesParams,ChannelRequestConnectorParams,} from '@lobechat/types';+import { normalizeChannelAskInput } from '@lobechat/types';import pMap from 'p-map';import { composioEnv } from '@/config/composio';@@ -94,6 +97,19 @@ export class ChannelHistoryService {this.repository = new ChannelHistoryRepository(db, userId, workspaceId);}+ /** Holds the run's questions; publishing its reply posts them as an `ask` card. */+ askUser = async (params: ChannelAskUserParams): Promise<ChannelAskedUser> => {+ await assertChannelEnabled(this.userId);+ let input;+ try {+ input = normalizeChannelAskInput(params);+ } catch (error) {+ throw new ChannelError('BAD_REQUEST', (error as Error).message);+ }+ await this.repository.ask(this.operationId, input);+ return { questions: input.questions.length, status: 'posts_with_reply' };+ };+readMessages = async (params: ChannelReadMessagesParams) => {await assertChannelEnabled(this.userId);return this.repository.readMessages(this.operationId, params);diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex 20094d8a3e5..22c55de4a4d 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -25,6 +25,8 @@ import type {ChannelStopScope,} from '@/database/repositories/channel';import { ChannelError, ChannelRepository } from '@/database/repositories/channel';+import type { ChannelAskAnswerInput } from '@/database/repositories/channel/ask';+import { answerAsk } from '@/database/repositories/channel/ask';import {projectDefaultChannelMetadata,withDisplayTitle,@@ -695,6 +697,15 @@ export class ChannelService {return message;};+ /** Answers an Agent's question as the person it asked; the answer wakes that Agent. */+ answerAsk = async (channelId: string, input: ChannelAskAnswerInput) => {+ const message = await this.repository.write(channelId, (tx, access) =>+ answerAsk(tx, access, input, channelContacts),+ );+ await Promise.all([wakeChannel(channelId), this.changed(channelId)]);+ return message;+ };+retryRouting = async (channelId: string, messageId: string) => {const message = await this.repository.retryRouting(channelId, messageId);await Promise.all([wakeChannel(channelId), this.changed(channelId)]);diff --git a/apps/server/src/services/channel/deviceGrantCard.ts b/apps/server/src/services/channel/deviceGrantCard.tsindex e482accd495..af172f1a67e 100644--- a/apps/server/src/services/channel/deviceGrantCard.ts+++ b/apps/server/src/services/channel/deviceGrantCard.ts@@ -109,6 +109,7 @@ export const announceDeviceGrants = async (db: LobeChatDatabase, channelId: striawait new ChannelRepository(db, deviceOwnerId, scope).postAgentMessage(direct.channel.id, {agentId,content: deviceGrantRequestText(card),+ kind: 'deviceGrant',metadata: { deviceGrant: card },requestKey: deviceGrantCardKey(request.grantId),});diff --git a/docs/development/database-schema.dbml b/docs/development/database-schema.dbmlindex 034595472e0..163e8211cf9 100644--- a/docs/development/database-schema.dbml+++ b/docs/development/database-schema.dbml@@ -1695,6 +1695,7 @@ table channel_jobs {writer_held boolean [not null, default: false]isolated_at "timestamp with time zone"draft text+ ask jsonbpublication_revoked boolean [not null, default: false]published_message_id uuidcreated_at "timestamp with time zone" [not null, default: `now()`]@@ -1794,6 +1795,7 @@ table channel_messages {channel_id text [not null]thread_id textsequence integer [not null]+ kind text [not null, default: 'text']content text [not null]user_id textagent_id textdiff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 3481b52a098..dbe9fd1dfdc 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -14,6 +14,13 @@"archived": "Archived","archivedGroup": "Archived · {{count}}","archivedNotice": "This channel is archived. Its history stays readable, but it takes no new messages.",+ "ask.answeredBy": "Answered by {{name}}",+ "ask.failed": "Couldn't send your answer. Try again.",+ "ask.multiSelect": "Choose all that apply",+ "ask.other": "Other",+ "ask.otherPlaceholder": "Type your answer",+ "ask.submit": "Send answer",+ "ask.waitingFor": "Waiting for {{name}} to answer","attachments.failed": "Upload failed. Try again.","attachments.failedShort": "Upload failed","attachments.limit": "Attach up to {{count}} files.",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex fe2fc459174..54f987df1d2 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -283,6 +283,7 @@"builtins.lobe-canvas.apiName.readCanvasGuide": "Read canvas guide","builtins.lobe-canvas.apiName.updateCanvas": "Update canvas","builtins.lobe-canvas.title": "Canvas",+ "builtins.lobe-channel.apiName.askUser": "Ask with options","builtins.lobe-channel.apiName.createThread": "Open Thread","builtins.lobe-channel.apiName.listChannels": "List Channels","builtins.lobe-channel.apiName.listPeople": "List people",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 9a0192c10bf..9edfed0beed 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -14,6 +14,13 @@"archived": "已归档","archivedGroup": "已归档 · {{count}}","archivedNotice": "此频道已归档。历史消息仍可查看,但不再接收新消息。",+ "ask.answeredBy": "{{name}} 已回答",+ "ask.failed": "回答没有发出去,请重试。",+ "ask.multiSelect": "可多选",+ "ask.other": "其他",+ "ask.otherPlaceholder": "输入你的回答",+ "ask.submit": "发送回答",+ "ask.waitingFor": "等待 {{name}} 回答","attachments.failed": "上传失败,请重试。","attachments.failedShort": "上传失败","attachments.limit": "最多添加 {{count}} 个附件。",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 5ab7dad97c0..98e030a7dc0 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -283,6 +283,7 @@"builtins.lobe-canvas.apiName.readCanvasGuide": "读取画布指南","builtins.lobe-canvas.apiName.updateCanvas": "更新画布","builtins.lobe-canvas.title": "画布",+ "builtins.lobe-channel.apiName.askUser": "发起选择题","builtins.lobe-channel.apiName.createThread": "开启子区","builtins.lobe-channel.apiName.listChannels": "列出频道","builtins.lobe-channel.apiName.listPeople": "列出可发消息的人",diff --git a/packages/builtin-tool-channel/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-channel/src/ExecutionRuntime/index.test.tsindex c779ab0bfb5..65dacbdffac 100644--- a/packages/builtin-tool-channel/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-channel/src/ExecutionRuntime/index.test.ts@@ -148,6 +148,36 @@ describe('Channel messaging', () => {});});+describe('Channel askUser', () => {+ const questions = [{ options: [{ label: 'A' }, { label: 'B' }], question: 'Which?' }];++ it('holds the questions and tells the run to end its turn instead of waiting', async () => {+ const askUser = vi.fn().mockResolvedValue({ questions: 1, status: 'posts_with_reply' });+ const runtime = new ChannelExecutionRuntime({+ askUser,+ readMessage: vi.fn(),+ readMessages: vi.fn(),+ });+ const result = await runtime.askUser({ questions });+ expect(askUser).toHaveBeenCalledWith({ questions });+ expect(result).toMatchObject({ state: { status: 'posts_with_reply' }, success: true });+ expect(result.content).toContain('End your turn now');+ });++ it('reports a refused ask as a tool error the model can correct', async () => {+ const runtime = new ChannelExecutionRuntime({+ askUser: vi.fn().mockRejectedValue(new Error('Question 1 has duplicate options')),+ readMessage: vi.fn(),+ readMessages: vi.fn(),+ });+ expect(await runtime.askUser({ questions })).toMatchObject({+ content: 'Question 1 has duplicate options',+ error: { type: 'ChannelAskError' },+ success: false,+ });+ });+});+describe('Channel connector requests', () => {it('posts the card and tells the Agent the connector comes next turn', async () => {const requestConnector = vidiff --git a/packages/builtin-tool-channel/src/ExecutionRuntime/index.ts b/packages/builtin-tool-channel/src/ExecutionRuntime/index.tsindex aa28c7f5af9..2fa65f3eba8 100644--- a/packages/builtin-tool-channel/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-channel/src/ExecutionRuntime/index.ts@@ -1,6 +1,8 @@import { projectChannelHistory } from '@lobechat/prompts/channel';import type {BuiltinServerRuntimeOutput,+ ChannelAskedUser,+ ChannelAskUserParams,ChannelConnectorRequestResult,ChannelCreatedThread,ChannelCreateThreadParams,@@ -29,6 +31,8 @@ import type {} from '@lobechat/types';export interface ChannelHistoryService {+ /** Holds the run's questions for its reply; see `ChannelHistoryRepository.ask`. */+ askUser?: (params: ChannelAskUserParams) => Promise<ChannelAskedUser>;readMessage: (params: ChannelReadMessageParams) => Promise<ChannelHistoryMessageDetail>;readMessages: (params: ChannelReadMessagesParams) => Promise<ChannelHistoryPage>;/** Posts a card in the run's conversation; the runtime binds the run and tool call. */@@ -114,6 +118,21 @@ export class ChannelExecutionRuntime {}}+ askUser = async (params: ChannelAskUserParams): Promise<BuiltinServerRuntimeOutput> => {+ try {+ if (!this.service.askUser) throw new Error('Asking is not available in this run');+ const state = await this.service.askUser(params);+ return {+ content:+ 'The question will be posted as a card with your final answer. End your turn now with a short lead-in to it, without listing the options. The answer arrives later as a new request replying to your question.',+ state,+ success: true,+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Could not ask the question';+ return { content: message, error: { type: 'ChannelAskError', message }, success: false };+ }+ };requestConnector = async (params: ChannelRequestConnectorParams,): Promise<BuiltinServerRuntimeOutput> => {diff --git a/packages/builtin-tool-channel/src/client/Inspector/index.tsx b/packages/builtin-tool-channel/src/client/Inspector/index.tsxindex 5156cdc83be..b290bb1462c 100644--- a/packages/builtin-tool-channel/src/client/Inspector/index.tsx+++ b/packages/builtin-tool-channel/src/client/Inspector/index.tsx@@ -2,6 +2,7 @@import type {BuiltinInspectorProps,+ ChannelAskUserParams,ChannelDirectoryPage,ChannelHistoryMessageDetail,ChannelHistoryPage,@@ -112,6 +113,22 @@ const MessagePersonInspector = memo<});MessagePersonInspector.displayName = 'ChannelMessagePersonInspector';+/** The question being asked, so the step reads as what the Agent wants to know. */+const AskUserInspector = memo<BuiltinInspectorProps<ChannelAskUserParams, unknown>>(+ ({ args, isArgumentsStreaming, isLoading }) => {+ const { t } = useTranslation('plugin');+ const loading = isArgumentsStreaming || isLoading;+ const question = args?.questions?.[0]?.question;+ return (+ <div className={cx(inspectorTextStyles.root, loading && shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-channel.apiName.askUser')}</span>+ {question && <span>{question}</span>}+ </div>+ );+ },+);+AskUserInspector.displayName = 'ChannelAskUserInspector';+const THREAD_API_NAMES = [ChannelApiName.createThread,ChannelApiName.listThreads,@@ -146,6 +163,7 @@ ThreadInspector.displayName = 'ChannelThreadInspector';export const ChannelInspectors = {...Object.fromEntries(THREAD_API_NAMES.map((name) => [name, ThreadInspector])),+ [ChannelApiName.askUser]: AskUserInspector,[ChannelApiName.listChannels]: ListChannelsInspector,[ChannelApiName.listPeople]: ListPeopleInspector,[ChannelApiName.messagePerson]: MessagePersonInspector,diff --git a/packages/builtin-tool-channel/src/manifest.ts b/packages/builtin-tool-channel/src/manifest.tsindex 2d386953895..d71a52eba2c 100644--- a/packages/builtin-tool-channel/src/manifest.ts+++ b/packages/builtin-tool-channel/src/manifest.ts@@ -1,4 +1,5 @@import type { BuiltinToolManifest } from '@lobechat/types';+import { CHANNEL_ASK_LIMITS } from '@lobechat/types';import { systemPrompt } from './systemRole';import { ChannelApiName, ChannelIdentifier } from './types';@@ -14,6 +15,63 @@ export const ChannelManifest: BuiltinToolManifest = {'Read the current shared conversation, message Agents in your other Channels, and message people for your requester.',},api: [+ {+ name: ChannelApiName.askUser,+ description:+ "Ask your requester to choose, as a card of options posted with your final answer. Use it when you need their decision to go on and the choices can be listed, e.g. which area to start with. The run does not wait: after calling it, end your turn with a short lead-in to the question (do not repeat the options, the card shows them). Their pick arrives later as a new request replying to your question, and you continue from there. Every card also offers 'Other' for their own words. Once per reply; only for a person's own request.",+ parameters: {+ type: 'object',+ additionalProperties: false,+ required: ['questions'],+ properties: {+ questions: {+ type: 'array',+ minItems: 1,+ maxItems: CHANNEL_ASK_LIMITS.maxQuestions,+ items: {+ type: 'object',+ additionalProperties: false,+ required: ['question', 'options'],+ properties: {+ question: {+ type: 'string',+ maxLength: CHANNEL_ASK_LIMITS.questionLength,+ description: "The question, in your requester's language.",+ },+ header: {+ type: 'string',+ maxLength: CHANNEL_ASK_LIMITS.headerLength,+ description: 'Optional short label above the question.',+ },+ multiSelect: {+ type: 'boolean',+ description: 'Allow picking several options. Default false.',+ },+ options: {+ type: 'array',+ minItems: CHANNEL_ASK_LIMITS.minOptions,+ maxItems: CHANNEL_ASK_LIMITS.maxOptions,+ description: "Distinct choices; do not add an 'Other' option, the card has one.",+ items: {+ type: 'object',+ additionalProperties: false,+ required: ['label'],+ properties: {+ label: { type: 'string', maxLength: CHANNEL_ASK_LIMITS.labelLength },+ description: {+ type: 'string',+ maxLength: CHANNEL_ASK_LIMITS.descriptionLength,+ description: 'Optional one-line explanation.',+ },+ },+ },+ },+ },+ },+ },+ },+ },+ },{name: ChannelApiName.readMessages,description:diff --git a/packages/builtin-tool-channel/src/systemRole.ts b/packages/builtin-tool-channel/src/systemRole.tsindex 43cc227161a..7c5fd95db38 100644--- a/packages/builtin-tool-channel/src/systemRole.ts+++ b/packages/builtin-tool-channel/src/systemRole.ts@@ -6,6 +6,7 @@ export const systemPrompt = `You can read the public history of your current Lob- **listChannels**: Find the Channels your requester belongs to and the Agents in each, to know where another Agent can be reached.- **sendMessage**: Tell or ask another Agent something and let it decide what to do: send it a self-contained message by agentIds. One Agent is asked in the conversation between you two: its answer wakes you there, and what you then write is posted back where you asked. Several Agents addressed together in a group (channelId) answer in that group, and the reply is brought back to you here as a new request marked \`reply_from\`. The person sees a notice of the message, so in your final answer now say in a sentence what you asked and that the answer will follow, without a link, without opening a Thread and without waiting for the reply. When the request is to hand a message to an Agent, this is the tool, not creating a task; create a task only for concrete work to be tracked.- **requestConnector**: When the person asks you to connect an app or MCP server, or the task needs a connector that is not connected, post a card they connect with one click; never paste an authorization link or ask for a key in chat. Then say in your answer that the card is there; the connector is usable from your next turn once they connect it.+- **askUser**: When you need your requester to decide between options before you can go on, ask with a card instead of a question in prose: they pick with one tap. The run does not wait; end your turn with a one-line lead-in to the question. Their answer arrives as a new request replying to your question. Ask only what blocks you, at most once per reply.- **listPeople** / **messagePerson**: Message a person for your requester, e.g. "let Alice know when you are done": find them with listPeople, then send a self-contained message. It is posted in your requester's one-on-one conversation with that person, marked as sent by you, and notifies them; nobody answers you there. Send it once the work it reports is done. If the name matches several people or nobody, ask your requester instead of guessing.**Parallel work in Threads.** Each Thread of this Channel is a separate conversation where you can answer in parallel. When the person talks about "the tasks" or "the first one / the third one", they usually mean your replies in this Channel's Threads; act on them directly, not by creating tasks:- **listThreads**: See every Thread, what it is about, and whether your reply there is queued, running or finished, with a running reply's latest steps. Call it first whenever the person asks about progress or refers to work by position or topic, then map their words to Threads.diff --git a/packages/builtin-tool-channel/src/types.ts b/packages/builtin-tool-channel/src/types.tsindex 1fdc6dce9c5..a3aa7683e0c 100644--- a/packages/builtin-tool-channel/src/types.ts+++ b/packages/builtin-tool-channel/src/types.ts@@ -1,5 +1,6 @@export const ChannelIdentifier = 'lobe-channel';export const ChannelApiName = {+ askUser: 'askUser',createThread: 'createThread',listChannels: 'listChannels',listPeople: 'listPeople',diff --git a/packages/database/migrations/0228_channel_message_kind.sql b/packages/database/migrations/0228_channel_message_kind.sqlnew file mode 100644index 00000000000..56993a97610--- /dev/null+++ b/packages/database/migrations/0228_channel_message_kind.sql@@ -0,0 +1,9 @@+ALTER TABLE "channel_jobs" ADD COLUMN IF NOT EXISTS "ask" jsonb;--> statement-breakpoint+ALTER TABLE "channel_messages" ADD COLUMN IF NOT EXISTS "kind" text DEFAULT 'text' NOT NULL;--> statement-breakpoint+UPDATE "channel_messages"+SET "kind" = CASE+ WHEN "metadata" ? 'card' THEN 'contact'+ WHEN "metadata" ? 'replyError' THEN 'error'+ ELSE 'deviceGrant'+END+WHERE "kind" = 'text' AND ("metadata" ? 'card' OR "metadata" ? 'replyError' OR "metadata" ? 'deviceGrant');diff --git a/packages/database/migrations/meta/0218_snapshot.json b/packages/database/migrations/meta/0228_snapshot.jsonsimilarity index 97%rename from packages/database/migrations/meta/0218_snapshot.jsonrename to packages/database/migrations/meta/0228_snapshot.jsonindex 259a59fb31c..8ff3e7fec53 100644--- a/packages/database/migrations/meta/0218_snapshot.json+++ b/packages/database/migrations/meta/0228_snapshot.json@@ -6,9 +6,9 @@},"dialect": "postgresql","enums": {},- "id": "f333c27e-af69-4fc7-bb95-59bf849ced71",+ "id": "38a32be4-f43d-4774-91c3-745834c6b6fc","policies": {},- "prevId": "44fde6f5-404e-4745-a43d-3fa16db429c8",+ "prevId": "315a7566-001a-43ff-a05a-5187c926f646","roles": {},"schemas": {},"sequences": {@@ -2752,6 +2752,596 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.agent_deliveries": {+ "name": "agent_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "subject_type": {+ "name": "subject_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "subject_id": {+ "name": "subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "parent_delivery_id": {+ "name": "parent_delivery_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "requester_user_id": {+ "name": "requester_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "channel_id": {+ "name": "channel_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "category": {+ "name": "category",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unknown'"+ },+ "outcome_source": {+ "name": "outcome_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "outcome_confidence": {+ "name": "outcome_confidence",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "shots": {+ "name": "shots",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "frictions": {+ "name": "frictions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "total_cost": {+ "name": "total_cost",+ "type": "numeric(20, 6)",+ "primaryKey": false,+ "notNull": false+ },+ "total_tokens": {+ "name": "total_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "tool_calls": {+ "name": "tool_calls",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_messages": {+ "name": "user_messages",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "agent_messages": {+ "name": "agent_messages",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "settled_at": {+ "name": "settled_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "distilled_at": {+ "name": "distilled_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_deliveries_subject_agent_unique": {+ "name": "agent_deliveries_subject_agent_unique",+ "columns": [+ {+ "expression": "subject_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_deliveries_agent_id_settled_at_idx": {+ "name": "agent_deliveries_agent_id_settled_at_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "settled_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_deliveries_user_id_settled_at_idx": {+ "name": "agent_deliveries_user_id_settled_at_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "settled_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_deliveries_workspace_id_settled_at_idx": {+ "name": "agent_deliveries_workspace_id_settled_at_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "settled_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_deliveries\".\"workspace_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_deliveries_parent_delivery_id_idx": {+ "name": "agent_deliveries_parent_delivery_id_idx",+ "columns": [+ {+ "expression": "parent_delivery_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_deliveries\".\"parent_delivery_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_deliveries_project_id_idx": {+ "name": "agent_deliveries_project_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_deliveries\".\"project_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_deliveries_task_id_idx": {+ "name": "agent_deliveries_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_deliveries\".\"task_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_deliveries_agent_id_agents_id_fk": {+ "name": "agent_deliveries_agent_id_agents_id_fk",+ "tableFrom": "agent_deliveries",+ "tableTo": "agents",+ "columnsFrom": ["agent_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_deliveries_user_id_users_id_fk": {+ "name": "agent_deliveries_user_id_users_id_fk",+ "tableFrom": "agent_deliveries",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_deliveries_workspace_id_workspaces_id_fk": {+ "name": "agent_deliveries_workspace_id_workspaces_id_fk",+ "tableFrom": "agent_deliveries",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_deliveries_parent_delivery_id_agent_deliveries_id_fk": {+ "name": "agent_deliveries_parent_delivery_id_agent_deliveries_id_fk",+ "tableFrom": "agent_deliveries",+ "tableTo": "agent_deliveries",+ "columnsFrom": ["parent_delivery_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "agent_deliveries_requester_user_id_users_id_fk": {+ "name": "agent_deliveries_requester_user_id_users_id_fk",+ "tableFrom": "agent_deliveries",+ "tableTo": "users",+ "columnsFrom": ["requester_user_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "agent_deliveries_project_id_projects_id_fk": {+ "name": "agent_deliveries_project_id_projects_id_fk",+ "tableFrom": "agent_deliveries",+ "tableTo": "projects",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "agent_deliveries_channel_id_channels_id_fk": {+ "name": "agent_deliveries_channel_id_channels_id_fk",+ "tableFrom": "agent_deliveries",+ "tableTo": "channels",+ "columnsFrom": ["channel_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "agent_deliveries_task_id_tasks_id_fk": {+ "name": "agent_deliveries_task_id_tasks_id_fk",+ "tableFrom": "agent_deliveries",+ "tableTo": "tasks",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_delivery_works": {+ "name": "agent_delivery_works",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "delivery_id": {+ "name": "delivery_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "work_id": {+ "name": "work_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "work_version_id": {+ "name": "work_version_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_delivery_works_delivery_id_work_id_unique": {+ "name": "agent_delivery_works_delivery_id_work_id_unique",+ "columns": [+ {+ "expression": "delivery_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "work_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_delivery_works_work_id_idx": {+ "name": "agent_delivery_works_work_id_idx",+ "columns": [+ {+ "expression": "work_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_delivery_works_workspace_id_idx": {+ "name": "agent_delivery_works_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_delivery_works\".\"workspace_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_delivery_works_delivery_id_agent_deliveries_id_fk": {+ "name": "agent_delivery_works_delivery_id_agent_deliveries_id_fk",+ "tableFrom": "agent_delivery_works",+ "tableTo": "agent_deliveries",+ "columnsFrom": ["delivery_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_delivery_works_work_id_works_id_fk": {+ "name": "agent_delivery_works_work_id_works_id_fk",+ "tableFrom": "agent_delivery_works",+ "tableTo": "works",+ "columnsFrom": ["work_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_delivery_works_workspace_id_workspaces_id_fk": {+ "name": "agent_delivery_works_workspace_id_workspaces_id_fk",+ "tableFrom": "agent_delivery_works",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_delivery_works_work_version_id_work_versions_id_fk": {+ "name": "agent_delivery_works_work_version_id_work_versions_id_fk",+ "tableFrom": "agent_delivery_works",+ "tableTo": "work_versions",+ "columnsFrom": ["work_version_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.agent_documents": {"name": "agent_documents","schema": "",@@ -7836,6 +8426,22 @@"method": "btree","with": {}},+ "agent_operations_running_created_at_idx": {+ "name": "agent_operations_running_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_operations\".\"status\" = 'running'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"agent_operations_user_id_created_at_idx": {"name": "agent_operations_user_id_created_at_idx","columns": [@@ -9905,6 +10511,113 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.agent_share_grants": {+ "name": "agent_share_grants",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "share_id": {+ "name": "share_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source": {+ "name": "source",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_share_grants_share_user_unique": {+ "name": "agent_share_grants_share_user_unique",+ "columns": [+ {+ "expression": "share_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_share_grants_user_id_idx": {+ "name": "agent_share_grants_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_share_grants_share_id_agent_shares_id_fk": {+ "name": "agent_share_grants_share_id_agent_shares_id_fk",+ "tableFrom": "agent_share_grants",+ "tableTo": "agent_shares",+ "columnsFrom": ["share_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_share_grants_user_id_users_id_fk": {+ "name": "agent_share_grants_user_id_users_id_fk",+ "tableFrom": "agent_share_grants",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.agent_shares": {"name": "agent_shares","schema": "",@@ -10047,6 +10760,12 @@"primaryKey": false,"notNull": true},+ "upstream": {+ "name": "upstream",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },"manifest": {"name": "manifest","type": "jsonb",@@ -11016,24 +11735,12 @@"primaryKey": false,"notNull": true},- "source_work_version_id": {- "name": "source_work_version_id",- "type": "uuid",- "primaryKey": false,- "notNull": false- },"source_path": {"name": "source_path","type": "text","primaryKey": false,"notNull": false},- "source_file_id": {- "name": "source_file_id",- "type": "text",- "primaryKey": false,- "notNull": false- },"metadata": {"name": "metadata","type": "jsonb",@@ -11157,22 +11864,6 @@"method": "btree","with": {}},- "artboard_boards_source_work_version_id_idx": {- "name": "artboard_boards_source_work_version_id_idx",- "columns": [- {- "expression": "source_work_version_id",- "isExpression": false,- "asc": true,- "nulls": "last"- }- ],- "isUnique": false,- "where": "\"artboard_boards\".\"source_work_version_id\" IS NOT NULL",- "concurrently": false,- "method": "btree",- "with": {}- },"artboard_boards_user_id_idx": {"name": "artboard_boards_user_id_idx","columns": [@@ -11268,37 +11959,15 @@"columnsTo": ["id"],"onDelete": "set null","onUpdate": "no action"- },- "artboard_boards_source_work_version_id_work_versions_id_fk": {- "name": "artboard_boards_source_work_version_id_work_versions_id_fk",- "tableFrom": "artboard_boards",- "tableTo": "work_versions",- "columnsFrom": ["source_work_version_id"],- "columnsTo": ["id"],- "onDelete": "set null",- "onUpdate": "no action"- },- "artboard_boards_source_file_id_files_id_fk": {- "name": "artboard_boards_source_file_id_files_id_fk",- "tableFrom": "artboard_boards",- "tableTo": "files",- "columnsFrom": ["source_file_id"],- "columnsTo": ["id"],- "onDelete": "set null",- "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {},"policies": {},"checkConstraints": {- "artboard_boards_single_source_check": {- "name": "artboard_boards_single_source_check",- "value": "num_nonnulls(\"artboard_boards\".\"source_work_version_id\", \"artboard_boards\".\"source_file_id\") <= 1"- },"artboard_boards_decision_no_source_check": {"name": "artboard_boards_decision_no_source_check",- "value": "\"artboard_boards\".\"type\" <> 'decision' OR num_nonnulls(\"artboard_boards\".\"source_work_version_id\", \"artboard_boards\".\"source_file_id\", \"artboard_boards\".\"source_path\") = 0"+ "value": "\"artboard_boards\".\"type\" <> 'decision' OR \"artboard_boards\".\"source_path\" IS NULL"}},"isRLSEnabled": false@@ -13537,6 +14206,228 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.channel_agent_grants": {+ "name": "channel_agent_grants",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "channel_id": {+ "name": "channel_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "member_id": {+ "name": "member_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "grantee_member_id": {+ "name": "grantee_member_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "requested_by_member_id": {+ "name": "requested_by_member_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "decided_at": {+ "name": "decided_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "revoke_reason": {+ "name": "revoke_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "channel_agent_grants_live_scope_unique": {+ "name": "channel_agent_grants_live_scope_unique",+ "columns": [+ {+ "expression": "member_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "coalesce(\"grantee_member_id\"::text, '')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "coalesce(\"thread_id\", '')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"channel_agent_grants\".\"status\" IN ('pending', 'approved')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "channel_agent_grants_owner_status_idx": {+ "name": "channel_agent_grants_owner_status_idx",+ "columns": [+ {+ "expression": "owner_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "channel_agent_grants_grantee_idx": {+ "name": "channel_agent_grants_grantee_idx",+ "columns": [+ {+ "expression": "grantee_member_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "channel_agent_grants_channel_id_channels_id_fk": {+ "name": "channel_agent_grants_channel_id_channels_id_fk",+ "tableFrom": "channel_agent_grants",+ "tableTo": "channels",+ "columnsFrom": ["channel_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "channel_agent_grants_owner_id_users_id_fk": {+ "name": "channel_agent_grants_owner_id_users_id_fk",+ "tableFrom": "channel_agent_grants",+ "tableTo": "users",+ "columnsFrom": ["owner_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "channel_agent_grants_member_fk": {+ "name": "channel_agent_grants_member_fk",+ "tableFrom": "channel_agent_grants",+ "tableTo": "channel_members",+ "columnsFrom": ["channel_id", "member_id"],+ "columnsTo": ["channel_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "channel_agent_grants_grantee_fk": {+ "name": "channel_agent_grants_grantee_fk",+ "tableFrom": "channel_agent_grants",+ "tableTo": "channel_members",+ "columnsFrom": ["channel_id", "grantee_member_id"],+ "columnsTo": ["channel_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "channel_agent_grants_requester_fk": {+ "name": "channel_agent_grants_requester_fk",+ "tableFrom": "channel_agent_grants",+ "tableTo": "channel_members",+ "columnsFrom": ["channel_id", "requested_by_member_id"],+ "columnsTo": ["channel_id", "id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "channel_agent_grants_thread_fk": {+ "name": "channel_agent_grants_thread_fk",+ "tableFrom": "channel_agent_grants",+ "tableTo": "channel_threads",+ "columnsFrom": ["channel_id", "thread_id"],+ "columnsTo": ["channel_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.channel_audit": {"name": "channel_audit","schema": "",@@ -13799,6 +14690,12 @@"primaryKey": false,"notNull": false},+ "ask": {+ "name": "ask",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },"publication_revoked": {"name": "publication_revoked","type": "boolean",@@ -14289,6 +15186,26 @@"primaryKey": false,"notNull": false},+ "section_id": {+ "name": "section_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "pinned": {+ "name": "pinned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "hidden": {+ "name": "hidden",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },"pinned_at": {"name": "pinned_at","type": "timestamp with time zone",@@ -14366,23 +15283,39 @@"nulls": "last"}],- "isUnique": true,- "where": "\"channel_members\".\"user_id\" IS NOT NULL",+ "isUnique": true,+ "where": "\"channel_members\".\"user_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "channel_members_user_id_idx": {+ "name": "channel_members_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,"concurrently": false,"method": "btree","with": {}},- "channel_members_user_id_idx": {- "name": "channel_members_user_id_idx",+ "channel_members_section_id_idx": {+ "name": "channel_members_section_id_idx","columns": [{- "expression": "user_id",+ "expression": "section_id","isExpression": false,"asc": true,"nulls": "last"}],"isUnique": false,+ "where": "\"channel_members\".\"section_id\" IS NOT NULL","concurrently": false,"method": "btree","with": {}@@ -14422,6 +15355,15 @@"onDelete": "set null","onUpdate": "no action"},+ "channel_members_section_id_channel_sections_id_fk": {+ "name": "channel_members_section_id_channel_sections_id_fk",+ "tableFrom": "channel_members",+ "tableTo": "channel_sections",+ "columnsFrom": ["section_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ },"channel_members_agent_id_agents_id_fk": {"name": "channel_members_agent_id_agents_id_fk","tableFrom": "channel_members",@@ -14466,6 +15408,10 @@"name": "channel_members_agent_id_owner_check","value": "\"channel_members\".\"agent_id\" IS NULL OR \"channel_members\".\"actor_type\" = 'agent'"},+ "channel_members_section_id_owner_check": {+ "name": "channel_members_section_id_owner_check",+ "value": "\"channel_members\".\"section_id\" IS NULL OR \"channel_members\".\"actor_type\" = 'user'"+ },"channel_members_config_owner_check": {"name": "channel_members_config_owner_check","value": "\"channel_members\".\"config\" IS NULL OR \"channel_members\".\"actor_type\" <> 'user'"@@ -14581,6 +15527,13 @@"primaryKey": false,"notNull": true},+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'text'"+ },"content": {"name": "content","type": "text",@@ -14845,6 +15798,112 @@},"isRLSEnabled": false},+ "public.channel_sections": {+ "name": "channel_sections",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "sort": {+ "name": "sort",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "collapsed": {+ "name": "collapsed",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "channel_sections_user_id_workspace_id_idx": {+ "name": "channel_sections_user_id_workspace_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "channel_sections_user_id_users_id_fk": {+ "name": "channel_sections_user_id_users_id_fk",+ "tableFrom": "channel_sections",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "channel_sections_workspace_id_workspaces_id_fk": {+ "name": "channel_sections_workspace_id_workspaces_id_fk",+ "tableFrom": "channel_sections",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.channel_threads": {"name": "channel_threads","schema": "",@@ -16335,12 +17394,24 @@"primaryKey": false,"notNull": true},+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },"message": {"name": "message","type": "text","primaryKey": false,"notNull": false},+ "source": {+ "name": "source",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },"status": {"name": "status","type": "text",@@ -16394,7 +17465,35 @@}],"isUnique": true,- "where": "\"user_contact_requests\".\"status\" = 'pending'",+ "where": "\"user_contact_requests\".\"status\" = 'pending' AND \"user_contact_requests\".\"workspace_id\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_contact_requests_workspace_pending_unique": {+ "name": "user_contact_requests_workspace_pending_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "requester_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "addressee_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_contact_requests\".\"status\" = 'pending' AND \"user_contact_requests\".\"workspace_id\" IS NOT NULL","concurrently": false,"method": "btree","with": {}@@ -16440,6 +17539,21 @@"concurrently": false,"method": "btree","with": {}+ },+ "user_contact_requests_workspace_id_idx": {+ "name": "user_contact_requests_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {@@ -16460,6 +17574,15 @@"columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"+ },+ "user_contact_requests_workspace_id_workspaces_id_fk": {+ "name": "user_contact_requests_workspace_id_workspaces_id_fk",+ "tableFrom": "user_contact_requests",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -16815,7 +17938,35 @@}],"isUnique": true,- "where": "\"user_contacts\".\"contact_user_id\" IS NOT NULL",+ "where": "\"user_contacts\".\"contact_user_id\" IS NOT NULL AND \"user_contacts\".\"workspace_id\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_contacts_workspace_user_unique": {+ "name": "user_contacts_workspace_user_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "contact_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_contacts\".\"contact_user_id\" IS NOT NULL AND \"user_contacts\".\"workspace_id\" IS NOT NULL","concurrently": false,"method": "btree","with": {}@@ -16893,6 +18044,21 @@"concurrently": false,"method": "btree","with": {}+ },+ "user_contacts_workspace_id_idx": {+ "name": "user_contacts_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {@@ -18564,6 +19730,12 @@"primaryKey": false,"notNull": false},+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },"name": {"name": "name","type": "varchar(255)",@@ -18649,6 +19821,22 @@"method": "btree","with": {}},+ "environments_project_id_unique": {+ "name": "environments_project_id_unique",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"environments\".\"project_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"environments_workspace_visibility_idx": {"name": "environments_workspace_visibility_idx","columns": [@@ -18693,7 +19881,7 @@}],"isUnique": true,- "where": "\"environments\".\"workspace_id\" is null",+ "where": "\"environments\".\"workspace_id\" IS NULL AND \"environments\".\"project_id\" IS NULL","concurrently": false,"method": "btree","with": {}@@ -18721,7 +19909,7 @@}],"isUnique": true,- "where": "\"environments\".\"workspace_id\" is not null",+ "where": "\"environments\".\"workspace_id\" IS NOT NULL AND \"environments\".\"project_id\" IS NULL","concurrently": false,"method": "btree","with": {}@@ -18745,6 +19933,15 @@"columnsTo": ["id"],"onDelete": "restrict","onUpdate": "no action"+ },+ "environments_project_id_projects_id_fk": {+ "name": "environments_project_id_projects_id_fk",+ "tableFrom": "environments",+ "tableTo": "projects",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "restrict",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -28961,6 +30158,27 @@"method": "btree","with": {}},+ "messages_user_id_topic_id_idx": {+ "name": "messages_user_id_topic_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "topic_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"messages_session_id_idx": {"name": "messages_session_id_idx","columns": [diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.jsonindex f109d968bdf..39d37b1263a 100644--- a/packages/database/migrations/meta/_journal.json+++ b/packages/database/migrations/meta/_journal.json@@ -1596,6 +1596,13 @@"when": 1795445232107,"tag": "0227_channel_agent_grants","breakpoints": true+ },+ {+ "idx": 228,+ "version": "7",+ "when": 1795457259109,+ "tag": "0228_channel_message_kind",+ "breakpoints": true}],"version": "6"diff --git a/packages/database/src/repositories/channel/__tests__/ask.test.ts b/packages/database/src/repositories/channel/__tests__/ask.test.tsnew file mode 100644index 00000000000..cbea43e080e--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/ask.test.ts@@ -0,0 +1,154 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agentOperations, channelJobs, workspaceMembers } from '../../../schemas';+import { ChannelExecutionRepository, ChannelHistoryRepository } from '..';+import { answerAsk } from '../ask';+import { createChannelFixture, jobsOf, lease } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-ask');+const execution = new ChannelExecutionRepository(db);+beforeEach(async () => {+ await fixture.setup();+ await db+ .insert(workspaceMembers)+ .values({ workspaceId: fixture.workspaceId, userId: fixture.memberId });+});+afterEach(fixture.cleanup);++const questions = [+ {+ options: [{ label: 'Diet' }, { description: 'Workouts and steps', label: 'Exercise' }],+ question: 'What should I watch first?',+ },+];++/** The member asks the Agent, whose run is now running. */+const running = async () => {+ const team = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(team.channel.id, 'Helper');+ const request = await team.asMember.send(team.channel.id, {+ content: 'Help me stay healthy',+ mentions: [agent.id],+ requestKey: 'ask-request',+ routing: 'decision',+ });+ const [job] = await jobsOf(db, request.id);+ const claim = (await execution.claim(team.channel.id, job.id, lease))!;+ const operationId = claim.job.operationId!;+ await db+ .update(agentOperations)+ .set({ status: 'running' })+ .where(eq(agentOperations.id, operationId));+ const history = new ChannelHistoryRepository(db, fixture.memberId, fixture.workspaceId);+ return { ...team, agent, history, job, operationId };+};++/** The run asks back and publishes `draft` with its questions. */+const askedReply = async (draft = 'Hi, I am your health helper.') => {+ const state = await running();+ await state.history.ask(state.operationId, { questions });+ await execution.accepted(state.channel.id, state.job.id);+ await execution.saveDraft(state.channel.id, state.job.id, draft);+ const replyId = await execution.publish(state.channel.id, state.job.id);+ return { ...state, replyId };+};++const answer = (state: Awaited<ReturnType<typeof askedReply>>, selected: string[], as = 'member') =>+ (as === 'member' ? state.asMember : state.asOwner).write(state.channel.id, (tx, access) =>+ answerAsk(tx, access, {+ answers: [{ selected }],+ messageId: state.replyId,+ requestKey: `answer:${state.replyId}`,+ }),+ );++describe('Channel ask messages', () => {+ it('publishes the questions with the reply as an ask, with a text fallback', async () => {+ const state = await askedReply();+ const reply = (await state.asMember.detail(state.channel.id)).messages.find(+ (message) => message.id === state.replyId,+ )!;++ expect(reply.kind).toBe('ask');+ expect(reply.content).toBe(+ 'Hi, I am your health helper.\n\nWhat should I watch first?\nA. Diet\nB. Exercise — Workouts and steps',+ );+ expect(reply.ask).toMatchObject({+ bodyLength: 'Hi, I am your health helper.'.length,+ questions,+ requesterMemberId: state.member.id,+ status: 'pending',+ });+ });++ it('keeps one ask per run: the same questions again are a no-op, others are refused', async () => {+ const state = await running();+ await state.history.ask(state.operationId, { questions });+ await state.history.ask(state.operationId, { questions });+ await expect(+ state.history.ask(state.operationId, {+ questions: [{ ...questions[0], question: 'Other?' }],+ }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ const [job] = await db.select().from(channelJobs).where(eq(channelJobs.id, state.job.id));+ expect(job.ask).toEqual({ questions });+ });++ it('posts only the questions when the run wrote nothing around them', async () => {+ const state = await askedReply('');+ const reply = (await state.asMember.detail(state.channel.id)).messages.find(+ (message) => message.id === state.replyId,+ )!;+ expect(reply.content.startsWith('What should I watch first?')).toBe(true);+ expect(reply.ask?.bodyLength).toBe(0);+ });++ it('posts the requester’s answer as their reply to the question and marks it answered', async () => {+ const state = await askedReply();+ const posted = await answer(state, ['Exercise']);++ expect(posted).toMatchObject({ content: 'B. Exercise', replyToId: state.replyId });+ // Quoting the Agent's question asks that Agent again.+ const [job] = await jobsOf(db, posted.id);+ expect(job.memberId).toBe(state.agent.id);++ const reply = (await state.asMember.detail(state.channel.id)).messages.find(+ (message) => message.id === state.replyId,+ )!;+ expect(reply.ask).toMatchObject({+ answer: {+ answers: [{ selected: ['Exercise'] }],+ memberId: state.member.id,+ messageId: posted.id,+ },+ status: 'answered',+ });++ // A retry returns the answer it already posted; a second, different answer is refused.+ expect((await answer(state, ['Exercise'])).id).toBe(posted.id);+ await expect(+ state.asMember.write(state.channel.id, (tx, access) =>+ answerAsk(tx, access, {+ answers: [{ selected: ['Diet'] }],+ messageId: state.replyId,+ requestKey: 'another',+ }),+ ),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ });++ it('lets only the requester answer, and only with the listed options', async () => {+ const state = await askedReply();+ await expect(answer(state, ['Exercise'], 'owner')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(answer(state, ['Sleep'])).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(answer(state, ['Diet', 'Exercise'])).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });+});diff --git a/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts b/packages/database/src/repositories/channel/__tests__/cardMessage.test.tsindex 49b73b12a2d..e4af3eca4c1 100644--- a/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts+++ b/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts@@ -33,6 +33,7 @@ describe('a contact card message', () => {});expect(sent.content).toBe('[Contact card] mia');+ expect(sent.kind).toBe('contact');const [seen] = (await asOwner.detail(channel.id)).messages;expect(seen.card).toEqual({avatar: null,diff --git a/packages/database/src/repositories/channel/__tests__/replyError.test.ts b/packages/database/src/repositories/channel/__tests__/replyError.test.tsindex 3ff760bc596..6367330f2c1 100644--- a/packages/database/src/repositories/channel/__tests__/replyError.test.ts+++ b/packages/database/src/repositories/channel/__tests__/replyError.test.ts@@ -80,6 +80,7 @@ describe('A failed reply leaves a card in its reply slot', () => {agentId: agent.agentId,content: draft.summary,id: posted!.messageId,+ kind: 'error',mentions: [],replyToId: message.id,routingStatus: 'reply',@@ -182,7 +183,11 @@ describe('A failed reply leaves a card in its reply slot', () => {expect(replyId).toBe(posted!.messageId);const replies = (await messagesOf(channel.id)).filter((row) => row.routingStatus === 'reply');expect(replies).toHaveLength(1);- expect(replies[0]).toMatchObject({ content: 'The migration timed out.', id: replyId });+ expect(replies[0]).toMatchObject({+ content: 'The migration timed out.',+ id: replyId,+ kind: 'text',+ });expect(channelMessageReplyError(replies[0].metadata)).toBeUndefined();expect((await asMember.detail(channel.id)).messages.at(-1)?.replyError).toBeNull();});diff --git a/packages/database/src/repositories/channel/ask.ts b/packages/database/src/repositories/channel/ask.tsnew file mode 100644index 00000000000..c534d260763--- /dev/null+++ b/packages/database/src/repositories/channel/ask.ts@@ -0,0 +1,106 @@+import type { ChannelAskAnswerItem, ChannelMessage } from '@lobechat/types';+import {+ channelAskAnswerText,+ channelMessageAsk,+ channelMessageDeletedAt,+ validateChannelAskAnswers,+} from '@lobechat/types';+import { and, eq } from 'drizzle-orm';++import { channelMessages } from '../../schemas';+import type { Transaction } from '../../type';+import type { ChannelContacts } from './contacts';+import { noChannelContacts } from './contacts';+import { ChannelError } from './error';+import { sendMessage } from './send';+import { audit } from './transaction';+import type { ChannelAccess } from './types';++export interface ChannelAskAnswerInput {+ answers: ChannelAskAnswerItem[];+ messageId: string;+ /** Client retry key of the answer message. */+ requestKey: string;+}++/**+ * Answers an Agent's `ask` message. Only the requester it asked may answer, once: the answer is+ * posted as their reply to the question, which wakes the Agent that asked like any reply to an+ * Agent does, and the question is marked answered in the same transaction. A retry of the same+ * answer returns the message it already posted.+ */+export const answerAsk = async (+ tx: Transaction,+ access: ChannelAccess,+ input: ChannelAskAnswerInput,+ contacts: ChannelContacts = noChannelContacts,+): Promise<ChannelMessage> => {+ const { channel, member } = access;+ const [message] = await tx+ .select()+ .from(channelMessages)+ .where(and(eq(channelMessages.channelId, channel.id), eq(channelMessages.id, input.messageId)))+ .for('update');+ const ask = message?.kind === 'ask' ? channelMessageAsk(message.metadata) : undefined;+ if (!message || !ask || channelMessageDeletedAt(message.metadata))+ throw new ChannelError('NOT_FOUND', 'Question not found');+ if (ask.requesterMemberId !== member.id)+ throw new ChannelError('FORBIDDEN', 'Only the person it asked can answer this question');++ if (ask.status === 'answered') {+ const [posted] = ask.answer?.messageId+ ? await tx+ .select()+ .from(channelMessages)+ .where(+ and(+ eq(channelMessages.channelId, channel.id),+ eq(channelMessages.id, ask.answer.messageId),+ ),+ )+ : [];+ if (posted?.requestKey === input.requestKey) return posted;+ throw new ChannelError('CONFLICT', 'This question was already answered');+ }++ const answers = input.answers.map(({ other, selected }) => ({+ selected,+ ...(other?.trim() && { other: other.trim() }),+ }));+ const invalid = validateChannelAskAnswers(ask, answers);+ if (invalid) throw new ChannelError('BAD_REQUEST', invalid);++ // Quoting the Agent's question without mentions asks that Agent, in the question's branch.+ const reply = await sendMessage(+ tx,+ access,+ {+ content: channelAskAnswerText(ask, answers),+ replyToId: message.id,+ requestKey: input.requestKey,+ routing: 'fallback',+ threadId: message.threadId,+ },+ contacts,+ );+ await tx+ .update(channelMessages)+ .set({+ metadata: {+ ...message.metadata,+ ask: {+ ...ask,+ answer: {+ answeredAt: new Date().toISOString(),+ answers,+ memberId: member.id,+ messageId: reply.id,+ },+ status: 'answered',+ },+ },+ })+ .where(eq(channelMessages.id, message.id));+ await audit(tx, channel.id, 'ask_answered', message.id, { messageId: reply.id });+ return reply;+};diff --git a/packages/database/src/repositories/channel/execution.ts b/packages/database/src/repositories/channel/execution.tsindex f3287270e43..13221321263 100644--- a/packages/database/src/repositories/channel/execution.ts+++ b/packages/database/src/repositories/channel/execution.ts@@ -1,10 +1,11 @@import type {AgentOperationStatus,+ ChannelAsk,ChannelContextMessage,ChannelJobStatus,ChannelReplyError,} from '@lobechat/types';-import { channelMessageReplyError } from '@lobechat/types';+import { channelAskFallbackText, channelMessageReplyError } from '@lobechat/types';import { and, asc, desc, eq, gt, isNotNull, isNull, ne, or, sql } from 'drizzle-orm';import type { ChannelJobItem } from '../../schemas';@@ -541,13 +542,27 @@ export class ChannelExecutionRepository {.for('share');if (!sender) throw new ChannelError('CONFLICT', 'The replying Agent was deleted');+ // Questions the run asked go out with its reply, as a card only its requester answers.+ const body = job.draft.trim();+ const ask: ChannelAsk | undefined = job.ask+ ? {+ ...job.ask,+ bodyLength: body.length,+ requesterMemberId: job.requesterMemberId,+ status: 'pending',+ }+ : undefined;+ const published = {+ content: ask ? [body, channelAskFallbackText(ask)].filter(Boolean).join('\n\n') : job.draft,+ ...(ask && { kind: 'ask' as const, metadata: { ask } }),+ };// A card from an earlier failure of this job is replaced by the reply, in the same slot.const reply =- (await replaceReplyError(tx, job, job.draft)) ??+ (await replaceReplyError(tx, job, published)) ??(await appendMessage(tx, {+ ...published,agentId: sender.id,channelId,- content: job.draft,replyToId: job.messageId,requestKey: replyRequestKey(job.id),routingStatus: 'reply',diff --git a/packages/database/src/repositories/channel/history.ts b/packages/database/src/repositories/channel/history.tsindex c43722079d3..5b079872042 100644--- a/packages/database/src/repositories/channel/history.ts+++ b/packages/database/src/repositories/channel/history.ts@@ -1,5 +1,6 @@import type {ChannelAgentExchange,+ ChannelAskInput,ChannelConnectorRequest,ChannelContextMessage,ChannelExecutionConfig,@@ -25,6 +26,7 @@ import {} from '@lobechat/types';import type { SQL } from 'drizzle-orm';import { and, count, desc, eq, gte, inArray, isNull, sql } from 'drizzle-orm';+import { isEqual } from 'es-toolkit';import {agentOperations,@@ -279,6 +281,41 @@ export class ChannelHistoryRepository {return { channelId, ...(exchange && { exchange }), manifest };});+ /**+ * Holds the questions a run asks its requester (`lobe-channel.askUser`) on its job; publishing+ * the reply posts them with it as an `ask` message. One ask per run: a retried call with the+ * same questions is a no-op, different ones are refused. Only a person's own request can be+ * asked back: an Agent's request has nobody to answer the card.+ */+ ask = async (operationId: string, input: ChannelAskInput): Promise<void> =>+ this.read(operationId, async (tx, channelId, manifest) => {+ const [request] = await tx+ .select({ agentId: channelMessages.agentId, metadata: channelMessages.metadata })+ .from(channelMessages)+ .where(+ and(+ eq(channelMessages.channelId, channelId),+ eq(channelMessages.id, manifest.requestMessageId),+ ),+ )+ .limit(1);+ if (!request || request.agentId || channelMessageVia(request.metadata))+ throw new ChannelError(+ 'FORBIDDEN',+ 'Only a request a person wrote can be asked back; answer this one instead',+ );+ const [job] = await tx+ .select({ ask: channelJobs.ask, id: channelJobs.id })+ .from(channelJobs)+ .where(and(eq(channelJobs.operationId, operationId), eq(channelJobs.channelId, channelId)))+ .limit(1);+ if (job.ask) {+ if (isEqual(job.ask, input)) return;+ throw new ChannelError('CONFLICT', 'This reply already asks its questions');+ }+ await tx.update(channelJobs).set({ ask: input }).where(eq(channelJobs.id, job.id));+ });+/*** Who a run relays as, and from where. A Channel run relays from its Channel and request* (`currentRun`, all its checks). A run with no Channel job may only be the requester's owndiff --git a/packages/database/src/repositories/channel/post.ts b/packages/database/src/repositories/channel/post.tsindex 5bdc235c108..5beedf87494 100644--- a/packages/database/src/repositories/channel/post.ts+++ b/packages/database/src/repositories/channel/post.ts@@ -1,4 +1,4 @@-import type { ChannelMessageMetadata } from '@lobechat/types';+import type { ChannelMessageKind, ChannelMessageMetadata } from '@lobechat/types';import { and, eq } from 'drizzle-orm';import type { ChannelMessageItem } from '../../schemas';@@ -12,6 +12,8 @@ export interface ChannelAgentPostInput {/** The Agent that wrote it; must be an active member of the Channel. */agentId: string;content: string;+ /** What the message is; its payload goes in `metadata.<kind>`. Default `text`. */+ kind?: ChannelMessageKind;metadata?: ChannelMessageMetadata;/** Identity of what produced the post (e.g. the run). Posting it again returns the stored one. */requestKey: string;@@ -64,6 +66,7 @@ export const postAgentMessage = async (agentId: input.agentId,channelId,content: input.content,+ ...(input.kind && { kind: input.kind }),metadata: input.metadata ?? {},requestKey: input.requestKey,routingStatus: 'reply',diff --git a/packages/database/src/repositories/channel/replyError.ts b/packages/database/src/repositories/channel/replyError.tsindex 872c6cc5a59..dc496c8e896 100644--- a/packages/database/src/repositories/channel/replyError.ts+++ b/packages/database/src/repositories/channel/replyError.ts@@ -232,6 +232,7 @@ export const upsertReplyError = async (.update(channelMessages).set({content: card.summary,+ kind: 'error',mentions: [],metadata: { ...baseMetadata(slot.metadata), replyError: card },...(await moveToEnd(tx, slot)),@@ -244,6 +245,7 @@ export const upsertReplyError = async (agentId: job.manifest.self.agentId,channelId: channel.id,content: card.summary,+ kind: 'error',metadata: { replyError: card },replyToId: job.messageId,requestKey: replyRequestKey(job.id),@@ -305,7 +307,8 @@ export const refineReplyError = async (export const replaceReplyError = async (tx: Transaction,job: SlotJob,- content: string,+ published: Pick<ChannelMessageItem, 'content'> &+ Partial<Pick<ChannelMessageItem, 'kind' | 'metadata'>>,): Promise<ChannelMessageItem | undefined> => {const slot = await findReplySlot(tx, job, false);if (!slot) return;@@ -313,9 +316,10 @@ export const replaceReplyError = async (const [reply] = await tx.update(channelMessages).set({- content,+ content: published.content,+ kind: published.kind ?? 'text',mentions: [],- metadata: baseMetadata(slot.metadata),+ metadata: { ...baseMetadata(slot.metadata), ...published.metadata },// Cleared as an acknowledgement: `lastNewsAt` counts the published reply, not the opening....(slot.requestKey === openingRequestKey(job.id) && {requestKey: replyRequestKey(job.id),diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.tsindex 907b307e3fb..97baa80d5e2 100644--- a/packages/database/src/repositories/channel/send.ts+++ b/packages/database/src/repositories/channel/send.ts@@ -333,6 +333,7 @@ export const sendMessage = async (...(author ? { agentId: author.agentId } : { userId: member.userId }),channelId: channel.id,content: card ? contactCardText(card) : input.content,+ ...(card && { kind: 'contact' as const }),mentions,...(metadata && { metadata }),requestKey: input.requestKey,diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex a51e31cb30f..6dabbb11f95 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -1,6 +1,7 @@import {type AgentDeviceOverride,type ChannelDeviceGrantCard,+ channelMessageAsk,channelMessageConnector,channelMessageDeletedAt,channelMessageDeviceGrant,@@ -141,6 +142,11 @@ export const publicMessage = (name: isAgent ? senderAgentName || senderAgentTitle : senderUserName || senderUsername,type: isAgent ? ('agent' as const) : ('user' as const),},+ // A deleted question keeps its row as a tombstone, but nothing is left to answer.+ ask:+ message.kind === 'ask' && !channelMessageDeletedAt(message.metadata)+ ? (channelMessageAsk(message.metadata) ?? null)+ : null,card: contactCardOf(message.metadata) ?? null,// An Agent asking the reader to connect a connector it needs.connector: (isAgent && channelMessageConnector(message.metadata)) || null,diff --git a/packages/database/src/schemas/channel.rowTypes.check.ts b/packages/database/src/schemas/channel.rowTypes.check.tsnew file mode 100644index 00000000000..03791a08245--- /dev/null+++ b/packages/database/src/schemas/channel.rowTypes.check.ts@@ -0,0 +1,16 @@+import type { ChannelMessage } from '@lobechat/types';++import type { channelMessages } from './channel';++type Equal<A, B> =+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;+type Assert<T extends true> = T;++/**+ * `ChannelMessage` is the declared contract readers outside this package use; the Drizzle table+ * must stay exactly that shape. A column added, removed or retyped here fails the type check+ * instead of silently widening the contract.+ */+export type ChannelMessageRowTypeMatchesSchema = Assert<+ Equal<ChannelMessage, typeof channelMessages.$inferSelect>+>;diff --git a/packages/database/src/schemas/channel.ts b/packages/database/src/schemas/channel.tsindex 0da93c9b3b3..725e5dcd897 100644--- a/packages/database/src/schemas/channel.ts+++ b/packages/database/src/schemas/channel.ts@@ -2,6 +2,7 @@ import type {ChannelAgentGrantMetadata,ChannelAgentGrantRevokeReason,ChannelAgentGrantStatus,+ ChannelAskInput,ChannelAuditDetails,ChannelConfig,ChannelExecutionConfig,@@ -17,6 +18,7 @@ import type {ChannelMemberMetadata,ChannelMemberRole,ChannelMemberStatus,+ ChannelMessageKind,ChannelMessageMetadata,ChannelMessageRoutingSource,ChannelMessageRoutingStatus,@@ -436,6 +438,8 @@ export const channelMessages = pgTable(.notNull(),threadId: text('thread_id'),sequence: integer('sequence').notNull(),+ /** What the message is (`ChannelMessageKind`); its payload is `metadata.<kind>`. */+ kind: text('kind').$type<ChannelMessageKind>().notNull().default('text'),content: text('content').notNull(),/** Actual human sender, not the owner/requester of an Agent reply. */userId: text('user_id').references(() => users.id, { onDelete: 'set null' }),@@ -582,6 +586,8 @@ export const channelJobs = pgTable(isolatedAt: timestamptz('isolated_at'),/** Final answer saved by the run; immutable once set. */draft: text('draft'),+ /** Questions the run asked (`lobe-channel.askUser`), posted with its reply as an `ask`. */+ ask: jsonb('ask').$type<ChannelAskInput>(),/** A revoked job never publishes. Set by stops, failures and isolation. */publicationRevoked: boolean('publication_revoked').notNull().default(false),publishedMessageId: uuid('published_message_id'),diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 7877c8ffc74..b79a46fbd18 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -126,6 +126,13 @@ export default {'copyThreadIdSuccess': 'Thread ID copied','copyThreadLink': 'Copy link','copyThreadLinkSuccess': 'Thread link copied',+ 'ask.answeredBy': 'Answered by {{name}}',+ 'ask.failed': "Couldn't send your answer. Try again.",+ 'ask.multiSelect': 'Choose all that apply',+ 'ask.other': 'Other',+ 'ask.otherPlaceholder': 'Type your answer',+ 'ask.submit': 'Send answer',+ 'ask.waitingFor': 'Waiting for {{name}} to answer','actionFailed': 'Something went wrong. Try again.','send': 'Send','sendFailed': 'Message was not sent. Your draft is preserved; try again.',diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex b2da37913a2..3030ac0167d 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -18,6 +18,7 @@ export default {'builtins.lobe-channel.moreHistory': 'Earlier messages are available','builtins.lobe-channel.empty': 'No messages are visible in this conversation.','builtins.lobe-channel.apiName.readMessage': 'Read Channel message',+ 'builtins.lobe-channel.apiName.askUser': 'Ask with options','builtins.lobe-channel.apiName.createThread': 'Open Thread','builtins.lobe-channel.apiName.listThreads': 'List Threads','builtins.lobe-channel.apiName.steerThread': 'Steer Thread',diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 03ac8b42232..8570b1421f2 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -3,6 +3,7 @@ import {LocalExecutionHeterogeneousAgentTypeSchema,REMOTE_HETEROGENEOUS_AGENT_CONFIGS,} from './agent/heterogeneousAgent';+import type { ChannelAsk, ChannelMessageKind } from './channelAsk';import type { ChannelConnectorRequest, ChannelDeviceGrantCard } from './channelMessageCard';import type { ContactCard, ContactCardType, ContactUserProfile } from './contact';import { getWorkingDirEffectivePath } from './device';@@ -974,6 +975,8 @@ export interface ChannelPublicMember {export interface ChannelPublicMessage {agentId: string | null;+ /** An Agent's question with options, on an `ask` message; null otherwise. */+ ask?: ChannelAsk | null;author: {avatar: string | null;id: string | null;@@ -997,6 +1000,8 @@ export interface ChannelPublicMessage {editedAt?: Date | null;fileIds: string[];id: string;+ /** What the message is; its payload, if any, is in the field named after it. */+ kind?: ChannelMessageKind;mentions: string[];/** Another Channel's reply this request brings back to the relaying Agent; null otherwise. */receipt?: ChannelMessageReceipt | null;diff --git a/packages/types/src/channelAsk.test.ts b/packages/types/src/channelAsk.test.tsnew file mode 100644index 00000000000..ff2fac8016d--- /dev/null+++ b/packages/types/src/channelAsk.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest';++import {+ channelAskAnswerText,+ channelAskFallbackText,+ channelMessageAsk,+ normalizeChannelAskInput,+ validateChannelAskAnswers,+} from './channelAsk';++const ask = {+ questions: [+ { options: [{ label: 'Diet' }, { label: 'Exercise' }], question: 'Start with?' },+ {+ multiSelect: true,+ options: [{ label: 'Mornings' }, { label: 'Evenings' }],+ question: 'When?',+ },+ ],+};++describe('channel ask', () => {+ it('normalizes what an Agent asks and refuses what a card cannot show', () => {+ expect(+ normalizeChannelAskInput({+ questions: [{ options: [{ label: ' A ' }, { label: 'B' }], question: ' Pick ' }],+ }),+ ).toEqual({ questions: [{ options: [{ label: 'A' }, { label: 'B' }], question: 'Pick' }] });+ expect(() =>+ normalizeChannelAskInput({ questions: [{ options: [{ label: 'A' }], question: 'Q' }] }),+ ).toThrow('between 2 and 6 options');+ expect(() =>+ normalizeChannelAskInput({+ questions: [{ options: [{ label: 'A' }, { label: 'A' }], question: 'Q' }],+ }),+ ).toThrow('duplicate options');+ expect(() => normalizeChannelAskInput({ questions: [] })).toThrow('between 1 and 4');+ });++ it('writes the questions and an answer as plain text', () => {+ expect(channelAskFallbackText(ask)).toBe(+ 'Start with?\nA. Diet\nB. Exercise\n\nWhen? (multiple choice)\nA. Mornings\nB. Evenings',+ );+ expect(+ channelAskAnswerText(ask, [+ { selected: ['Exercise'] },+ { other: 'Weekends', selected: ['Mornings'] },+ ]),+ ).toBe('Start with?\nB. Exercise\n\nWhen?\nA. Mornings; Weekends');+ });++ it('checks an answer against its questions', () => {+ const valid = [{ selected: ['Diet'] }, { selected: ['Mornings', 'Evenings'] }];+ expect(validateChannelAskAnswers(ask, valid)).toBeUndefined();+ expect(validateChannelAskAnswers(ask, [valid[0]])).toBe('Answer every question');+ expect(validateChannelAskAnswers(ask, [{ selected: ['Diet', 'Exercise'] }, valid[1]])).toMatch(+ 'takes one answer',+ );+ expect(validateChannelAskAnswers(ask, [{ other: 'Sleep', selected: [] }, valid[1]])).toBe(+ undefined,+ );+ expect(validateChannelAskAnswers(ask, [{ selected: [] }, valid[1]])).toMatch('no answer');+ expect(validateChannelAskAnswers(ask, [{ selected: ['Sleep'] }, valid[1]])).toMatch(+ 'pick from its options',+ );+ });++ it('reads metadata.ask defensively', () => {+ expect(channelMessageAsk({})).toBeUndefined();+ expect(+ channelMessageAsk({ ask: { ...ask, bodyLength: 3, requesterMemberId: 'm', status: 'x' } }),+ ).toMatchObject({ bodyLength: 3, status: 'pending' });+ });+});diff --git a/packages/types/src/channelAsk.ts b/packages/types/src/channelAsk.tsnew file mode 100644index 00000000000..f4f302e48e3--- /dev/null+++ b/packages/types/src/channelAsk.ts@@ -0,0 +1,256 @@+/**+ * Message kinds of a Channel timeline (`channel_messages.kind`), and the `ask` kind: a question+ * an Agent puts to its requester, answered from a card instead of by typing.+ *+ * A kind's payload lives in `metadata` under the kind's own key (`metadata.ask` for `ask`); the+ * contact card keeps its earlier `metadata.card`, and the error card `metadata.replyError`. `content` always holds a plain-text fallback, so+ * a client that does not know a kind, the model's history and search all still read it as text.+ */+export const CHANNEL_MESSAGE_KINDS = ['text', 'contact', 'ask', 'error', 'deviceGrant'] as const;++/**+ * - `text`: an ordinary message.+ * - `contact`: a person or an Agent shared as a contact card (`metadata.card`).+ * - `ask`: an Agent's question with options (`metadata.ask`).+ * - `error`: a reply that failed, shown as a card in its slot (`metadata.replyError`); the reply+ * that later succeeds replaces it and its kind.+ * - `deviceGrant`: an Agent's request to use a device (`metadata.deviceGrant`).+ */+export type ChannelMessageKind = (typeof CHANNEL_MESSAGE_KINDS)[number];++export const CHANNEL_ASK_LIMITS = {+ descriptionLength: 200,+ headerLength: 40,+ labelLength: 80,+ maxOptions: 6,+ maxQuestions: 4,+ minOptions: 2,+ otherLength: 500,+ questionLength: 300,+} as const;++export interface ChannelAskOption {+ description?: string;+ label: string;+}++export interface ChannelAskQuestion {+ /** Short label shown above the question, e.g. "Focus". */+ header?: string;+ /** Several options may be picked. */+ multiSelect?: boolean;+ options: ChannelAskOption[];+ question: string;+}++/** What an Agent asks with `lobe-channel.askUser`, held on its job until the reply publishes. */+export interface ChannelAskInput {+ questions: ChannelAskQuestion[];+}++/** One question's answer: the labels picked, and/or the person's own words for "Other". */+export interface ChannelAskAnswerItem {+ other?: string;+ selected: string[];+}++/** `lobe-channel.askUser`: questions posted with the reply, answered from a card. */+export type ChannelAskUserParams = ChannelAskInput;++export interface ChannelAskedUser {+ questions: number;+ status: 'posts_with_reply';+}++export type ChannelAskStatus = 'answered' | 'pending';++/** `metadata.ask` of an `ask` message. */+export interface ChannelAsk extends ChannelAskInput {+ answer?: {+ /** One entry per question, in order. */+ answers: ChannelAskAnswerItem[];+ answeredAt: string;+ memberId: string;+ /** The person's message carrying the answer, a reply to the question. */+ messageId?: string;+ };+ /**+ * Characters of `content` the Agent wrote; the rest is the plain-text fallback of the+ * questions, which a client rendering the card does not show again.+ */+ bodyLength: number;+ /** The member whose request the Agent was answering: the only one who may answer. */+ requesterMemberId: string;+ status: ChannelAskStatus;+}++const isString = (value: unknown): value is string => typeof value === 'string';++const parseQuestion = (value: unknown): ChannelAskQuestion | undefined => {+ const raw = value as Partial<ChannelAskQuestion> | null;+ if (!raw || !isString(raw.question) || !Array.isArray(raw.options)) return;+ const options = raw.options+ .filter((option): option is ChannelAskOption => isString(option?.label))+ .map(({ description, label }) => ({ label, ...(isString(description) && { description }) }));+ if (!options.length) return;+ return {+ options,+ question: raw.question,+ ...(isString(raw.header) && { header: raw.header }),+ ...(raw.multiSelect === true && { multiSelect: true }),+ };+};++const parseAnswers = (value: unknown): ChannelAskAnswerItem[] | undefined => {+ if (!Array.isArray(value)) return;+ return value.map((item) => ({+ selected: Array.isArray(item?.selected) ? item.selected.filter(isString) : [],+ ...(isString(item?.other) && { other: item.other }),+ }));+};++export const channelMessageAsk = (+ metadata: Record<string, unknown> | null | undefined,+): ChannelAsk | undefined => {+ const raw = metadata?.ask as Partial<ChannelAsk> | undefined;+ if (!raw || !Array.isArray(raw.questions) || !isString(raw.requesterMemberId)) return;+ const questions = raw.questions.map(parseQuestion);+ if (!questions.length || questions.some((question) => !question)) return;+ const answer = raw.answer;+ const answers = parseAnswers(answer?.answers);+ return {+ bodyLength: typeof raw.bodyLength === 'number' && raw.bodyLength >= 0 ? raw.bodyLength : 0,+ questions: questions as ChannelAskQuestion[],+ requesterMemberId: raw.requesterMemberId,+ status: raw.status === 'answered' ? 'answered' : 'pending',+ ...(answer &&+ answers &&+ isString(answer.memberId) &&+ isString(answer.answeredAt) && {+ answer: {+ answeredAt: answer.answeredAt,+ answers,+ memberId: answer.memberId,+ ...(isString(answer.messageId) && { messageId: answer.messageId }),+ },+ }),+ };+};++const optionLetter = (index: number) => String.fromCodePoint(65 + index);++/** The questions as plain text, appended to the Agent's own words in `content`. */+export const channelAskFallbackText = ({ questions }: ChannelAskInput): string =>+ questions+ .map(({ multiSelect, options, question }) =>+ [+ multiSelect ? `${question} (multiple choice)` : question,+ ...options.map(+ (option, index) =>+ `${optionLetter(index)}. ${option.label}${option.description ? ` — ${option.description}` : ''}`,+ ),+ ].join('\n'),+ )+ .join('\n\n');++/**+ * The answer as the person's message: readable to everyone, and to the Agent it wakes. One line+ * per question; several questions are each prefixed with their question.+ */+export const channelAskAnswerText = (+ { questions }: ChannelAskInput,+ answers: ChannelAskAnswerItem[],+): string =>+ questions+ .map((question, index) => {+ const { other, selected } = answers[index] ?? { selected: [] };+ const picked = selected.map((label) => {+ const at = question.options.findIndex((option) => option.label === label);+ return at < 0 ? label : `${optionLetter(at)}. ${label}`;+ });+ const parts = [...picked, ...(other?.trim() ? [other.trim()] : [])];+ const value = parts.join('; ');+ return questions.length > 1 ? `${question.question}\n${value}` : value;+ })+ .join('\n\n');++/**+ * Checks an answer against its questions: picked labels must be options, a single-choice+ * question takes one pick or the person's own words, and every question needs something.+ */+export const validateChannelAskAnswers = (+ { questions }: ChannelAskInput,+ answers: ChannelAskAnswerItem[],+): string | undefined => {+ if (answers.length !== questions.length) return 'Answer every question';+ for (const [index, question] of questions.entries()) {+ const { other, selected } = answers[index];+ const labels = new Set(question.options.map((option) => option.label));+ if (new Set(selected).size !== selected.length || selected.some((label) => !labels.has(label)))+ return `Question ${index + 1}: pick from its options`;+ const words = other?.trim() ?? '';+ if (words.length > CHANNEL_ASK_LIMITS.otherLength)+ return `Question ${index + 1}: at most ${CHANNEL_ASK_LIMITS.otherLength} characters`;+ const count = selected.length + (words ? 1 : 0);+ if (!count) return `Question ${index + 1} has no answer`;+ if (!question.multiSelect && count > 1) return `Question ${index + 1} takes one answer`;+ }+};++const bounded = (value: unknown, what: string, max: number, optional = false) => {+ const text = isString(value) ? value.trim() : '';+ if (!text) {+ if (optional) return;+ throw new Error(`${what} is required`);+ }+ if (text.length > max) throw new Error(`${what} must be at most ${max} characters`);+ return text;+};++/** Trims and checks what an Agent asks; throws with a message the Agent can correct. */+export const normalizeChannelAskInput = (input: unknown): ChannelAskInput => {+ const raw = (input as Partial<ChannelAskInput> | null)?.questions;+ const { maxOptions, maxQuestions, minOptions } = CHANNEL_ASK_LIMITS;+ if (!Array.isArray(raw) || !raw.length || raw.length > maxQuestions)+ throw new Error(`Ask between 1 and ${maxQuestions} questions`);+ return {+ questions: raw.map((question, index) => {+ const what = `Question ${index + 1}`;+ const options = Array.isArray(question?.options) ? question.options : [];+ if (options.length < minOptions || options.length > maxOptions)+ throw new Error(`${what} needs between ${minOptions} and ${maxOptions} options`);+ const normalized = options.map((option: Partial<ChannelAskOption>, at: number) => {+ const description = bounded(+ option?.description,+ `${what} option ${at + 1} description`,+ CHANNEL_ASK_LIMITS.descriptionLength,+ true,+ );+ return {+ label: bounded(+ option?.label,+ `${what} option ${at + 1}`,+ CHANNEL_ASK_LIMITS.labelLength,+ )!,+ ...(description && { description }),+ };+ });+ if (+ new Set(normalized.map((option: ChannelAskOption) => option.label)).size !== options.length+ )+ throw new Error(`${what} has duplicate options`);+ const header = bounded(+ question?.header,+ `${what} header`,+ CHANNEL_ASK_LIMITS.headerLength,+ true,+ );+ return {+ options: normalized,+ question: bounded(question?.question, what, CHANNEL_ASK_LIMITS.questionLength)!,+ ...(header && { header }),+ ...(question?.multiSelect === true && { multiSelect: true }),+ };+ }),+ };+};diff --git a/packages/types/src/channelMessage.ts b/packages/types/src/channelMessage.tsnew file mode 100644index 00000000000..bd06548f88b--- /dev/null+++ b/packages/types/src/channelMessage.ts@@ -0,0 +1,42 @@+import type {+ ChannelMessageMetadata,+ ChannelMessageRoutingSource,+ ChannelMessageRoutingStatus,+} from './channel';+import type { ChannelMessageKind } from './channelAsk';++/**+ * One public message row (`channel_messages`), declared here as a contract instead of being+ * inferred from the Drizzle table: readers outside the database package depend on this shape, so+ * a column change has to update it deliberately. `channel.rowTypes.check.ts` next to the table+ * keeps the two in step at compile time.+ */+export interface ChannelMessage {+ /** Actual Agent sender; NULL once that author is deleted. */+ agentId: string | null;+ channelId: string;+ content: string;+ createdAt: Date;+ id: string;+ /** What the message is; its payload lives in `metadata.<kind>`. */+ kind: ChannelMessageKind;+ /** Mentioned member ids. Mentioned Agents run; mentioned people are only notified. */+ mentions: string[];+ metadata: ChannelMessageMetadata | null;+ /** Agent member ids that actually received a job for this message. */+ recipientMemberIds: string[];+ replyToId: string | null;+ /** Client retry key for a human message; run identity for a published reply. */+ requestKey: string;+ /** Incremented each time routing starts, so a late decision cannot overwrite a retry. */+ routingAttempt: number;+ /** Human-readable explanation of why these recipients (or none) were chosen. */+ routingReason: string | null;+ /** Where the recipients came from; NULL until routing settles, and on replies. */+ routingSource: ChannelMessageRoutingSource | null;+ routingStatus: ChannelMessageRoutingStatus;+ sequence: number;+ threadId: string | null;+ /** Actual human sender, not the owner/requester of an Agent reply; NULL once deleted. */+ userId: string | null;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex f1df95968ce..f2b869223da 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -18,6 +18,8 @@ export * from './asyncTask';export * from './auth';export * from './brief';export * from './channel';+export * from './channelAsk';+export * from './channelMessage';export * from './channelMessageCard';export * from './chunk';export * from './contact';diff --git a/src/features/Channels/AskCard.tsx b/src/features/Channels/AskCard.tsxnew file mode 100644index 00000000000..1516c307713--- /dev/null+++ b/src/features/Channels/AskCard.tsx@@ -0,0 +1,341 @@+import type {+ ChannelAsk,+ ChannelAskAnswerItem,+ ChannelAskQuestion,+ ChannelDetail,+ ChannelPublicMessage,+} from '@lobechat/types';+import { CHANNEL_ASK_LIMITS } from '@lobechat/types';+import { Button, Icon, Input, Text, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { Check } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { channelActions } from '@/store/channel';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import { isCurrentUserMember, memberName } from './memberName';++const styles = stylex.create({+ card: {+ display: 'flex',+ flexDirection: 'column',+ gap: 16,+ width: '100%',+ maxWidth: 560,+ paddingBlock: 16,+ paddingInline: 16,+ borderRadius: 16,+ backgroundColor: cssVar.colorFillQuaternary,+ },+ question: {+ display: 'flex',+ flexDirection: 'column',+ gap: 4,+ },+ option: {+ display: 'flex',+ gap: 10,+ alignItems: 'center',+ width: '100%',+ marginBlock: 0,+ marginInline: 0,+ paddingBlock: 6,+ paddingInline: 6,+ borderWidth: 0,+ borderStyle: 'none',+ borderRadius: 10,+ font: 'inherit',+ color: cssVar.colorText,+ textAlign: 'start',+ backgroundColor: {+ 'default': 'transparent',+ ':hover': cssVar.colorFillTertiary,+ },+ cursor: 'pointer',+ },+ optionStatic: {+ backgroundColor: 'transparent',+ cursor: 'default',+ },+ optionPicked: {+ backgroundColor: cssVar.colorFillSecondary,+ },+ optionFaded: {+ opacity: 0.45,+ },+ letter: {+ display: 'inline-flex',+ flexShrink: 0,+ alignItems: 'center',+ justifyContent: 'center',+ width: 28,+ height: 28,+ borderRadius: 8,+ fontSize: 12,+ fontWeight: 500,+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillTertiary,+ },+ letterPicked: {+ color: cssVar.colorBgContainer,+ backgroundColor: cssVar.colorText,+ },+ label: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ minWidth: 0,+ },+ footer: {+ display: 'flex',+ gap: 8,+ alignItems: 'center',+ justifyContent: 'space-between',+ },+});++const letterOf = (index: number) => String.fromCodePoint(65 + index);++interface Draft {+ other: string;+ otherOpen: boolean;+ selected: string[];+}++const emptyDraft = (): Draft => ({ other: '', otherOpen: false, selected: [] });++const toAnswer = ({ other, otherOpen, selected }: Draft): ChannelAskAnswerItem => ({+ selected,+ ...(otherOpen && other.trim() && { other: other.trim() }),+});++const answered = (draft: Draft) =>+ draft.selected.length > 0 || (draft.otherOpen && !!draft.other.trim());++const OptionRow = ({+ description,+ faded,+ index,+ label,+ onClick,+ picked,+}: {+ description?: string;+ faded?: boolean;+ index: number;+ label: string;+ onClick?: () => void;+ picked: boolean;+}) => (+ <button+ aria-pressed={onClick ? picked : undefined}+ disabled={!onClick}+ type="button"+ onClick={onClick}+ {...stylex.props(+ styles.option,+ !onClick && styles.optionStatic,+ picked && styles.optionPicked,+ faded && styles.optionFaded,+ )}+ >+ <span {...stylex.props(styles.letter, picked && styles.letterPicked)}>+ {picked ? <Icon icon={Check} size={14} /> : letterOf(index)}+ </span>+ <span {...stylex.props(styles.label)}>+ <span>{label}</span>+ {description && (+ <Text fontSize={12} type="secondary">+ {description}+ </Text>+ )}+ </span>+ </button>+);++const QuestionBlock = ({+ answer,+ draft,+ onChange,+ onPick,+ question,+}: {+ /** Set once answered: shows what was picked, read-only. */+ answer?: ChannelAskAnswerItem;+ /** Set while the viewer may answer. */+ draft?: Draft;+ onChange?: (draft: Draft) => void;+ /** A single-choice pick that completes the whole card. */+ onPick?: (label: string) => void;+ question: ChannelAskQuestion;+}) => {+ const { t } = useTranslation('channel');+ const interactive = !!draft && !!onChange;+ const otherIndex = question.options.length;+ const otherPicked = answer ? !!answer.other : !!draft?.otherOpen;++ const toggle = (label: string) => {+ if (!draft || !onChange) return;+ if (!question.multiSelect) {+ if (onPick) return onPick(label);+ return onChange({ ...draft, otherOpen: false, selected: [label] });+ }+ const selected = draft.selected.includes(label)+ ? draft.selected.filter((value) => value !== label)+ : [...draft.selected, label];+ onChange({ ...draft, selected });+ };++ return (+ <div {...stylex.props(styles.question)}>+ {question.header && (+ <Text fontSize={12} type="secondary">+ {question.header}+ </Text>+ )}+ <Text strong>{question.question}</Text>+ {question.multiSelect && interactive && (+ <Text fontSize={12} type="secondary">+ {t('ask.multiSelect')}+ </Text>+ )}+ {question.options.map((option, index) => {+ const picked = answer+ ? answer.selected.includes(option.label)+ : !!draft?.selected.includes(option.label);+ return (+ <OptionRow+ description={option.description}+ faded={!!answer && !picked}+ index={index}+ key={option.label}+ label={option.label}+ picked={picked}+ onClick={interactive ? () => toggle(option.label) : undefined}+ />+ );+ })}+ {(interactive || answer?.other) && (+ <OptionRow+ faded={!!answer && !otherPicked}+ index={otherIndex}+ label={answer?.other ?? t('ask.other')}+ picked={otherPicked}+ onClick={+ interactive+ ? () =>+ onChange!({+ ...draft!,+ otherOpen: !draft!.otherOpen,+ selected: question.multiSelect ? draft!.selected : [],+ })+ : undefined+ }+ />+ )}+ {interactive && draft!.otherOpen && (+ <Input+ autoFocus+ maxLength={CHANNEL_ASK_LIMITS.otherLength}+ placeholder={t('ask.otherPlaceholder')}+ value={draft!.other}+ onChange={(event) => onChange!({ ...draft!, other: event.target.value })}+ />+ )}+ </div>+ );+};++/**+ * An Agent's question with options. Its requester answers with a tap (or their own words under+ * "Other"); the answer posts as their reply and wakes the Agent. Everyone else, and everyone+ * once it is answered, sees it read-only.+ */+export const AskCard = ({+ ask,+ detail,+ message,+}: {+ ask: ChannelAsk;+ detail: ChannelDetail;+ message: ChannelPublicMessage;+}) => {+ const { t } = useTranslation('channel');+ const userId = useUserStore(userProfileSelectors.userId);+ const requester = detail.members.find((member) => member.id === ask.requesterMemberId);+ const canAnswer =+ ask.status === 'pending' &&+ !message.deletedAt &&+ !!requester &&+ isCurrentUserMember(requester, userId);+ const [drafts, setDrafts] = useState<Draft[]>(() => ask.questions.map(emptyDraft));+ const [submitting, setSubmitting] = useState(false);++ const submit = async (answers: ChannelAskAnswerItem[]) => {+ setSubmitting(true);+ try {+ await channelActions.answerAsk({+ answers,+ channelId: detail.channel.id,+ messageId: message.id,+ // One answer per question: a retry of the same answer returns what it posted.+ requestKey: `ask-answer:${message.id}`,+ threadId: message.threadId,+ });+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t('ask.failed'));+ } finally {+ setSubmitting(false);+ }+ };++ // One single-choice question needs no confirm step: the tap is the answer.+ const instant = ask.questions.length === 1 && !ask.questions[0].multiSelect;+ const complete = drafts.every(answered);++ return (+ <div {...stylex.props(styles.card)}>+ {ask.questions.map((question, index) => (+ <QuestionBlock+ answer={ask.status === 'answered' ? ask.answer?.answers[index] : undefined}+ draft={canAnswer && !submitting ? drafts[index] : undefined}+ key={index}+ question={question}+ onPick={instant ? (label) => submit([{ selected: [label] }]) : undefined}+ onChange={(draft) =>+ setDrafts((current) => current.map((item, at) => (at === index ? draft : item)))+ }+ />+ ))}+ {canAnswer && (!instant || drafts[0].otherOpen) && (+ <div {...stylex.props(styles.footer)}>+ <span />+ <Button+ disabled={!complete}+ loading={submitting}+ type="primary"+ onClick={() => submit(drafts.map(toAnswer))}+ >+ {t('ask.submit')}+ </Button>+ </div>+ )}+ {!canAnswer && (+ <Text fontSize={12} type="secondary">+ {ask.status === 'answered'+ ? t('ask.answeredBy', {+ name: memberName(+ detail.members.find((member) => member.id === ask.answer?.memberId),+ t('deletedMember'),+ ),+ })+ : t('ask.waitingFor', { name: memberName(requester, t('deletedMember')) })}+ </Text>+ )}+ </div>+ );+};diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsxindex ff022055532..24cce79ab02 100644--- a/src/features/Channels/ChannelMessage.tsx+++ b/src/features/Channels/ChannelMessage.tsx@@ -36,6 +36,7 @@ import UserAvatar from '@/features/User/UserAvatar';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';+import { AskCard } from './AskCard';import { authorAvatar, isCurrentUserAuthor, memberName } from './memberName';import { CHANNEL_MENTION_TAG, remarkChannelMentions } from './mentionMarkdown';import { MessageAttachments } from './MessageAttachments';@@ -150,6 +151,9 @@ export const ChannelMessage = ({? detail.members.find((member) => member.agentId === agentAuthorId): undefined;const sourceTopicId = message.sourceTopicId;+ // A question card shows its options itself; the text fallback after the Agent's words is for+ // clients that cannot render it.+ const body = message.ask ? message.content.slice(0, message.ask.bodyLength) : message.content;// A direct conversation is a chat with one Agent; folding its answers only adds a click.const collapsible = !detail.channel.agentId;// Long messages stay open by default; folding one is an explicit choice from "more".@@ -324,7 +328,7 @@ export const ChannelMessage = ({{message.fileIds.length > 0 && (<MessageAttachments attachments={detail.attachments} fileIds={message.fileIds} />)}- {message.content &&+ {body &&(collapsible ? (<CollapsibleContenthideCollapseToggle@@ -334,11 +338,12 @@ export const ChannelMessage = ({onCollapsedChange={setCollapsed}onOverflowChange={setOverflowing}>- <MessageText content={message.content} names={mentionNames} />+ <MessageText content={body} names={mentionNames} /></CollapsibleContent>) : (- <MessageText content={message.content} names={mentionNames} />+ <MessageText content={body} names={mentionNames} />))}+ {message.ask && <AskCard ask={message.ask} detail={detail} message={message} />}{!!message.works?.length && <ReplyWorks works={message.works} />}{failures?.map((job) => (<ReplyFailureCard job={job} key={job.id} />diff --git a/src/services/channel.ts b/src/services/channel.tsindex f4f0721336c..d6f83ba65fb 100644--- a/src/services/channel.ts+++ b/src/services/channel.ts@@ -1,4 +1,5 @@import type {+ ChannelAskAnswerItem,ChannelDetail,ChannelJoinableItem,ChannelListItem,@@ -33,6 +34,12 @@ export interface ChannelViewParams {}class ChannelService {+ answerAsk = (input: {+ answers: ChannelAskAnswerItem[];+ channelId: string;+ messageId: string;+ requestKey: string;+ }) => lambdaClient.channel.answerAsk.mutate(input);archive = (channelId: string) => lambdaClient.channel.archive.mutate({ channelId });unarchive = (channelId: string) => lambdaClient.channel.unarchive.mutate({ channelId });archiveThread = (channelId: string, threadId: string) =>diff --git a/src/store/channel/action.answerAsk.test.ts b/src/store/channel/action.answerAsk.test.tsnew file mode 100644index 00000000000..d363f1fd4fd--- /dev/null+++ b/src/store/channel/action.answerAsk.test.ts@@ -0,0 +1,84 @@+import type { ChannelDetail } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { channelService } from '@/services/channel';++import { channelActions } from './action';+import { channelViewKey } from './projection';+import { useChannelStore } from './store';++vi.mock('@/services/channel', () => ({+ channelService: { answerAsk: vi.fn(), detail: vi.fn(), list: vi.fn() },+}));++const main = { channelId: 'channel' };+const data = {+ attachments: [],+ channel: {+ createdAt: new Date(),+ id: 'channel',+ sequence: 1,+ title: 'Channel',+ workspaceId: null,+ },+ hasMore: false,+ jobs: [],+ members: [],+ messages: [],+ rootMessage: null,+ threads: [],+} satisfies ChannelDetail;++const answer = {+ answers: [{ selected: ['Approve'] }],+ channelId: 'channel',+ messageId: 'message',+ requestKey: 'ask-answer:message',+ threadId: null,+};++describe('Channel ask answer refresh', () => {+ beforeEach(() => {+ const scope = crypto.randomUUID();+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(false);+ vi.mocked(channelService.list).mockResolvedValue([data.channel]);+ vi.mocked(channelService.detail).mockResolvedValue(data);+ vi.mocked(channelService.answerAsk).mockResolvedValue({ success: true } as never);+ channelActions.reset();+ });+ afterEach(() => {+ channelActions.reset();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('refreshes the conversation and the sidebar after the answer is saved', async () => {+ await channelActions.answerAsk(answer);++ expect(channelService.answerAsk).toHaveBeenCalledWith({+ answers: answer.answers,+ channelId: answer.channelId,+ messageId: answer.messageId,+ requestKey: answer.requestKey,+ });+ const state = useChannelStore.getState();+ expect(state.detailMap[channelViewKey(main)]).toEqual(data);+ expect(state.listMap.all).toEqual([data.channel]);+ });++ // The answer is committed once the write returns: an offline refresh must not read back as a+ // failed answer, or the card stays actionable and the same question can be answered twice.+ it('keeps the saved answer when the refreshes fail', async () => {+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(channelService.detail).mockRejectedValue(new Error('offline'));+ vi.mocked(channelService.list).mockRejectedValue(new Error('offline'));++ await expect(channelActions.answerAsk(answer)).resolves.toBeUndefined();++ expect(channelService.answerAsk).toHaveBeenCalledTimes(1);+ expect(logged).toHaveBeenCalled();+ });+});diff --git a/src/store/channel/action.ts b/src/store/channel/action.tsindex f808d15b42a..eff2c48b6f2 100644--- a/src/store/channel/action.ts+++ b/src/store/channel/action.ts@@ -441,6 +441,22 @@ class ChannelActionImpl {this.refreshList(),]),);+ /** Answers an Agent's question card; the answer posts as the person's reply to it. */+ answerAsk = async (+ input: Parameters<typeof channelService.answerAsk>[0] & { threadId: string | null },+ ) => {+ const { threadId, ...answer } = input;+ await channelService.answerAsk(answer);+ // The answer is committed once the write returns. A refresh that fails afterwards must not+ // read back as a failed answer: the card would stay actionable and the question could be+ // answered twice. Same policy as every other write path: log the refresh, keep the write.+ await this.#refreshAfterWrite(() =>+ Promise.all([+ this.refreshDetail({ channelId: input.channelId, threadId }),+ this.refreshList(),+ ]),+ );+ };stop = async (channelId: string, scope: Parameters<typeof channelService.stop>[1]) => {await channelService.stop(channelId, scope);await this.refreshDetail({ channelId, threadId: 'threadId' in scope ? scope.threadId : null });