π€― 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
π fix(channel): let CLI runs read other Threads and 404 malformed message ids (#23769)
Arvin Xu54e23788227d
diff --git a/apps/cli/src/commands/channel.test.ts b/apps/cli/src/commands/channel.test.tsindex 4116965084b..22807089148 100644--- a/apps/cli/src/commands/channel.test.ts+++ b/apps/cli/src/commands/channel.test.ts@@ -14,21 +14,31 @@ const historyMessage = {truncated: false,};-const { listChannels, listPeople, messagePerson, readMessages, readMessage, sendMessage, output } =- vi.hoisted(() => ({- listChannels: vi.fn(),- listPeople: vi.fn(),- messagePerson: vi.fn(),- readMessages: vi.fn(),- readMessage: vi.fn(),- sendMessage: vi.fn(),- output: vi.fn(),- }));+const {+ listChannels,+ listPeople,+ listThreads,+ messagePerson,+ readMessages,+ readMessage,+ sendMessage,+ output,+} = vi.hoisted(() => ({+ listChannels: vi.fn(),+ listThreads: vi.fn(),+ listPeople: vi.fn(),+ messagePerson: vi.fn(),+ readMessages: vi.fn(),+ readMessage: vi.fn(),+ sendMessage: vi.fn(),+ output: vi.fn(),+}));vi.mock('../api/client', () => ({getTrpcClient: async () => ({channel: {listChannels: { query: listChannels },listPeople: { query: listPeople },+ listThreads: { query: listThreads },messagePerson: { mutate: messagePerson },readMessages: { query: readMessages },readMessage: { query: readMessage },@@ -49,7 +59,11 @@ describe('Channel CLI', () => {const page = { cutoffSequence: 20, messages: [historyMessage], nextBeforeSequence: 12 };readMessages.mockResolvedValue(page);await run(['channel', 'history', '--before', '20', '--limit', '5', '--json']);- expect(readMessages).toHaveBeenCalledWith({ beforeSequence: 20, limit: 5 });+ expect(readMessages).toHaveBeenCalledWith({+ beforeSequence: 20,+ limit: 5,+ threadId: undefined,+ });expect(output).toHaveBeenCalledWith({messages: [{@@ -67,7 +81,11 @@ describe('Channel CLI', () => {it('continues a long message', async () => {readMessage.mockResolvedValue({ message: historyMessage, nextOffset: null, offset: 12000 });await run(['channel', 'message', 'message-id', '--offset', '12000', '--json']);- expect(readMessage).toHaveBeenCalledWith({ messageId: 'message-id', offset: 12000 });+ expect(readMessage).toHaveBeenCalledWith({+ messageId: 'message-id',+ offset: 12000,+ threadId: undefined,+ });const result = output.mock.calls[0][0];expect(result.message).not.toHaveProperty('sequence');expect(result.message).not.toHaveProperty('threadId');@@ -76,6 +94,29 @@ describe('Channel CLI', () => {expect(result.nextOffset).toBeNull();expect(result.offset).toBe(12000);});+ it('lists the Channel Threads and reads one by its id', async () => {+ const threads = { nextBefore: null, threads: [] };+ listThreads.mockResolvedValue(threads);+ await run(['channel', 'threads', '--active', '--limit', '3', '--json']);+ expect(listThreads).toHaveBeenCalledWith({ activeOnly: true, before: undefined, limit: 3 });+ expect(output).toHaveBeenCalledWith(threads);++ readMessages.mockResolvedValue({ cutoffSequence: 9, messages: [], nextBeforeSequence: null });+ await run(['channel', 'history', '--thread', 'cht_example', '--json']);+ expect(readMessages).toHaveBeenCalledWith({+ beforeSequence: undefined,+ limit: undefined,+ threadId: 'cht_example',+ });++ readMessage.mockResolvedValue({ message: historyMessage, nextOffset: null, offset: 0 });+ await run(['channel', 'message', 'message-id', '--thread', 'cht_example', '--json']);+ expect(readMessage).toHaveBeenCalledWith({+ messageId: 'message-id',+ offset: undefined,+ threadId: 'cht_example',+ });+ });it('surfaces denied reads without retrying under another credential', async () => {readMessages.mockRejectedValue(new Error('Operation has already ended'));await expect(run(['channel', 'history'])).rejects.toThrow('Operation has already ended');diff --git a/apps/cli/src/commands/channel.ts b/apps/cli/src/commands/channel.tsindex 2891d799db3..66c0355bc73 100644--- a/apps/cli/src/commands/channel.ts+++ b/apps/cli/src/commands/channel.ts@@ -16,8 +16,9 @@ const numberOption = (value: string) => {const collect = (value: string, previous: string[] = []) => [...previous, value];/**- * Operation-scoped: reads stay in the run's own conversation, and messages go out as the run's- * requester. Never falls back to the device owner's account.+ * Operation-scoped: reads stay in the run's Channel (its own conversation, or another Thread of+ * it by `--thread`), and messages go out as the run's requester. Never falls back to the device+ * owner's account.*/export const registerChannelCommand = (program: Command) => {const channel = program@@ -30,14 +31,19 @@ export const registerChannelCommand = (program: Command) => {.description('Read recent public messages; page backwards with the returned cursor').option('--before <sequence>', 'Exclusive nextBeforeSequence cursor', numberOption).option('--limit <count>', 'Messages per page (1β20, default 10)', numberOption)+ .option(+ '--thread <threadId>',+ 'Read another Thread of this Channel (from `channel threads`) live, instead of your own conversation',+ ).option('--json', 'Print structured JSON')- .action(async (options: { before?: number; limit?: number }) => {+ .action(async (options: { before?: number; limit?: number; thread?: string }) => {const client = await getTrpcClient();outputJson(projectChannelHistory(await client.channel.readMessages.query({beforeSequence: options.before,limit: options.limit,+ threadId: options.thread,}),),);@@ -46,15 +52,37 @@ export const registerChannelCommand = (program: Command) => {.command('message <id>').description('Read a full public message and its attachment links').option('--offset <characters>', 'Continue at nextOffset', numberOption)+ .option('--thread <threadId>', 'The Thread `history --thread` returned the message from').option('--json', 'Print structured JSON')- .action(async (messageId: string, options: { offset?: number }) => {+ .action(async (messageId: string, options: { offset?: number; thread?: string }) => {const client = await getTrpcClient();outputJson(projectChannelHistory(- await client.channel.readMessage.query({ messageId, offset: options.offset }),+ await client.channel.readMessage.query({+ messageId,+ offset: options.offset,+ threadId: options.thread,+ }),),);});+ channel+ .command('threads')+ .description('List the Threads of this Channel, newest first, to read one with --thread')+ .option('--active', 'Only Threads where you have a queued or running reply')+ .option('--before <threadId>', 'Exclusive cursor: nextBefore of the previous page')+ .option('--limit <count>', 'Threads per page (1β20, default 10)', numberOption)+ .option('--json', 'Print structured JSON')+ .action(async (options: { active?: boolean; before?: string; limit?: number }) => {+ const client = await getTrpcClient();+ outputJson(+ await client.channel.listThreads.query({+ activeOnly: options.active,+ before: options.before,+ limit: options.limit,+ }),+ );+ });channel.command('list').description(diff --git a/apps/server/src/routers/lambda/channelHistory.ts b/apps/server/src/routers/lambda/channelHistory.tsindex 4ee7165533e..8baf6e4f9c6 100644--- a/apps/server/src/routers/lambda/channelHistory.ts+++ b/apps/server/src/routers/lambda/channelHistory.ts@@ -72,6 +72,8 @@ export const channelHistoryProcedures = {.object({beforeSequence: z.number().int().positive().optional(),limit: z.number().int().min(1).max(20).optional(),+ /** Another Thread of the run's Channel, from `listThreads`. */+ threadId: z.string().min(1).optional(),}).strict(),)@@ -79,10 +81,25 @@ export const channelHistoryProcedures = {readMessage: historyProcedure.input(z- .object({ messageId: z.string().min(1), offset: z.number().int().nonnegative().optional() })+ .object({+ messageId: z.string().min(1),+ offset: z.number().int().nonnegative().optional(),+ threadId: z.string().min(1).optional(),+ }).strict(),).query(({ ctx, input }) => ctx.channelHistory.readMessage(input)),+ listThreads: historyProcedure+ .input(+ z+ .object({+ activeOnly: z.boolean().optional(),+ before: z.string().min(1).optional(),+ limit: z.number().int().min(1).max(20).optional(),+ })+ .strict(),+ )+ .query(({ ctx, input }) => ctx.channelHistory.listThreads(input)),listChannels: messagingProcedure.input(zdiff --git a/apps/server/src/services/channel/ChannelHistoryService.ts b/apps/server/src/services/channel/ChannelHistoryService.tsindex dadb3055dd7..e3f9620abef 100644--- a/apps/server/src/services/channel/ChannelHistoryService.ts+++ b/apps/server/src/services/channel/ChannelHistoryService.ts@@ -2,6 +2,7 @@ import { getOfficialMcpServerById, resolveConnectorCatalogItem } from '@lobechatimport type {ChannelConnectorRequest,ChannelConnectorRequestResult,+ ChannelListThreadsParams,ChannelReadMessageParams,ChannelReadMessagesParams,ChannelRequestConnectorParams,@@ -114,6 +115,12 @@ export class ChannelHistoryService {};};+ /** The Threads of the run's Channel, so a read can name one with `threadId`. */+ listThreads = async (params: ChannelListThreadsParams = {}) => {+ await assertChannelEnabled(this.userId);+ return this.repository.listThreads(this.operationId, params);+ };+/*** Posts a card in the run's conversation asking its requester to connect a connector; the* person connects from the card. `requestKey` (the tool call) keeps a retry from posting twice.diff --git a/packages/database/src/repositories/channel/__tests__/history.test.ts b/packages/database/src/repositories/channel/__tests__/history.test.tsindex 1bcd921b3b9..e5f9fad566b 100644--- a/packages/database/src/repositories/channel/__tests__/history.test.ts+++ b/packages/database/src/repositories/channel/__tests__/history.test.ts@@ -181,6 +181,22 @@ describe('Channel on-demand history', () => {).rejects.toMatchObject({ code: 'NOT_FOUND' });});+ it('rejects an unknown Thread and a malformed message id as NOT_FOUND', async () => {+ const state = await setup();+ await state.say('Own conversation');+ const { operationId, request } = await state.run();+ await expect(+ state.history.readMessages(operationId, { threadId: 'cht_missing' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(+ state.history.readMessage(operationId, { messageId: request.id, threadId: 'cht_missing' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ // A Thread id passed as a message id is not a uuid; it must not reach Postgres as one.+ await expect(+ state.history.readMessage(operationId, { messageId: 'cht_uvOObyIW8CII' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+it.each(['requester','agent',diff --git a/packages/database/src/repositories/channel/history.ts b/packages/database/src/repositories/channel/history.tsindex c73ccc8d648..c43722079d3 100644--- a/packages/database/src/repositories/channel/history.ts+++ b/packages/database/src/repositories/channel/history.ts@@ -40,6 +40,7 @@ import {import type { LobeChatDatabase, Transaction } from '../../type';import { agentTitleSql } from '../../utils/inboxAgent';import { notTrashed } from '../../utils/softDelete';+import { isUuid } from '../../utils/uuid';import { normalizeWorkspaceId } from '../../utils/workspace';import { activeMembers, appendMessage, findThread } from './delivery';import { ChannelError } from './error';@@ -682,9 +683,10 @@ export class ChannelHistoryRepository {? await findThread(tx, channelId, params.threadId): null;const manifest = other ? liveThreadManifest(runManifest, other) : runManifest;- const [message] = await readManifestMessages(tx, channelId, manifest, {- messageId: params.messageId,- });+ // Message ids are uuids; anything else (a Thread id, say) would abort the query.+ const [message] = isUuid(params.messageId)+ ? await readManifestMessages(tx, channelId, manifest, { messageId: params.messageId })+ : [];if (!message) throw new ChannelError('NOT_FOUND', 'Message not found in this conversation');if (offset > message.content.length)throw new ChannelError('BAD_REQUEST', 'Offset exceeds message length');