From 2cbf1cbde68c1f7606cb7793f02c29fffa48f271 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 20:58:43 -0800 Subject: [PATCH 01/10] feat(search): list your own chat history on Search MCP and in the Assistant --- .../contracts/mothership-assistant-tools.ts | 49 +++ .../application/chat-history.integration.ts | 291 ++++++++++++++++++ .../lib/knowledge/application/chat-history.ts | 183 +++++++++++ .../knowledge/application/chat-operations.ts | 15 + apps/sim/lib/knowledge/mcp/chat-history.ts | 42 +++ .../lib/knowledge/mcp/server.protocol.test.ts | 7 +- apps/sim/lib/knowledge/mcp/server.test.ts | 22 +- apps/sim/lib/knowledge/mcp/server.ts | 4 + apps/sim/lib/knowledge/mcp/tool-arguments.ts | 2 + .../execute-chat-history-use-case.ts | 39 +++ .../lib/mothership/assistant/tool-policy.ts | 1 + .../mothership/generated/tool-catalog-v1.ts | 51 +++ .../mothership/generated/tool-schemas-v1.ts | 44 +++ .../tools/server/knowledge/chat-history.ts | 40 +++ .../sim/lib/mothership/tools/server/router.ts | 2 + 15 files changed, 788 insertions(+), 4 deletions(-) create mode 100644 apps/sim/lib/knowledge/application/chat-history.integration.ts create mode 100644 apps/sim/lib/knowledge/application/chat-history.ts create mode 100644 apps/sim/lib/knowledge/mcp/chat-history.ts create mode 100644 apps/sim/lib/mothership/application/execute-chat-history-use-case.ts create mode 100644 apps/sim/lib/mothership/tools/server/knowledge/chat-history.ts diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index 3c3e5b9d99b..2c587b832ed 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -368,6 +368,48 @@ export const searchPeopleInputSchema = z message: 'Pass either personId or a query with its cursor, not both.', }) +/** + * The caller's own questions to Sim over a window, oldest first. The 92-day window and the page + * bounds are literals so the worker's generated copy stays standalone. + */ +export const listMyChatHistoryInputSchema = z + .object({ + startDate: z + .string() + .datetime({ offset: true }) + .describe( + 'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.' + ), + endDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + 'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.' + ), + topK: z + .number() + .int() + .min(1) + .max(100) + .optional() + .describe('Questions per page, 50 by default.'), + cursor: z + .string() + .min(1) + .max(1024) + .optional() + .describe('nextCursor from the previous page of the same window.'), + includeAnswers: z + .boolean() + .optional() + .describe( + "Adds the start of Sim's answer to each question. Answers reflect the sources as they were when asked." + ), + }) + .strict() +export type ListMyChatHistoryInput = z.output + /** Connection requests name a provider and optionally an owned account to repair. */ export const oauthGetAuthLinkInputSchema = z.object({ providerName: z @@ -438,6 +480,13 @@ export const assistantToolContracts = [ 'Look up people in this organization’s directory by name, email, title, department, or location. Returns each person’s title, department, location, email, and manager. When exactly one person matches, or with a personId, returns that person with managerChain (direct manager first) and directReports. Covers only this organization’s people; use search_workspace for customers, vendors, and other outside contacts.', inputSchema: searchPeopleInputSchema, }, + { + id: 'list_my_chat_history', + route: 'sim', + description: + 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.', + inputSchema: listMyChatHistoryInputSchema, + }, { id: 'oauth_get_auth_link', route: 'sim', diff --git a/apps/sim/lib/knowledge/application/chat-history.integration.ts b/apps/sim/lib/knowledge/application/chat-history.integration.ts new file mode 100644 index 00000000000..7ca5c024ce3 --- /dev/null +++ b/apps/sim/lib/knowledge/application/chat-history.integration.ts @@ -0,0 +1,291 @@ +/** + * `list_my_chat_history` against real PostgreSQL: whose questions it returns, which conversations + * and turns it leaves out, its window bounds, keyset paging across identical timestamps, answer + * excerpts, and the principals it refuses. + */ +import type { SessionPrincipal, WorkspaceApiKeyPrincipal } from '@sim/auth/principal' +import { db } from '@sim/db' +import { + copilotChats, + copilotMessages, + member, + organization, + permissions, + project, + user, + workspace, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { inArray } from 'drizzle-orm' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { listMyChatHistory } from '@/lib/knowledge/application/chat-history' + +const organizationId = generateId() +const otherOrganizationId = generateId() +const callerId = generateId() +const colleagueId = generateId() +const outsiderId = generateId() +const users = [callerId, colleagueId, outsiderId] +const organizationProjectId = generateId() +const otherProjectId = generateId() +const openWorkspaceId = generateId() +const closedWorkspaceId = generateId() +const otherOrganizationWorkspaceId = generateId() + +const WINDOW = { startDate: '2026-11-01T00:00:00Z', endDate: '2026-11-08T00:00:00Z' } + +function session(userId: string): SessionPrincipal { + return { kind: 'session', userId, sessionId: generateId() } +} + +function list(input: Record = {}, userId = callerId) { + return listMyChatHistory.execute({ + principal: session(userId), + input: { ...WINDOW, organizationId, ...input }, + }) +} + +async function chat(values: Partial = {}): Promise { + const id = generateId() + await db.insert(copilotChats).values({ + id, + userId: callerId, + organizationId, + type: 'mothership', + ...values, + }) + return id +} + +async function ask( + chatId: string, + content: string, + createdAt: string, + extra: Partial = {} +): Promise { + await db.insert(copilotMessages).values({ + chatId, + messageId: generateId(), + role: 'user', + content: { content }, + createdAt: new Date(createdAt), + ...extra, + }) +} + +describe('list_my_chat_history', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + users.map((id) => ({ + id, + name: 'History fixture', + email: `${id}@chat-history.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db.insert(organization).values( + [organizationId, otherOrganizationId].map((id) => ({ + id, + name: 'History fixture', + slug: `history-${id}`, + })) + ) + await db.insert(member).values([ + { id: generateId(), userId: callerId, organizationId, role: 'member' }, + { id: generateId(), userId: colleagueId, organizationId, role: 'member' }, + { + id: generateId(), + userId: outsiderId, + organizationId: otherOrganizationId, + role: 'member', + }, + ]) + await db.insert(project).values([ + { id: organizationProjectId, name: 'History', ownerId: colleagueId, organizationId }, + { + id: otherProjectId, + name: 'History', + ownerId: outsiderId, + organizationId: otherOrganizationId, + }, + ]) + await db.insert(workspace).values( + [ + [openWorkspaceId, organizationProjectId, organizationId], + [closedWorkspaceId, organizationProjectId, organizationId], + [otherOrganizationWorkspaceId, otherProjectId, otherOrganizationId], + ].map(([id, projectId, orgId]) => ({ + id, + projectId, + name: 'History workspace', + ownerId: orgId === organizationId ? colleagueId : outsiderId, + billedAccountUserId: orgId === organizationId ? colleagueId : outsiderId, + organizationId: orgId, + workspaceMode: 'organization' as const, + })) + ) + await db.insert(permissions).values( + [openWorkspaceId, otherOrganizationWorkspaceId].map((entityId) => ({ + id: generateId(), + userId: callerId, + entityType: 'workspace', + entityId, + permissionType: 'write' as const, + })) + ) + }) + + beforeEach(async () => { + await db.delete(copilotChats).where(inArray(copilotChats.userId, users)) + }) + + afterAll(async () => { + await db.delete(copilotChats).where(inArray(copilotChats.userId, users)) + await db + .delete(workspace) + .where( + inArray(workspace.id, [openWorkspaceId, closedWorkspaceId, otherOrganizationWorkspaceId]) + ) + await db.delete(project).where(inArray(project.id, [organizationProjectId, otherProjectId])) + await db + .delete(organization) + .where(inArray(organization.id, [organizationId, otherOrganizationId])) + await db.delete(user).where(inArray(user.id, users)) + }) + + it("returns only the caller's own questions, oldest first, with their surface and link", async () => { + const assistant = await chat() + const slack = await chat({ externalConversationKey: 'slack:["i","D1","t"]' }) + const agent = await chat({ config: { conversationMode: 'agent' } }) + await ask(assistant, 'second', '2026-11-02T10:00:00Z') + await ask(slack, 'first', '2026-11-01T09:00:00Z') + await ask(agent, 'third', '2026-11-03T08:00:00Z') + await ask(await chat({ userId: colleagueId }), 'colleague question', '2026-11-02T11:00:00Z') + + const { questions, nextCursor } = await list() + + expect( + questions.map(({ question, surface, timestamp }) => [question, surface, timestamp]) + ).toEqual([ + ['first', 'slack', '2026-11-01T09:00:00.000Z'], + ['second', 'assistant', '2026-11-02T10:00:00.000Z'], + ['third', 'agent', '2026-11-03T08:00:00.000Z'], + ]) + expect(questions[1]?.conversationUrl).toMatch( + new RegExp(`/o/${organizationId}/chat/${assistant}$`) + ) + expect(nextCursor).toBeUndefined() + }) + + it('leaves out deleted conversations and messages, automated turns, workflow copilot and benchmark chats', async () => { + const kept = await chat() + await ask(kept, 'kept', '2026-11-02T10:00:00Z') + await ask(kept, 'deleted message', '2026-11-02T10:01:00Z', { deletedAt: new Date() }) + await ask(kept, 'scheduled job brief', '2026-11-02T10:02:00Z', { + content: { content: 'Job: brief', origin: 'job' }, + }) + await ask(await chat({ deletedAt: new Date() }), 'deleted chat', '2026-11-02T11:00:00Z') + await ask( + await chat({ config: { benchmark: { id: 'b' } } }), + 'benchmark', + '2026-11-02T12:00:00Z' + ) + await ask( + await chat({ type: 'copilot', organizationId: null, workspaceId: openWorkspaceId }), + 'workflow copilot', + '2026-11-02T13:00:00Z' + ) + + expect((await list()).questions.map((q) => q.question)).toEqual(['kept']) + }) + + it("includes home chats only in the organization's workspaces the caller can open", async () => { + await ask( + await chat({ organizationId: null, workspaceId: openWorkspaceId }), + 'open workspace', + '2026-11-02T10:00:00Z' + ) + await ask( + await chat({ organizationId: null, workspaceId: closedWorkspaceId }), + 'closed workspace', + '2026-11-02T11:00:00Z' + ) + await ask( + await chat({ organizationId: null, workspaceId: otherOrganizationWorkspaceId }), + 'other organization', + '2026-11-02T12:00:00Z' + ) + + const { questions } = await list() + expect(questions.map((q) => [q.question, q.surface])).toEqual([['open workspace', 'agent']]) + expect(questions[0]?.conversationUrl).toMatch(new RegExp(`/workspace/${openWorkspaceId}/chat/`)) + }) + + it('includes startDate and excludes endDate, and refuses a window over 92 days', async () => { + const id = await chat() + await ask(id, 'at start', WINDOW.startDate) + await ask(id, 'at end', WINDOW.endDate) + + expect((await list()).questions.map((q) => q.question)).toEqual(['at start']) + await expect( + list({ startDate: '2026-01-01T00:00:00Z', endDate: '2026-04-04T00:00:00Z' }) + ).rejects.toThrow(/at most 92 days/) + await expect(list({ endDate: WINDOW.startDate })).rejects.toThrow(/after startDate/) + }) + + it('pages through questions asked at the same instant without repeating or skipping one', async () => { + const id = await chat() + for (let index = 0; index < 5; index++) await ask(id, `q${index}`, '2026-11-02T10:00:00Z') + + const seen: string[] = [] + let cursor: string | undefined + do { + const page = await list({ topK: 2, ...(cursor ? { cursor } : {}) }) + seen.push(...page.questions.map((q) => q.question)) + cursor = page.nextCursor + } while (cursor) + + expect(seen.sort()).toEqual(['q0', 'q1', 'q2', 'q3', 'q4']) + await expect(list({ cursor: 'not-a-cursor' })).rejects.toThrow(/nextCursor/) + }) + + it('adds the start of the next answer, without citation tags, only when asked', async () => { + const id = await chat() + await ask(id, 'what shipped?', '2026-11-02T10:00:00Z') + await db.insert(copilotMessages).values({ + chatId: id, + messageId: generateId(), + role: 'assistant', + content: { + content: `Two releases shipped {"id":"c1"}. ${'x'.repeat(900)}`, + }, + createdAt: new Date('2026-11-02T10:00:30Z'), + }) + + const withAnswers = (await list({ includeAnswers: true })).questions[0] + expect(withAnswers?.answerExcerpt?.startsWith('Two releases shipped . x')).toBe(true) + expect(withAnswers?.answerExcerpt?.length).toBeLessThanOrEqual(603) + expect((await list()).questions[0]?.answerExcerpt).toBeUndefined() + }) + + it('refuses a caller outside the organization and a principal that is not a person', async () => { + await ask(await chat(), 'private', '2026-11-02T10:00:00Z') + + await expect(list({}, outsiderId)).rejects.toThrow() + const workspaceKey: WorkspaceApiKeyPrincipal = { + kind: 'workspace_api_key', + workspaceId: openWorkspaceId, + keyId: generateId(), + access: 'read', + } + await expect( + listMyChatHistory.execute({ + principal: workspaceKey, + input: { ...WINDOW, organizationId }, + }) + ).rejects.toThrow() + }) +}) diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts new file mode 100644 index 00000000000..33b61127246 --- /dev/null +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -0,0 +1,183 @@ +import { requirePrincipalSubjectUserId } from '@sim/auth/principal' +import { db } from '@sim/db' +import { copilotChats, copilotMessages } from '@sim/db/schema' +import { truncate } from '@sim/utils/string' +import { and, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm' +import type { ListMyChatHistoryInput } from '@/lib/api/contracts/mothership-assistant-tools' +import { defineAuthorizedOrganizationUseCase } from '@/lib/core/application/authorized-organization-use-case' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { getBaseUrl } from '@/lib/core/utils/urls' +import { stripInteractiveCards } from '@/lib/knowledge/application/chat-citations' +import { listMyChatHistoryOperation } from '@/lib/knowledge/application/chat-operations' +import { conversationModeSelection } from '@/lib/mothership/chat/intent' +import { organizationRoutes } from '@/lib/navigation/paths' +import { listAccessibleWorkspaceRowsForUser } from '@/lib/workspaces/utils' + +const DAY_MS = 86_400_000 +const MAX_WINDOW_DAYS = 92 +const DEFAULT_TOP_K = 50 +const QUESTION_MAX_CHARS = 2_000 +const ANSWER_EXCERPT_MAX_CHARS = 600 + +export type ChatHistorySurface = 'assistant' | 'agent' | 'slack' + +export interface ChatHistoryQuestion { + /** When the question was asked, as an ISO datetime in UTC. */ + timestamp: string + question: string + chatId: string + conversationUrl: string + surface: ChatHistorySurface + /** The start of Sim's answer, when asked for and the question was answered. */ + answerExcerpt?: string +} + +export interface ChatHistoryPage { + questions: ChatHistoryQuestion[] + nextCursor?: string +} + +type ListMyChatHistoryUseCaseInput = ListMyChatHistoryInput & { organizationId: string } + +/** A position in the caller's questions: the exact stored time and message id of the last row. */ +function encodeCursor(createdAt: string, id: string): string { + return Buffer.from(JSON.stringify([createdAt, id])).toString('base64url') +} + +function decodeCursor(cursor: string): [string, string] { + try { + const decoded: unknown = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) + if ( + Array.isArray(decoded) && + decoded.length === 2 && + typeof decoded[0] === 'string' && + !Number.isNaN(Date.parse(`${decoded[0]}Z`)) && + typeof decoded[1] === 'string' && + /^[0-9a-f-]{36}$/i.test(decoded[1]) + ) + return [decoded[0], decoded[1]] + } catch {} + throw new OrchestrationError('validation', 'cursor is not a nextCursor from this tool') +} + +function resolveWindow(input: ListMyChatHistoryUseCaseInput): { from: Date; to: Date } { + const from = new Date(input.startDate) + const to = input.endDate ? new Date(input.endDate) : new Date() + if (Number.isNaN(from.getTime()) || Number.isNaN(to.getTime())) + throw new OrchestrationError('validation', 'startDate and endDate must be ISO datetimes') + if (to <= from) throw new OrchestrationError('validation', 'endDate must be after startDate') + if (to.getTime() - from.getTime() > MAX_WINDOW_DAYS * DAY_MS) + throw new OrchestrationError( + 'validation', + `The window is at most ${MAX_WINDOW_DAYS} days; page through a longer period in parts` + ) + return { from, to } +} + +/** Answer text as a reader sees it: no interactive cards, citation tags or runs of whitespace. */ +function answerExcerpt(content: string | null): string | undefined { + if (!content) return undefined + const text = stripInteractiveCards(content) + .replace(/[\s\S]*?<\/source>/g, '') + .replace(/\s+/g, ' ') + .trim() + return text ? truncate(text, ANSWER_EXCERPT_MAX_CHARS) : undefined +} + +/** + * The caller's own questions to Sim in this organization, oldest first: Assistant and agent chats + * in the organization (including those asked through the Slack app and Search MCP `chat`), and + * home chats in the organization's workspaces the caller can still open. Deleted conversations and + * messages, automated task and job turns, workflow copilot chats and benchmark runs are left out. + * The caller is always the authenticated person; no input names anyone else. + */ +export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ + operation: listMyChatHistoryOperation, + async execute({ principal, input }): Promise { + const userId = requirePrincipalSubjectUserId(principal) + const { organizationId } = input + const { from, to } = resolveWindow(input) + const topK = input.topK ?? DEFAULT_TOP_K + const after = input.cursor ? decodeCursor(input.cursor) : undefined + + const workspaceIds = (await listAccessibleWorkspaceRowsForUser(userId, 'active')) + .filter(({ workspace }) => workspace.organizationId === organizationId) + .map(({ workspace }) => workspace.id) + const owned: SQL | undefined = workspaceIds.length + ? or( + eq(copilotChats.organizationId, organizationId), + inArray(copilotChats.workspaceId, workspaceIds) + ) + : eq(copilotChats.organizationId, organizationId) + + const answer = input.includeAnswers + ? sql`( + SELECT coalesce(a.display_content, a.content)->>'content' + FROM ${copilotMessages} a + WHERE a.chat_id = ${copilotMessages.chatId} AND a.role = 'assistant' + AND a.deleted_at IS NULL + AND (a.created_at, a.id) > (${copilotMessages.createdAt}, ${copilotMessages.id}) + ORDER BY a.created_at, a.id + LIMIT 1)` + : sql`NULL` + + const rows = await db + .select({ + id: copilotMessages.id, + chatId: copilotMessages.chatId, + createdAt: sql`${copilotMessages.createdAt}::text`, + question: sql`${copilotMessages.content}->>'content'`, + answer, + workspaceId: copilotChats.workspaceId, + slack: sql`coalesce(${copilotChats.externalConversationKey} LIKE 'slack:%', false)`, + mode: conversationModeSelection, + }) + .from(copilotMessages) + .innerJoin(copilotChats, eq(copilotChats.id, copilotMessages.chatId)) + .where( + and( + eq(copilotChats.userId, userId), + eq(copilotChats.type, 'mothership'), + owned, + isNull(copilotChats.deletedAt), + sql`${copilotChats.config}->'benchmark' IS NULL`, + eq(copilotMessages.role, 'user'), + isNull(copilotMessages.deletedAt), + sql`${copilotMessages.content}->>'origin' IS NULL`, + sql`${copilotMessages.createdAt} >= (${from.toISOString()}::timestamptz AT TIME ZONE 'UTC')`, + sql`${copilotMessages.createdAt} < (${to.toISOString()}::timestamptz AT TIME ZONE 'UTC')`, + after + ? sql`(${copilotMessages.createdAt}, ${copilotMessages.id}) > (${after[0]}::timestamp, ${after[1]}::uuid)` + : undefined + ) + ) + .orderBy(copilotMessages.createdAt, copilotMessages.id) + .limit(topK + 1) + + const page = rows.slice(0, topK) + const last = page[page.length - 1] + return { + questions: page.map((row) => { + const excerpt = answerExcerpt(row.answer) + return { + timestamp: new Date(`${row.createdAt.replace(' ', 'T')}Z`).toISOString(), + question: truncate(row.question ?? '', QUESTION_MAX_CHARS), + chatId: row.chatId, + conversationUrl: new URL( + row.workspaceId + ? `/workspace/${row.workspaceId}/chat/${row.chatId}` + : organizationRoutes(organizationId).chat(row.chatId), + getBaseUrl() + ).href, + surface: row.slack + ? 'slack' + : row.workspaceId || row.mode !== 'assistant' + ? 'agent' + : 'assistant', + ...(excerpt ? { answerExcerpt: excerpt } : {}), + } + }), + ...(rows.length > topK && last ? { nextCursor: encodeCursor(last.createdAt, last.id) } : {}), + } + }, +}) diff --git a/apps/sim/lib/knowledge/application/chat-operations.ts b/apps/sim/lib/knowledge/application/chat-operations.ts index e255ceb845f..fa03841ed20 100644 --- a/apps/sim/lib/knowledge/application/chat-operations.ts +++ b/apps/sim/lib/knowledge/application/chat-operations.ts @@ -7,3 +7,18 @@ export const organizationSearchChatOperation = defineOrganizationOperation({ principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], capability: 'copilot.use', }) + +/** + * A member reading back their own questions to Sim: in the app, through Search MCP clients under + * the scope that admits Search, and from the organization Assistant under its Search delegation. + */ +export const listMyChatHistoryOperation = defineOrganizationOperation({ + id: 'knowledge.chat_history.list', + oauthScope: 'search:read', + minimumRole: 'member', + principalKinds: ['session', 'personal_api_key', 'oauth_access_token', 'organization_delegated'], + delegationAudience: 'sim:knowledge', + delegatedServices: ['copilot'], + contentDelivery: 'none', + capability: 'copilot.use', +}) diff --git a/apps/sim/lib/knowledge/mcp/chat-history.ts b/apps/sim/lib/knowledge/mcp/chat-history.ts new file mode 100644 index 00000000000..07dd334ef85 --- /dev/null +++ b/apps/sim/lib/knowledge/mcp/chat-history.ts @@ -0,0 +1,42 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import type { Principal } from '@sim/auth/principal' +import { listMyChatHistoryInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' +import { listMyChatHistory } from '@/lib/knowledge/application/chat-history' +import { + KNOWLEDGE_MCP_READ_ONLY, + type KnowledgeMcpToolRunner, + projectResult, +} from '@/lib/knowledge/mcp/tool-runner' + +interface ChatHistoryToolContext { + execute: KnowledgeMcpToolRunner + principal: Principal + organizationId: string +} + +/** Registers `list_my_chat_history`: the caller's own questions to Sim, oldest first. */ +export function registerListMyChatHistoryTool( + server: McpServer, + { execute, principal, organizationId }: ChatHistoryToolContext +) { + server.registerTool( + 'list_my_chat_history', + { + title: 'List my chat history', + description: + 'List the questions you asked Sim between startDate (inclusive) and endDate (exclusive, at most 92 days later), oldest first: the Assistant, agent chats, the Slack app and this server’s chat tool. Each carries its time, a link to the conversation and, with includeAnswers, the start of the answer. Only your own conversations that still exist are listed. Follow nextCursor for the next page.', + inputSchema: listMyChatHistoryInputSchema, + annotations: KNOWLEDGE_MCP_READ_ONLY, + }, + async (input: unknown, extra: { signal: AbortSignal }) => + execute('list_my_chat_history', listMyChatHistory.operation, extra.signal, async (registry) => + projectResult( + await listMyChatHistory.execute({ + principal, + input: { ...listMyChatHistoryInputSchema.parse(input), organizationId }, + }), + registry + ) + ) + ) +} diff --git a/apps/sim/lib/knowledge/mcp/server.protocol.test.ts b/apps/sim/lib/knowledge/mcp/server.protocol.test.ts index 2e1dee80297..75372873bcb 100644 --- a/apps/sim/lib/knowledge/mcp/server.protocol.test.ts +++ b/apps/sim/lib/knowledge/mcp/server.protocol.test.ts @@ -72,7 +72,12 @@ describe('Search MCP protocol', () => { await server.connect(serverTransport) await client.connect(clientTransport) const { tools } = await client.listTools() - expect(tools.map((tool) => tool.name)).toEqual(['search', 'read_document', 'chat']) + expect(tools.map((tool) => tool.name)).toEqual([ + 'search', + 'read_document', + 'chat', + 'list_my_chat_history', + ]) const searchSchema = tools.find((tool) => tool.name === 'search')?.inputSchema const readSchema = tools.find((tool) => tool.name === 'read_document')?.inputSchema expect(searchSchema?.properties).toHaveProperty('nativeQueries') diff --git a/apps/sim/lib/knowledge/mcp/server.test.ts b/apps/sim/lib/knowledge/mcp/server.test.ts index 45ec7d82513..09c90ec596f 100644 --- a/apps/sim/lib/knowledge/mcp/server.test.ts +++ b/apps/sim/lib/knowledge/mcp/server.test.ts @@ -1,5 +1,8 @@ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js' -import { createPersonalApiKeyPrincipal } from '@sim/testing/factories/principal.factory' +import { + createPersonalApiKeyPrincipal, + createWorkspaceApiKeyPrincipal, +} from '@sim/testing/factories/principal.factory' import { apiServerRoutesMock } from '@sim/testing/mocks/api-server-routes.mock' import { getMockLogger } from '@sim/testing/mocks/logger.mock' import { urlsMockFns } from '@sim/testing/mocks/urls.mock' @@ -500,9 +503,22 @@ describe('organization Search MCP tools', () => { }) describe('organization chat', () => { - it('exposes only the three organization Search tools', () => { + it('exposes the organization Search tools and the chat history of the caller', () => { create() - expect([...mocks.tools.keys()]).toEqual(['search', 'read_document', 'chat']) + expect([...mocks.tools.keys()]).toEqual([ + 'search', + 'read_document', + 'chat', + 'list_my_chat_history', + ]) + }) + it('offers no chat history to a workspace API key, which acts for no person', () => { + createKnowledgeMcpServer({ + organizationId: 'org-1', + request, + auth: { ...auth, principal: createWorkspaceApiKeyPrincipal(), keyType: 'workspace' }, + }) + expect(mocks.tools.has('list_my_chat_history')).toBe(false) }) it('does not run when rate limited', async () => { create() diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 1dccc6a7fb7..98b42786c8f 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -18,6 +18,7 @@ import { recordOrganizationSearchMcpActivity, type SearchMcpActivityInput, } from '@/lib/knowledge/mcp/activity' +import { registerListMyChatHistoryTool } from '@/lib/knowledge/mcp/chat-history' import { callerErrorMessage, readOrganizationDocuments, @@ -202,6 +203,9 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe if (context.searchPeople) registerSearchPeopleTool(server, { execute, principal, organizationId, request }) + /** Only a person has a chat history; a workspace API key acts for no one. */ + if (resolvePrincipalSubjectUserId(principal)) + registerListMyChatHistoryTool(server, { execute, principal, organizationId }) return server } diff --git a/apps/sim/lib/knowledge/mcp/tool-arguments.ts b/apps/sim/lib/knowledge/mcp/tool-arguments.ts index 8a7f50c62a1..c2f740b13bc 100644 --- a/apps/sim/lib/knowledge/mcp/tool-arguments.ts +++ b/apps/sim/lib/knowledge/mcp/tool-arguments.ts @@ -7,6 +7,7 @@ import { } from '@/lib/api/contracts/knowledge/mcp' import { mcpToolCallParamsSchema } from '@/lib/api/contracts/mcp' import { + listMyChatHistoryInputSchema, liveSearchProviderSchema, searchPeopleInputSchema, } from '@/lib/api/contracts/mothership-assistant-tools' @@ -27,6 +28,7 @@ const TOOL_INPUT_SCHEMAS = new Map([ ['read_document', readLiveDocumentMcpSchema], ['chat', chatSearchMcpSchema], ['search_people', searchPeopleInputSchema], + ['list_my_chat_history', listMyChatHistoryInputSchema], ]) function readToolCall(message: Record) { diff --git a/apps/sim/lib/mothership/application/execute-chat-history-use-case.ts b/apps/sim/lib/mothership/application/execute-chat-history-use-case.ts new file mode 100644 index 00000000000..99278a20732 --- /dev/null +++ b/apps/sim/lib/mothership/application/execute-chat-history-use-case.ts @@ -0,0 +1,39 @@ +import type { ListMyChatHistoryInput } from '@/lib/api/contracts/mothership-assistant-tools' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { listMyChatHistory } from '@/lib/knowledge/application/chat-history' +import { + COPILOT_APPLICATION_DELEGATION_TTL_MS, + type CopilotExecutionContext, + createTrustedOrganizationCopilotPrincipal, + requireTrustedOrganizationCopilotContext, +} from '@/lib/mothership/auth/application-delegation' +import { authorizeOrganizationChatDelegation } from '@/lib/mothership/chat/organization-chats' + +/** + * Lists the conversation owner's own questions for the organization Assistant. The person and + * organization come from the trusted turn and the delegation is bound to the member's private + * chat, so a model argument can never name another member's history. + */ +export async function executeCopilotChatHistoryRead( + context: CopilotExecutionContext | undefined, + input: ListMyChatHistoryInput +) { + const trusted = requireTrustedOrganizationCopilotContext(context) + if (context?.requestMode !== 'assistant') + throw new OrchestrationError( + 'forbidden', + 'Chat history is available only in organization Assistant conversations' + ) + const principal = createTrustedOrganizationCopilotPrincipal( + { ...trusted, delegationId: trusted.toolCallId }, + { + audience: listMyChatHistory.operation.delegationAudience, + ttlMs: COPILOT_APPLICATION_DELEGATION_TTL_MS, + } + ) + await authorizeOrganizationChatDelegation.execute({ principal }) + return listMyChatHistory.execute({ + principal, + input: { ...input, organizationId: trusted.organizationId }, + }) +} diff --git a/apps/sim/lib/mothership/assistant/tool-policy.ts b/apps/sim/lib/mothership/assistant/tool-policy.ts index e04059e1888..675d1417191 100644 --- a/apps/sim/lib/mothership/assistant/tool-policy.ts +++ b/apps/sim/lib/mothership/assistant/tool-policy.ts @@ -6,6 +6,7 @@ export const ASSISTANT_TOOLS = new Set([ 'search_workspace', 'read_document', 'search_people', + 'list_my_chat_history', 'oauth_get_auth_link', 'run_function', ]) diff --git a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts index dc17ad3c564..3b6fea88b16 100644 --- a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts @@ -11,6 +11,7 @@ export interface ToolCatalogEntry { | 'Discover and configure organization Search sources. list/get return accessible sources and indexing status; providers returns available integration approvals; approve changes a provider approval when authorized; setup returns the existing connection UI for the user to complete. Put the returned setupUrl in a clickable Markdown link at the end of the reply. Setup does not mean connected or indexed. Use search_workspace and read_document to retrieve source content.' | 'List accessible Projects within this conversation, with visible environments and current capabilities. Follow nextCursor for more results; discovery does not grant file write access.' | 'List currently accessible workspaces with roles and explicit capability restrictions. Bulk results report copilotAllowed and deniedCapabilities; exact workspaceId returns the full capability map. Omitted restrictions never authorize an operation.' + | 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.' | 'Look up people in this organization’s directory by name, email, title, department, or location. Returns each person’s title, department, location, email, and manager. When exactly one person matches, or with a personId, returns that person with managerChain (direct manager first) and directReports. Covers only this organization’s people; use search_workspace for customers, vendors, and other outside contacts.' | 'Publish and edit the selected workspace’s changelog. publish takes a title, a markdown body, the changes (one line each, with the workflowId, deploymentVersionId, and chatId they came from when known), and bump: major, minor, or patch for how significant the release is, with a one-line bumpReason. The server computes the version from the workspace’s highest one; never write a version number on publish. It returns the release with its revision and changelog/.md, the body file: edit the body there with the file tools, for example to add impact charts once there is data. update changes the title, bumpReason, version label, or the whole change list, and requires expectedRevision from get, list, or publish so a concurrent edit is never overwritten. A deployment ships in one release: a deploymentVersionId already in another release is rejected. list pages newest first; get returns one release with its revision and its changelog/.md path.' | 'Read and manage account, organization, and workspace settings. list finds sections; get returns current values, updateSchema and operation names; describe returns one operation’s exact input schema; update changes narrow preferences; execute performs a listed operation; open returns the existing user setup flow. When user setup is needed, put the returned setupUrl in a clickable Markdown link at the end of the reply. Workspace resources retain their CLI commands. Account is the acting user; organization is the conversation’s organization. Every operation checks current permissions and entitlements.' @@ -89,6 +90,7 @@ export interface ToolCatalogEntry { | 'knowledge' | 'list_deployment_versions' | 'list_integration_tools' + | 'list_my_chat_history' | 'list_user_projects' | 'list_workspace_mcp_servers' | 'list_workspaces' @@ -7792,6 +7794,54 @@ export const SearchPeople: ToolCatalogEntry = { }, } +export const ListMyChatHistory: ToolCatalogEntry = { + id: 'list_my_chat_history', + description: + 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.', + route: 'sim', + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + startDate: { + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + description: + 'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.', + }, + endDate: { + description: + 'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.', + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + }, + topK: { + description: 'Questions per page, 50 by default.', + type: 'integer', + minimum: 1, + maximum: 100, + }, + cursor: { + description: 'nextCursor from the previous page of the same window.', + type: 'string', + minLength: 1, + maxLength: 1024, + }, + includeAnswers: { + description: + "Adds the start of Sim's answer to each question. Answers reflect the sources as they were when asked.", + type: 'boolean', + }, + }, + required: ['startDate'], + additionalProperties: false, + }, +} + export const Dashboards: ToolCatalogEntry = { id: 'dashboards', description: @@ -8802,6 +8852,7 @@ export const TOOL_CATALOG: Record = { [ListUserProjects.id]: ListUserProjects, [ListWorkspaces.id]: ListWorkspaces, [SearchPeople.id]: SearchPeople, + [ListMyChatHistory.id]: ListMyChatHistory, [Dashboards.id]: Dashboards, [Tests.id]: Tests, [Changelog.id]: Changelog, diff --git a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts index 2c5250f21e4..ac9f13088cf 100644 --- a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts @@ -7872,6 +7872,50 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, + list_my_chat_history: { + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + startDate: { + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + description: + 'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.', + }, + endDate: { + description: + 'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.', + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + }, + topK: { + description: 'Questions per page, 50 by default.', + type: 'integer', + minimum: 1, + maximum: 100, + }, + cursor: { + description: 'nextCursor from the previous page of the same window.', + type: 'string', + minLength: 1, + maxLength: 1024, + }, + includeAnswers: { + description: + "Adds the start of Sim's answer to each question. Answers reflect the sources as they were when asked.", + type: 'boolean', + }, + }, + required: ['startDate'], + additionalProperties: false, + }, + resultSchema: undefined, + }, dashboards: { parameters: { $schema: 'http://json-schema.org/draft-07/schema#', diff --git a/apps/sim/lib/mothership/tools/server/knowledge/chat-history.ts b/apps/sim/lib/mothership/tools/server/knowledge/chat-history.ts new file mode 100644 index 00000000000..1a2635cec38 --- /dev/null +++ b/apps/sim/lib/mothership/tools/server/knowledge/chat-history.ts @@ -0,0 +1,40 @@ +import { createLogger } from '@sim/logger' +import { z } from 'zod' +import { listMyChatHistoryInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' +import { getValidationErrorMessage } from '@/lib/api/server/validation' +import { messageForCopilotApplicationError } from '@/lib/mothership/application/errors' +import { executeCopilotChatHistoryRead } from '@/lib/mothership/application/execute-chat-history-use-case' +import type { BaseServerTool, ServerToolContext } from '@/lib/mothership/tools/server/base-tool' + +const logger = createLogger('ListMyChatHistoryTool') + +/** `list_my_chat_history` for the organization Assistant: the Search MCP tool of that name. */ +export const listMyChatHistoryServerTool: BaseServerTool = { + name: 'list_my_chat_history', + inputSchema: listMyChatHistoryInputSchema, + async execute(raw, context?: ServerToolContext) { + if (!context?.organizationId) + return { + success: false, + message: 'Chat history is available only in organization conversations.', + } + try { + const data = await executeCopilotChatHistoryRead( + context, + listMyChatHistoryInputSchema.parse(raw) + ) + return { success: true, data } + } catch (error) { + if (error instanceof z.ZodError) + return { + success: false, + message: getValidationErrorMessage(error, 'Invalid chat history arguments'), + } + logger.error('Chat history lookup failed', { error }) + return { + success: false, + message: messageForCopilotApplicationError(error, 'Chat history lookup failed'), + } + } + }, +} diff --git a/apps/sim/lib/mothership/tools/server/router.ts b/apps/sim/lib/mothership/tools/server/router.ts index dadf6835809..c62322249ab 100644 --- a/apps/sim/lib/mothership/tools/server/router.ts +++ b/apps/sim/lib/mothership/tools/server/router.ts @@ -25,6 +25,7 @@ import { editContentServerTool } from '@/lib/mothership/tools/server/files/edit- import { workspaceFileServerTool } from '@/lib/mothership/tools/server/files/workspace-file' import { validateGeneratedToolPayload } from '@/lib/mothership/tools/server/generated-schema' import { generateImageServerTool } from '@/lib/mothership/tools/server/image/generate-image' +import { listMyChatHistoryServerTool } from '@/lib/mothership/tools/server/knowledge/chat-history' import { searchPeopleServerTool } from '@/lib/mothership/tools/server/knowledge/people' import { readDocumentServerTool, @@ -81,6 +82,7 @@ const baseServerToolRegistry: Record = { [openResourceServerTool.name]: openResourceServerTool, [readDocumentServerTool.name]: readDocumentServerTool, [searchPeopleServerTool.name]: searchPeopleServerTool, + [listMyChatHistoryServerTool.name]: listMyChatHistoryServerTool, // The streamed file-writing pair: prepare opens the write (live preview), // apply continues it. The preview machinery keys off these exact names. [workspaceFileServerTool.name]: withFileTabFlag(workspaceFileServerTool), From cf2be831068d7f916e1aff6391bb914d9149d5af Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:14:54 -0800 Subject: [PATCH 02/10] =?UTF-8?q?improvement(search):=20chat=20history=20r?= =?UTF-8?q?eview=20pass=20=E2=80=94=20chats=20first,=20bounded=20answers,?= =?UTF-8?q?=20precise=20cursor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../application/chat-history.integration.ts | 46 +++++- .../lib/knowledge/application/chat-history.ts | 144 ++++++++++-------- apps/sim/lib/knowledge/mcp/server.ts | 2 +- 3 files changed, 127 insertions(+), 65 deletions(-) diff --git a/apps/sim/lib/knowledge/application/chat-history.integration.ts b/apps/sim/lib/knowledge/application/chat-history.integration.ts index 7ca5c024ce3..c92098699ce 100644 --- a/apps/sim/lib/knowledge/application/chat-history.integration.ts +++ b/apps/sim/lib/knowledge/application/chat-history.integration.ts @@ -18,6 +18,8 @@ import { import { generateId } from '@sim/utils/id' import { inArray } from 'drizzle-orm' import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { OrganizationMembershipNotFoundError } from '@/lib/core/application/organization-authorization' +import { PrincipalKindAuthorizationError } from '@/lib/core/application/workspace-authorization' import { listMyChatHistory } from '@/lib/knowledge/application/chat-history' const organizationId = generateId() @@ -175,7 +177,7 @@ describe('list_my_chat_history', () => { ['third', 'agent', '2026-11-03T08:00:00.000Z'], ]) expect(questions[1]?.conversationUrl).toMatch( - new RegExp(`/o/${organizationId}/chat/${assistant}$`) + new RegExp(`/o/${organizationId}/search/chat/${assistant}$`) ) expect(nextCursor).toBeUndefined() }) @@ -267,14 +269,50 @@ describe('list_my_chat_history', () => { const withAnswers = (await list({ includeAnswers: true })).questions[0] expect(withAnswers?.answerExcerpt?.startsWith('Two releases shipped . x')).toBe(true) - expect(withAnswers?.answerExcerpt?.length).toBeLessThanOrEqual(603) + expect(withAnswers?.answerExcerpt?.length).toBeLessThan(700) expect((await list()).questions[0]?.answerExcerpt).toBeUndefined() }) + it("gives an unanswered question no answer, rather than the next question's", async () => { + const id = await chat() + await ask(id, 'stopped question', '2026-11-02T10:00:00Z') + await ask(id, 'answered question', '2026-11-02T10:01:00Z') + await db.insert(copilotMessages).values({ + chatId: id, + messageId: generateId(), + role: 'assistant', + content: { content: 'The answer to the second question' }, + createdAt: new Date('2026-11-02T10:01:30Z'), + }) + + const { questions } = await list({ includeAnswers: true }) + expect(questions.map((q) => [q.question, q.answerExcerpt])).toEqual([ + ['stopped question', undefined], + ['answered question', 'The answer to the second question'], + ]) + }) + + it('reads bounds in their own offset and runs to now without an endDate', async () => { + const id = await chat() + await ask(id, 'late on the 1st in Los Angeles', '2026-11-02T07:30:00Z') + await ask(id, 'recent', new Date(Date.now() - 60_000).toISOString()) + + const losAngeles = await list({ + startDate: '2026-11-01T00:00:00-08:00', + endDate: '2026-11-02T00:00:00-08:00', + }) + expect(losAngeles.questions.map((q) => q.question)).toEqual(['late on the 1st in Los Angeles']) + const sinceYesterday = await list({ + startDate: new Date(Date.now() - 86_400_000).toISOString(), + endDate: undefined, + }) + expect(sinceYesterday.questions.map((q) => q.question)).toEqual(['recent']) + }) + it('refuses a caller outside the organization and a principal that is not a person', async () => { await ask(await chat(), 'private', '2026-11-02T10:00:00Z') - await expect(list({}, outsiderId)).rejects.toThrow() + await expect(list({}, outsiderId)).rejects.toBeInstanceOf(OrganizationMembershipNotFoundError) const workspaceKey: WorkspaceApiKeyPrincipal = { kind: 'workspace_api_key', workspaceId: openWorkspaceId, @@ -286,6 +324,6 @@ describe('list_my_chat_history', () => { principal: workspaceKey, input: { ...WINDOW, organizationId }, }) - ).rejects.toThrow() + ).rejects.toBeInstanceOf(PrincipalKindAuthorizationError) }) }) diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts index 33b61127246..9a9500a7d87 100644 --- a/apps/sim/lib/knowledge/application/chat-history.ts +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -2,8 +2,10 @@ import { requirePrincipalSubjectUserId } from '@sim/auth/principal' import { db } from '@sim/db' import { copilotChats, copilotMessages } from '@sim/db/schema' import { truncate } from '@sim/utils/string' -import { and, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm' +import { and, eq, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm' +import { z } from 'zod' import type { ListMyChatHistoryInput } from '@/lib/api/contracts/mothership-assistant-tools' +import { classifyTimestampCursor, preciseTimestampText } from '@/lib/api/list-query' import { defineAuthorizedOrganizationUseCase } from '@/lib/core/application/authorized-organization-use-case' import { OrchestrationError } from '@/lib/core/orchestration/types' import { getBaseUrl } from '@/lib/core/utils/urls' @@ -19,9 +21,9 @@ const DEFAULT_TOP_K = 50 const QUESTION_MAX_CHARS = 2_000 const ANSWER_EXCERPT_MAX_CHARS = 600 -export type ChatHistorySurface = 'assistant' | 'agent' | 'slack' +type ChatHistorySurface = 'assistant' | 'agent' | 'slack' -export interface ChatHistoryQuestion { +interface ChatHistoryQuestion { /** When the question was asked, as an ISO datetime in UTC. */ timestamp: string question: string @@ -32,39 +34,32 @@ export interface ChatHistoryQuestion { answerExcerpt?: string } -export interface ChatHistoryPage { +interface ChatHistoryPage { questions: ChatHistoryQuestion[] nextCursor?: string } -type ListMyChatHistoryUseCaseInput = ListMyChatHistoryInput & { organizationId: string } +/** A position in the caller's questions: the stored time at full precision and the message id. */ +const cursorSchema = z.tuple([ + z.string().refine((value) => classifyTimestampCursor(value) === 'precise'), + z.string().uuid(), +]) -/** A position in the caller's questions: the exact stored time and message id of the last row. */ function encodeCursor(createdAt: string, id: string): string { return Buffer.from(JSON.stringify([createdAt, id])).toString('base64url') } function decodeCursor(cursor: string): [string, string] { try { - const decoded: unknown = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) - if ( - Array.isArray(decoded) && - decoded.length === 2 && - typeof decoded[0] === 'string' && - !Number.isNaN(Date.parse(`${decoded[0]}Z`)) && - typeof decoded[1] === 'string' && - /^[0-9a-f-]{36}$/i.test(decoded[1]) - ) - return [decoded[0], decoded[1]] + const parsed = cursorSchema.safeParse(JSON.parse(Buffer.from(cursor, 'base64url').toString())) + if (parsed.success) return parsed.data } catch {} throw new OrchestrationError('validation', 'cursor is not a nextCursor from this tool') } -function resolveWindow(input: ListMyChatHistoryUseCaseInput): { from: Date; to: Date } { +function resolveWindow(input: ListMyChatHistoryInput): { from: Date; to: Date } { const from = new Date(input.startDate) const to = input.endDate ? new Date(input.endDate) : new Date() - if (Number.isNaN(from.getTime()) || Number.isNaN(to.getTime())) - throw new OrchestrationError('validation', 'startDate and endDate must be ISO datetimes') if (to <= from) throw new OrchestrationError('validation', 'endDate must be after startDate') if (to.getTime() - from.getTime() > MAX_WINDOW_DAYS * DAY_MS) throw new OrchestrationError( @@ -93,30 +88,61 @@ function answerExcerpt(content: string | null): string | undefined { */ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ operation: listMyChatHistoryOperation, - async execute({ principal, input }): Promise { + async execute({ principal, input, context }): Promise { const userId = requirePrincipalSubjectUserId(principal) - const { organizationId } = input + const { organizationId } = context const { from, to } = resolveWindow(input) const topK = input.topK ?? DEFAULT_TOP_K const after = input.cursor ? decodeCursor(input.cursor) : undefined - const workspaceIds = (await listAccessibleWorkspaceRowsForUser(userId, 'active')) + const workspaceIds = ( + await listAccessibleWorkspaceRowsForUser(userId, 'active', organizationId) + ) .filter(({ workspace }) => workspace.organizationId === organizationId) .map(({ workspace }) => workspace.id) - const owned: SQL | undefined = workspaceIds.length - ? or( - eq(copilotChats.organizationId, organizationId), - inArray(copilotChats.workspaceId, workspaceIds) + /** The caller's chats first: few per person, so the message read probes each chat's index. */ + const chats = await db + .select({ + id: copilotChats.id, + workspaceId: copilotChats.workspaceId, + slack: sql`coalesce(${copilotChats.externalConversationKey} LIKE 'slack:%', false)`, + mode: conversationModeSelection, + }) + .from(copilotChats) + .where( + and( + eq(copilotChats.userId, userId), + eq(copilotChats.type, 'mothership'), + workspaceIds.length + ? or( + eq(copilotChats.organizationId, organizationId), + inArray(copilotChats.workspaceId, workspaceIds) + ) + : eq(copilotChats.organizationId, organizationId), + isNull(copilotChats.deletedAt), + sql`${copilotChats.config}->'benchmark' IS NULL` ) - : eq(copilotChats.organizationId, organizationId) + ) + if (!chats.length) return { questions: [] } + const chatById = new Map(chats.map((chat) => [chat.id, chat])) + /** + * The first reply to this question, never one that answers a later question in the chat. The + * outer row is named in full: a single-table select leaves its own columns unqualified, which + * inside these subqueries would resolve to the inner rows. + */ const answer = input.includeAnswers ? sql`( SELECT coalesce(a.display_content, a.content)->>'content' FROM ${copilotMessages} a - WHERE a.chat_id = ${copilotMessages.chatId} AND a.role = 'assistant' + WHERE a.chat_id = copilot_messages.chat_id AND a.role = 'assistant' AND a.deleted_at IS NULL - AND (a.created_at, a.id) > (${copilotMessages.createdAt}, ${copilotMessages.id}) + AND (a.created_at, a.id) > (copilot_messages.created_at, copilot_messages.id) + AND NOT EXISTS ( + SELECT 1 FROM ${copilotMessages} u + WHERE u.chat_id = a.chat_id AND u.role = 'user' AND u.deleted_at IS NULL + AND (u.created_at, u.id) > (copilot_messages.created_at, copilot_messages.id) + AND (u.created_at, u.id) < (a.created_at, a.id)) ORDER BY a.created_at, a.id LIMIT 1)` : sql`NULL` @@ -125,57 +151,55 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ .select({ id: copilotMessages.id, chatId: copilotMessages.chatId, - createdAt: sql`${copilotMessages.createdAt}::text`, + createdAt: preciseTimestampText(copilotMessages.createdAt), question: sql`${copilotMessages.content}->>'content'`, answer, - workspaceId: copilotChats.workspaceId, - slack: sql`coalesce(${copilotChats.externalConversationKey} LIKE 'slack:%', false)`, - mode: conversationModeSelection, }) .from(copilotMessages) - .innerJoin(copilotChats, eq(copilotChats.id, copilotMessages.chatId)) .where( and( - eq(copilotChats.userId, userId), - eq(copilotChats.type, 'mothership'), - owned, - isNull(copilotChats.deletedAt), - sql`${copilotChats.config}->'benchmark' IS NULL`, + inArray(copilotMessages.chatId, [...chatById.keys()]), eq(copilotMessages.role, 'user'), isNull(copilotMessages.deletedAt), sql`${copilotMessages.content}->>'origin' IS NULL`, - sql`${copilotMessages.createdAt} >= (${from.toISOString()}::timestamptz AT TIME ZONE 'UTC')`, - sql`${copilotMessages.createdAt} < (${to.toISOString()}::timestamptz AT TIME ZONE 'UTC')`, + gte(copilotMessages.createdAt, from), + lt(copilotMessages.createdAt, to), after - ? sql`(${copilotMessages.createdAt}, ${copilotMessages.id}) > (${after[0]}::timestamp, ${after[1]}::uuid)` + ? sql`(${copilotMessages.createdAt}, ${copilotMessages.id}) > (cast(${after[0]} as timestamp), ${after[1]}::uuid)` : undefined ) ) .orderBy(copilotMessages.createdAt, copilotMessages.id) .limit(topK + 1) + const routes = organizationRoutes(organizationId) const page = rows.slice(0, topK) const last = page[page.length - 1] return { - questions: page.map((row) => { + questions: page.flatMap((row) => { + const chat = chatById.get(row.chatId) + if (!chat) return [] + const surface: ChatHistorySurface = chat.slack + ? 'slack' + : chat.workspaceId || chat.mode !== 'assistant' + ? 'agent' + : 'assistant' + const path = chat.workspaceId + ? `/workspace/${chat.workspaceId}/chat/${chat.id}` + : surface === 'assistant' + ? routes.searchChat(chat.id) + : routes.chat(chat.id) const excerpt = answerExcerpt(row.answer) - return { - timestamp: new Date(`${row.createdAt.replace(' ', 'T')}Z`).toISOString(), - question: truncate(row.question ?? '', QUESTION_MAX_CHARS), - chatId: row.chatId, - conversationUrl: new URL( - row.workspaceId - ? `/workspace/${row.workspaceId}/chat/${row.chatId}` - : organizationRoutes(organizationId).chat(row.chatId), - getBaseUrl() - ).href, - surface: row.slack - ? 'slack' - : row.workspaceId || row.mode !== 'assistant' - ? 'agent' - : 'assistant', - ...(excerpt ? { answerExcerpt: excerpt } : {}), - } + return [ + { + timestamp: new Date(row.createdAt).toISOString(), + question: truncate(row.question ?? '', QUESTION_MAX_CHARS), + chatId: chat.id, + conversationUrl: new URL(path, getBaseUrl()).href, + surface, + ...(excerpt ? { answerExcerpt: excerpt } : {}), + }, + ] }), ...(rows.length > topK && last ? { nextCursor: encodeCursor(last.createdAt, last.id) } : {}), } diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 98b42786c8f..319dfbbbb55 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -203,7 +203,7 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe if (context.searchPeople) registerSearchPeopleTool(server, { execute, principal, organizationId, request }) - /** Only a person has a chat history; a workspace API key acts for no one. */ + // Only a person has a chat history; a workspace API key acts for no one. if (resolvePrincipalSubjectUserId(principal)) registerListMyChatHistoryTool(server, { execute, principal, organizationId }) From e6fd43432a63c9a84ecbf911c37b55b64873de94 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:25:17 -0800 Subject: [PATCH 03/10] fix(search): type the chat history use case input --- apps/sim/lib/knowledge/application/chat-history.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts index 9a9500a7d87..4b7f36366fb 100644 --- a/apps/sim/lib/knowledge/application/chat-history.ts +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -6,7 +6,10 @@ import { and, eq, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm' import { z } from 'zod' import type { ListMyChatHistoryInput } from '@/lib/api/contracts/mothership-assistant-tools' import { classifyTimestampCursor, preciseTimestampText } from '@/lib/api/list-query' -import { defineAuthorizedOrganizationUseCase } from '@/lib/core/application/authorized-organization-use-case' +import { + defineAuthorizedOrganizationUseCase, + type OrganizationUseCaseContext, +} from '@/lib/core/application/authorized-organization-use-case' import { OrchestrationError } from '@/lib/core/orchestration/types' import { getBaseUrl } from '@/lib/core/utils/urls' import { stripInteractiveCards } from '@/lib/knowledge/application/chat-citations' @@ -88,7 +91,13 @@ function answerExcerpt(content: string | null): string | undefined { */ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ operation: listMyChatHistoryOperation, - async execute({ principal, input, context }): Promise { + async execute({ + principal, + input, + context, + }: OrganizationUseCaseContext< + ListMyChatHistoryInput & { organizationId: string } + >): Promise { const userId = requirePrincipalSubjectUserId(principal) const { organizationId } = context const { from, to } = resolveWindow(input) From 384835899b417132ea3ebebc6796dc657c27c6dd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:40:07 -0800 Subject: [PATCH 04/10] fix(search): match replies in transcript order and gate chat history on Search availability --- .../application/chat-history.integration.ts | 30 +++++++++++++++++++ .../lib/knowledge/application/chat-history.ts | 22 +++++++++----- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/apps/sim/lib/knowledge/application/chat-history.integration.ts b/apps/sim/lib/knowledge/application/chat-history.integration.ts index c92098699ce..697ee36558f 100644 --- a/apps/sim/lib/knowledge/application/chat-history.integration.ts +++ b/apps/sim/lib/knowledge/application/chat-history.integration.ts @@ -292,6 +292,36 @@ describe('list_my_chat_history', () => { ]) }) + it("finds a reply that shares its question's timestamp, in transcript order", async () => { + const id = await chat() + const at = new Date('2026-11-02T10:00:00Z') + await db.insert(copilotMessages).values([ + { + id: 'ffffffff-ffff-4fff-bfff-ffffffffffff', + chatId: id, + messageId: generateId(), + role: 'user', + content: { content: 'same instant' }, + seq: 1, + createdAt: at, + }, + { + id: '00000000-0000-4000-8000-000000000000', + chatId: id, + messageId: generateId(), + role: 'assistant', + content: { content: 'Saved reply' }, + seq: 2, + createdAt: at, + }, + ]) + + const { questions } = await list({ includeAnswers: true }) + expect(questions.map((q) => [q.question, q.answerExcerpt])).toEqual([ + ['same instant', 'Saved reply'], + ]) + }) + it('reads bounds in their own offset and runs to now without an endDate', async () => { const id = await chat() await ask(id, 'late on the 1st in Los Angeles', '2026-11-02T07:30:00Z') diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts index 4b7f36366fb..eadb554a34a 100644 --- a/apps/sim/lib/knowledge/application/chat-history.ts +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -12,6 +12,7 @@ import { } from '@/lib/core/application/authorized-organization-use-case' import { OrchestrationError } from '@/lib/core/orchestration/types' import { getBaseUrl } from '@/lib/core/utils/urls' +import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability' import { stripInteractiveCards } from '@/lib/knowledge/application/chat-citations' import { listMyChatHistoryOperation } from '@/lib/knowledge/application/chat-operations' import { conversationModeSelection } from '@/lib/mothership/chat/intent' @@ -23,6 +24,8 @@ const MAX_WINDOW_DAYS = 92 const DEFAULT_TOP_K = 50 const QUESTION_MAX_CHARS = 2_000 const ANSWER_EXCERPT_MAX_CHARS = 600 +/** Orders a message without a transcript `seq` after every numbered one, as transcripts read. */ +const LAST_SEQ = sql.raw('2147483647') type ChatHistorySurface = 'assistant' | 'agent' | 'slack' @@ -100,6 +103,7 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ >): Promise { const userId = requirePrincipalSubjectUserId(principal) const { organizationId } = context + await requireOrganizationSearchAvailable(organizationId) const { from, to } = resolveWindow(input) const topK = input.topK ?? DEFAULT_TOP_K const after = input.cursor ? decodeCursor(input.cursor) : undefined @@ -136,9 +140,10 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ const chatById = new Map(chats.map((chat) => [chat.id, chat])) /** - * The first reply to this question, never one that answers a later question in the chat. The - * outer row is named in full: a single-table select leaves its own columns unqualified, which - * inside these subqueries would resolve to the inner rows. + * The first reply to this question, never one that answers a later question in the chat, in + * transcript order (`seq`, then time and id): a turn's question and reply can share a + * timestamp. The outer row is named in full: a single-table select leaves its own columns + * unqualified, which inside these subqueries would resolve to the inner rows. */ const answer = input.includeAnswers ? sql`( @@ -146,13 +151,16 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ FROM ${copilotMessages} a WHERE a.chat_id = copilot_messages.chat_id AND a.role = 'assistant' AND a.deleted_at IS NULL - AND (a.created_at, a.id) > (copilot_messages.created_at, copilot_messages.id) + AND (coalesce(a.seq, ${LAST_SEQ}), a.created_at, a.id) + > (coalesce(copilot_messages.seq, ${LAST_SEQ}), copilot_messages.created_at, copilot_messages.id) AND NOT EXISTS ( SELECT 1 FROM ${copilotMessages} u WHERE u.chat_id = a.chat_id AND u.role = 'user' AND u.deleted_at IS NULL - AND (u.created_at, u.id) > (copilot_messages.created_at, copilot_messages.id) - AND (u.created_at, u.id) < (a.created_at, a.id)) - ORDER BY a.created_at, a.id + AND (coalesce(u.seq, ${LAST_SEQ}), u.created_at, u.id) + > (coalesce(copilot_messages.seq, ${LAST_SEQ}), copilot_messages.created_at, copilot_messages.id) + AND (coalesce(u.seq, ${LAST_SEQ}), u.created_at, u.id) + < (coalesce(a.seq, ${LAST_SEQ}), a.created_at, a.id)) + ORDER BY a.seq ASC NULLS LAST, a.created_at, a.id LIMIT 1)` : sql`NULL` From b44c0d876787dab556a0ebd399383bce3f3ed865 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:45:07 -0800 Subject: [PATCH 05/10] fix(search): truncate chat history text at code points --- apps/sim/lib/knowledge/application/chat-history.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts index eadb554a34a..29f737e1667 100644 --- a/apps/sim/lib/knowledge/application/chat-history.ts +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -1,7 +1,7 @@ import { requirePrincipalSubjectUserId } from '@sim/auth/principal' import { db } from '@sim/db' import { copilotChats, copilotMessages } from '@sim/db/schema' -import { truncate } from '@sim/utils/string' +import { truncateAtCodePoint } from '@sim/utils/string' import { and, eq, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm' import { z } from 'zod' import type { ListMyChatHistoryInput } from '@/lib/api/contracts/mothership-assistant-tools' From 7baa6593eabbd92e18e469a45a64d847edb33cb2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:45:28 -0800 Subject: [PATCH 06/10] fix(search): finish the code-point truncation change --- apps/sim/lib/knowledge/application/chat-history.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts index 29f737e1667..397fc177500 100644 --- a/apps/sim/lib/knowledge/application/chat-history.ts +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -82,7 +82,7 @@ function answerExcerpt(content: string | null): string | undefined { .replace(/[\s\S]*?<\/source>/g, '') .replace(/\s+/g, ' ') .trim() - return text ? truncate(text, ANSWER_EXCERPT_MAX_CHARS) : undefined + return text ? truncateAtCodePoint(text, ANSWER_EXCERPT_MAX_CHARS) : undefined } /** @@ -210,7 +210,7 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ return [ { timestamp: new Date(row.createdAt).toISOString(), - question: truncate(row.question ?? '', QUESTION_MAX_CHARS), + question: truncateAtCodePoint(row.question ?? '', QUESTION_MAX_CHARS), chatId: chat.id, conversationUrl: new URL(path, getBaseUrl()).href, surface, From f9e6a612d880c3836a144387eae08dc3635a7b87 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:56:57 -0800 Subject: [PATCH 07/10] fix(search): deleted questions still end their turn; clamp a future endDate to now --- .../application/chat-history.integration.ts | 13 +++++++++++++ apps/sim/lib/knowledge/application/chat-history.ts | 9 ++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/knowledge/application/chat-history.integration.ts b/apps/sim/lib/knowledge/application/chat-history.integration.ts index 697ee36558f..f18421b329e 100644 --- a/apps/sim/lib/knowledge/application/chat-history.integration.ts +++ b/apps/sim/lib/knowledge/application/chat-history.integration.ts @@ -276,6 +276,14 @@ describe('list_my_chat_history', () => { it("gives an unanswered question no answer, rather than the next question's", async () => { const id = await chat() await ask(id, 'stopped question', '2026-11-02T10:00:00Z') + await ask(id, 'deleted question', '2026-11-02T10:00:20Z', { deletedAt: new Date() }) + await db.insert(copilotMessages).values({ + chatId: id, + messageId: generateId(), + role: 'assistant', + content: { content: 'The answer to the deleted question' }, + createdAt: new Date('2026-11-02T10:00:30Z'), + }) await ask(id, 'answered question', '2026-11-02T10:01:00Z') await db.insert(copilotMessages).values({ chatId: id, @@ -337,6 +345,11 @@ describe('list_my_chat_history', () => { endDate: undefined, }) expect(sinceYesterday.questions.map((q) => q.question)).toEqual(['recent']) + const futureEnd = await list({ + startDate: new Date(Date.now() - 91 * 86_400_000).toISOString(), + endDate: new Date(Date.now() + 30 * 86_400_000).toISOString(), + }) + expect(futureEnd.questions.map((q) => q.question)).toEqual(['recent']) }) it('refuses a caller outside the organization and a principal that is not a person', async () => { diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts index 397fc177500..89de5d0140c 100644 --- a/apps/sim/lib/knowledge/application/chat-history.ts +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -65,7 +65,9 @@ function decodeCursor(cursor: string): [string, string] { function resolveWindow(input: ListMyChatHistoryInput): { from: Date; to: Date } { const from = new Date(input.startDate) - const to = input.endDate ? new Date(input.endDate) : new Date() + const now = new Date() + /** Nothing was asked after now, so a later end only widens the read. */ + const to = input.endDate && new Date(input.endDate) < now ? new Date(input.endDate) : now if (to <= from) throw new OrchestrationError('validation', 'endDate must be after startDate') if (to.getTime() - from.getTime() > MAX_WINDOW_DAYS * DAY_MS) throw new OrchestrationError( @@ -140,7 +142,8 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ const chatById = new Map(chats.map((chat) => [chat.id, chat])) /** - * The first reply to this question, never one that answers a later question in the chat, in + * The first reply to this question, never one that answers a later question in the chat (a + * deleted question still ends its turn), in * transcript order (`seq`, then time and id): a turn's question and reply can share a * timestamp. The outer row is named in full: a single-table select leaves its own columns * unqualified, which inside these subqueries would resolve to the inner rows. @@ -155,7 +158,7 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ > (coalesce(copilot_messages.seq, ${LAST_SEQ}), copilot_messages.created_at, copilot_messages.id) AND NOT EXISTS ( SELECT 1 FROM ${copilotMessages} u - WHERE u.chat_id = a.chat_id AND u.role = 'user' AND u.deleted_at IS NULL + WHERE u.chat_id = a.chat_id AND u.role = 'user' AND (coalesce(u.seq, ${LAST_SEQ}), u.created_at, u.id) > (coalesce(copilot_messages.seq, ${LAST_SEQ}), copilot_messages.created_at, copilot_messages.id) AND (coalesce(u.seq, ${LAST_SEQ}), u.created_at, u.id) From 42548c78d61074bd9651d6b62cfd0eebddd8036a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:57:27 -0800 Subject: [PATCH 08/10] test(search): future-end assertion independent of other fixture rows --- apps/sim/lib/knowledge/application/chat-history.integration.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/sim/lib/knowledge/application/chat-history.integration.ts b/apps/sim/lib/knowledge/application/chat-history.integration.ts index f18421b329e..7e51908efbf 100644 --- a/apps/sim/lib/knowledge/application/chat-history.integration.ts +++ b/apps/sim/lib/knowledge/application/chat-history.integration.ts @@ -349,7 +349,7 @@ describe('list_my_chat_history', () => { startDate: new Date(Date.now() - 91 * 86_400_000).toISOString(), endDate: new Date(Date.now() + 30 * 86_400_000).toISOString(), }) - expect(futureEnd.questions.map((q) => q.question)).toEqual(['recent']) + expect(futureEnd.questions.map((q) => q.question)).toContain('recent') }) it('refuses a caller outside the organization and a principal that is not a person', async () => { From f7fde4c745abe60d0f79392831f69b21af26687e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:17:08 -0800 Subject: [PATCH 09/10] feat(search): admit workflow runs as their person on the chat history operation --- apps/sim/lib/knowledge/application/chat-operations.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/knowledge/application/chat-operations.ts b/apps/sim/lib/knowledge/application/chat-operations.ts index fa03841ed20..8c3788e3b35 100644 --- a/apps/sim/lib/knowledge/application/chat-operations.ts +++ b/apps/sim/lib/knowledge/application/chat-operations.ts @@ -10,7 +10,8 @@ export const organizationSearchChatOperation = defineOrganizationOperation({ /** * A member reading back their own questions to Sim: in the app, through Search MCP clients under - * the scope that admits Search, and from the organization Assistant under its Search delegation. + * the scope that admits Search, from the organization Assistant under its Search delegation, and + * from a workflow run as its person. */ export const listMyChatHistoryOperation = defineOrganizationOperation({ id: 'knowledge.chat_history.list', @@ -18,7 +19,7 @@ export const listMyChatHistoryOperation = defineOrganizationOperation({ minimumRole: 'member', principalKinds: ['session', 'personal_api_key', 'oauth_access_token', 'organization_delegated'], delegationAudience: 'sim:knowledge', - delegatedServices: ['copilot'], + delegatedServices: ['copilot', 'executor'], contentDelivery: 'none', capability: 'copilot.use', }) From 04a51dc042b7f594e6c680f23ea9e48448f0e4ba Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:29:55 -0800 Subject: [PATCH 10/10] fix(search): chat history lists only conversations the caller may still open --- .../application/chat-history.integration.ts | 50 ++++++++++++++++++- .../lib/knowledge/application/chat-history.ts | 45 ++++++++++++++--- 2 files changed, 87 insertions(+), 8 deletions(-) diff --git a/apps/sim/lib/knowledge/application/chat-history.integration.ts b/apps/sim/lib/knowledge/application/chat-history.integration.ts index 7e51908efbf..3ab0f95a4d9 100644 --- a/apps/sim/lib/knowledge/application/chat-history.integration.ts +++ b/apps/sim/lib/knowledge/application/chat-history.integration.ts @@ -17,7 +17,24 @@ import { } from '@sim/db/schema' import { generateId } from '@sim/utils/id' import { inArray } from 'drizzle-orm' -import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +/** What the caller may open now: chat reads decide it from Build and Plan mode, stood in here. */ +const access = vi.hoisted(() => ({ canBuild: true, planEnabled: false })) +vi.mock('@/lib/mothership/chat/organization-chats', async (importOriginal) => { + const { OrchestrationError } = await import('@/lib/core/orchestration/types') + return { + ...(await importOriginal()), + requireOrganizationBuildPermission: async () => { + if (!access.canBuild) throw new OrchestrationError('forbidden', 'Build requires permission') + }, + } +}) +vi.mock('@/lib/mothership/feature-flags', async (importOriginal) => ({ + ...(await importOriginal()), + isPlanModeEnabled: async () => access.planEnabled, +})) + import { OrganizationMembershipNotFoundError } from '@/lib/core/application/organization-authorization' import { PrincipalKindAuthorizationError } from '@/lib/core/application/workspace-authorization' import { listMyChatHistory } from '@/lib/knowledge/application/chat-history' @@ -226,6 +243,37 @@ describe('list_my_chat_history', () => { expect(questions[0]?.conversationUrl).toMatch(new RegExp(`/workspace/${openWorkspaceId}/chat/`)) }) + it('leaves out conversations the caller can no longer open', async () => { + await ask(await chat(), 'assistant', '2026-11-02T10:00:00Z') + await ask( + await chat({ config: { conversationMode: 'agent' } }), + 'org agent', + '2026-11-02T10:01:00Z' + ) + await ask( + await chat({ config: { conversationMode: 'plan' } }), + 'org plan', + '2026-11-02T10:02:00Z' + ) + await ask( + await chat({ organizationId: null, workspaceId: openWorkspaceId }), + 'workspace agent', + '2026-11-02T10:03:00Z' + ) + const questions = async () => (await list()).questions.map((q) => q.question) + + try { + expect(await questions()).toEqual(['assistant', 'org agent', 'workspace agent']) + access.planEnabled = true + expect(await questions()).toEqual(['assistant', 'org agent', 'org plan', 'workspace agent']) + access.canBuild = false + expect(await questions()).toEqual(['assistant', 'workspace agent']) + } finally { + access.canBuild = true + access.planEnabled = false + } + }) + it('includes startDate and excludes endDate, and refuses a window over 92 days', async () => { const id = await chat() await ask(id, 'at start', WINDOW.startDate) diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts index 89de5d0140c..2e1ceebe87f 100644 --- a/apps/sim/lib/knowledge/application/chat-history.ts +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -15,7 +15,9 @@ import { getBaseUrl } from '@/lib/core/utils/urls' import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability' import { stripInteractiveCards } from '@/lib/knowledge/application/chat-citations' import { listMyChatHistoryOperation } from '@/lib/knowledge/application/chat-operations' -import { conversationModeSelection } from '@/lib/mothership/chat/intent' +import { type ConversationMode, conversationModeSelection } from '@/lib/mothership/chat/intent' +import { requireOrganizationBuildPermission } from '@/lib/mothership/chat/organization-chats' +import { isPlanModeEnabled } from '@/lib/mothership/feature-flags' import { organizationRoutes } from '@/lib/navigation/paths' import { listAccessibleWorkspaceRowsForUser } from '@/lib/workspaces/utils' @@ -115,6 +117,29 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ ) .filter(({ workspace }) => workspace.organizationId === organizationId) .map(({ workspace }) => workspace.id) + /** + * Only conversations the caller may open now, as chat reads decide it: agent and plan chats + * in the organization need Build, plan chats need Plan mode, and Assistant chats need neither. + */ + const [canBuild, planEnabled] = await Promise.all([ + requireOrganizationBuildPermission(context).then( + () => true, + (error: unknown) => { + if (error instanceof OrchestrationError && error.code === 'forbidden') return false + throw error + } + ), + isPlanModeEnabled(userId), + ]) + const organizationModes: ConversationMode[] = [ + 'assistant', + ...(canBuild ? (['agent'] as const) : []), + ...(canBuild && planEnabled ? (['plan'] as const) : []), + ] + const workspaceModes: ConversationMode[] = [ + 'agent', + ...(planEnabled ? (['plan'] as const) : []), + ] /** The caller's chats first: few per person, so the message read probes each chat's index. */ const chats = await db .select({ @@ -128,12 +153,18 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ and( eq(copilotChats.userId, userId), eq(copilotChats.type, 'mothership'), - workspaceIds.length - ? or( - eq(copilotChats.organizationId, organizationId), - inArray(copilotChats.workspaceId, workspaceIds) - ) - : eq(copilotChats.organizationId, organizationId), + or( + and( + eq(copilotChats.organizationId, organizationId), + inArray(conversationModeSelection, organizationModes) + ), + workspaceIds.length + ? and( + inArray(copilotChats.workspaceId, workspaceIds), + inArray(conversationModeSelection, workspaceModes) + ) + : undefined + ), isNull(copilotChats.deletedAt), sql`${copilotChats.config}->'benchmark' IS NULL` )