Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/sim/lib/api/contracts/mothership-assistant-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ export const assistantToolContracts = [
id: 'list_my_activity',
route: 'sim',
description:
'List what you did across your connected sources in a date window, always newest first: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted, Jira issues you created or that were assigned to you, Confluence pages you created or edited and comments you wrote, GitHub issues and pull requests you opened and commits you authored, Linear issues you created, Google Drive files you created or edited, and GitHub issues and pull requests and Linear issues you are involved in (involved, at their last update, which may be someone else’s). Each item has a documentId for read_document. Follow nextCursor for more; a source that failed and recovers on a later page can return entries older than that page. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link; unsupported names connected sources it does not cover; search_workspace reaches them with the filters each supports. Defaults to the last 7 days; the window spans at most 92 days. For a colleague’s activity, use search_workspace with involving.',
'List what you did across your connected sources in a date window, always newest first: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted, Jira issues you created or that were assigned to you, Confluence pages you created or edited and comments you wrote, GitHub issues and pull requests you opened and commits you authored, GitLab issues and merge requests you opened, changed, approved or commented on and commits you pushed, Linear issues you created, Google Drive files you created or edited, and the GitHub issues and pull requests you take part in, such as by being assigned, reviewing or commenting, and the Linear issues assigned to you (involved, at the item’s last update, which may be someone else’s). Each item has a documentId for read_document. Follow nextCursor for more; a source that failed and recovers on a later page can return entries older than that page. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link; unsupported names connected sources it does not cover; search_workspace reaches them with the filters each supports. Defaults to the last 7 days; the window spans at most 92 days. For a colleague’s activity, use search_workspace with involving.',
inputSchema: listMyActivityInputSchema,
},
{
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/internal/organization-search/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export const ORGANIZATION_TOOL_CATALOG = {
surface === 'mcp'
? ['you', 'you', 'your']
: ['the person running the workflow', 'they', 'their']
return `List what ${who} did across ${their} connected sources in a date window, always newest first, each at its activity time: Slack messages and Gmail mail ${they} sent (replied when the message answers another), Google Calendar meetings ${they} organized or accepted (attended), Jira issues ${they} created or that were assigned to ${surface === 'mcp' ? 'you' : 'them'}, Confluence pages ${they} created or edited and comments ${they} wrote, GitHub issues and pull requests ${they} opened (created) and commits ${they} authored (committed), Linear issues ${they} created, Google Drive files ${they} created or edited, and the GitHub issues and pull requests and Linear issues ${they} are involved in or assigned (involved, at their last update, which may be someone else’s). Use it for standups, weekly reports and open action items. Defaults to the last 7 days; the window spans at most 92 days. Each item has a documentId for ${nameOn(surface, 'read_document')} and, when available, a citationUrl to cite. While nextCursor is present, call again with it and the same startDate, endDate and source (topK may change): pages continue without gaps, though a source that failed and recovers on a later page can return entries older than that page. sources reports every source: not_connected and reconnect carry connect.url, where ${they} connect that account. unsupported names connected sources this listing does not cover; search those for the same dates with the filters each supports. For a colleague’s activity, use ${nameOn(surface, 'search')} with involving.${surface === 'workflow' ? RUN_LOGS : ''}`
return `List what ${who} did across ${their} connected sources in a date window, always newest first, each at its activity time: Slack messages and Gmail mail ${they} sent (replied when the message answers another), Google Calendar meetings ${they} organized or accepted (attended), Jira issues ${they} created or that were assigned to ${surface === 'mcp' ? 'you' : 'them'}, Confluence pages ${they} created or edited and comments ${they} wrote, GitHub issues and pull requests ${they} opened (created) and commits ${they} authored (committed), GitLab issues and merge requests ${they} opened, changed, approved or commented on and commits ${they} pushed, Linear issues ${they} created, Google Drive files ${they} created or edited, and the GitHub issues and pull requests ${they} take part in, such as by being assigned, reviewing or commenting, and the Linear issues assigned to ${surface === 'mcp' ? 'you' : 'them'} (involved, at the item’s last update, which may be someone else’s). Use it for standups, weekly reports and open action items. Defaults to the last 7 days; the window spans at most 92 days. Each item has a documentId for ${nameOn(surface, 'read_document')} and, when available, a citationUrl to cite. While nextCursor is present, call again with it and the same startDate, endDate and source (topK may change): pages continue without gaps, though a source that failed and recovers on a later page can return entries older than that page. sources reports every source: not_connected and reconnect carry connect.url, where ${they} connect that account. unsupported names connected sources this listing does not cover; search those for the same dates with the filters each supports. For a colleague’s activity, use ${nameOn(surface, 'search')} with involving.${surface === 'workflow' ? RUN_LOGS : ''}`
},
},
} as const satisfies Record<OrganizationToolName, OrganizationToolEntry>
Expand Down
37 changes: 36 additions & 1 deletion apps/sim/lib/knowledge/application/chat-citations.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { describe, expect, it } from 'vitest'
import { stripInteractiveCards } from '@/lib/knowledge/application/chat-citations'
import {
resolveSearchChatCitations,
stripInteractiveCards,
} from '@/lib/knowledge/application/chat-citations'

describe('stripInteractiveCards', () => {
it('removes a JSON card, including closing markers inside its strings', () => {
Expand All @@ -15,3 +18,35 @@ describe('stripInteractiveCards', () => {
expect(stripInteractiveCards('Connect here <credential>{"type":"link"')).toBe('Connect here ')
})
})

describe('resolveSearchChatCitations', () => {
it('gives each cited source the documentId read_document reads', () => {
const documentId = 'live:v2.reference'
const { citations } = resolveSearchChatCitations(
'See <source>{"id":"live:0123456789abcdef0123456789abcdef"}</source>.',
[
{
id: 'call',
name: 'search_workspace',
status: 'success',
result: {
success: true,
data: {
results: [
{
citationId: 'live:0123456789abcdef0123456789abcdef',
citationUrl: 'https://docs.example.com/plan',
documentId,
documentName: 'Plan',
},
],
},
},
},
]
)
expect(citations).toEqual([
expect.objectContaining({ title: 'Plan', url: 'https://docs.example.com/plan', documentId }),
])
})
})
29 changes: 29 additions & 0 deletions apps/sim/lib/knowledge/application/chat-citations.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { isPlainRecord } from '@sim/utils/object'
import {
citationResults,
parseCitationRecord,
toCitationResult,
} from '@/lib/mothership/chat/citation-evidence'
import { compactRetrievalCitations } from '@/lib/mothership/chat/retrieval-citations'
import type { ToolCallSummary } from '@/lib/mothership/request/types'

export interface SearchChatCitation {
id: string
title: string
url: string
/** The cited document as search names it, for read_document; absent for a web page. */
documentId?: string
}

/** Cards the Chat UI renders from a JSON payload; an MCP text answer drops them. */
Expand Down Expand Up @@ -43,6 +50,24 @@ export function stripInteractiveCards(content: string): string {
.replace(UNCLOSED_CARD, '')
}

/**
* The document each citation of one tool result names, from the full result: the saved,
* compacted evidence leaves document IDs out.
*/
function citedDocumentIds(toolName: string, raw: unknown): Map<string, string> {
const output = parseCitationRecord(raw)
const data = output && isPlainRecord(output.data) ? output.data : output
const ids = new Map<string, string>()
if (!data) return ids
for (const item of citationResults(toolName, data)) {
if (!isPlainRecord(item)) continue
const { citationId, documentId } = toCitationResult(toolName, item)
if (typeof citationId === 'string' && typeof documentId === 'string')
ids.set(citationId, documentId)
}
return ids
}

/** Resolves Assistant source tags only against successful, bounded retrieval evidence. */
export function resolveSearchChatCitations(content: string, toolCalls: ToolCallSummary[]) {
const evidence = new Map<string, SearchChatCitation>()
Expand All @@ -52,6 +77,7 @@ export function resolveSearchChatCitations(content: string, toolCalls: ToolCallS
if (!isPlainRecord(compact) || !isPlainRecord(compact.data)) continue
const results = compact.data.results
if (!Array.isArray(results)) continue
const documentIds = citedDocumentIds(tool.name, tool.result)
for (const result of results) {
if (
evidence.size >= 50 ||
Expand All @@ -68,6 +94,9 @@ export function resolveSearchChatCitations(content: string, toolCalls: ToolCallS
id: result.citationId,
title: typeof result.documentName === 'string' ? result.documentName : 'Source',
url: url.href,
...(documentIds.has(result.citationId)
? { documentId: documentIds.get(result.citationId) }
: {}),
})
}
}
Expand Down
19 changes: 15 additions & 4 deletions apps/sim/lib/knowledge/application/chat-history.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,14 @@ vi.mock('@/lib/mothership/feature-flags', async (importOriginal) => ({
isPlanModeEnabled: async () => access.planEnabled,
}))

import { UNREADABLE_CURSOR_MESSAGE } from '@/lib/api/cursor-binding'
import { INVALID_CURSOR_MESSAGE } from '@/lib/api/list-query'
import { OrganizationMembershipNotFoundError } from '@/lib/core/application/organization-authorization'
import { PrincipalKindAuthorizationError } from '@/lib/core/application/workspace-authorization'
import { listMyChatHistory } from '@/lib/knowledge/application/chat-history'
import {
listMyChatHistory,
SEARCH_MCP_CHAT_SURFACE,
} from '@/lib/knowledge/application/chat-history'

const organizationId = generateId()
const otherOrganizationId = generateId()
Expand Down Expand Up @@ -190,6 +195,8 @@ describe('list_my_chat_history', () => {
const assistant = await chat()
const slack = await chat({ externalConversationKey: 'slack:["i","D1","t"]' })
const agent = await chat({ config: { conversationMode: 'agent' } })
const searchMcp = await chat({ config: { surface: SEARCH_MCP_CHAT_SURFACE } })
await ask(searchMcp, 'fourth', '2026-11-04T08:00:00Z')
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')
Expand All @@ -203,10 +210,14 @@ describe('list_my_chat_history', () => {
['first', 'slack', '2026-11-01T09:00:00.000Z'],
['second', 'assistant', '2026-11-02T10:00:00.000Z'],
['third', 'agent', '2026-11-03T08:00:00.000Z'],
['fourth', 'search_mcp', '2026-11-04T08:00:00.000Z'],
])
expect(questions[1]?.conversationUrl).toMatch(
new RegExp(`/o/${organizationId}/search/chat/${assistant}$`)
)
expect(questions[3]?.conversationUrl).toMatch(
new RegExp(`/o/${organizationId}/search/chat/${searchMcp}$`)
)
expect(nextCursor).toBeUndefined()
})

Expand Down Expand Up @@ -355,7 +366,7 @@ describe('list_my_chat_history', () => {
} while (cursor)

expect(seen.sort()).toEqual(['q0', 'q1', 'q2', 'q3', 'q4'])
await expect(list({ cursor: 'not-a-cursor' })).rejects.toThrow(/nextCursor/)
await expect(list({ cursor: 'not-a-cursor' })).rejects.toThrow(UNREADABLE_CURSOR_MESSAGE)
})

it('adds the start of the next answer, without citation tags, only when asked', async () => {
Expand Down Expand Up @@ -488,7 +499,7 @@ describe('list_my_chat_history', () => {
)
).toEqual(['earlier'])
await expect(list({ sortBy: 'oldest', cursor: newest.nextCursor })).rejects.toThrow(
/same sortBy/
INVALID_CURSOR_MESSAGE
)
})

Expand Down Expand Up @@ -516,7 +527,7 @@ describe('list_my_chat_history', () => {
generateId(),
])
).toString('base64url')
await expect(list({ cursor: forged })).rejects.toThrow(/nextCursor/)
await expect(list({ cursor: forged })).rejects.toThrow(UNREADABLE_CURSOR_MESSAGE)
})

it('finds the answer to a question saved without a transcript seq', async () => {
Expand Down
33 changes: 23 additions & 10 deletions apps/sim/lib/knowledge/application/chat-history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ import { truncateAtCodePoint } from '@sim/utils/string'
import { and, asc, desc, 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 { UNREADABLE_CURSOR_MESSAGE } from '@/lib/api/cursor-binding'
import {
classifyTimestampCursor,
INVALID_CURSOR_MESSAGE,
preciseTimestampText,
} from '@/lib/api/list-query'
import {
defineAuthorizedOrganizationUseCase,
type OrganizationUseCaseContext,
Expand Down Expand Up @@ -34,7 +39,10 @@ const ANSWER_READ_CHARS = 4_000
/** 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'
/** The `config.surface` of a conversation the Search MCP `chat` tool started. */
export const SEARCH_MCP_CHAT_SURFACE = 'search_mcp'

type ChatHistorySurface = 'assistant' | 'agent' | 'slack' | 'search_mcp'

interface ChatHistoryQuestion {
/** When the question was asked, as an ISO datetime in UTC. */
Expand Down Expand Up @@ -93,7 +101,9 @@ function encodeCursor(sort: ChatHistorySort, position: ChatHistoryPosition): str
function decodeCursor(cursor: string, sort: ChatHistorySort): ChatHistoryPosition {
try {
const parsed = cursorSchema.safeParse(JSON.parse(Buffer.from(cursor, 'base64url').toString()))
if (parsed.success && parsed.data[0] === sort) {
if (parsed.success && parsed.data[0] !== sort)
throw new OrchestrationError('validation', INVALID_CURSOR_MESSAGE)
if (parsed.success) {
const [, from, to, createdAt, id] = parsed.data
const window = { from: new Date(from), to: new Date(to) }
/** The cursor is not signed, so its window is held to the same bounds as a first page. */
Expand All @@ -103,11 +113,11 @@ function decodeCursor(cursor: string, sort: ChatHistorySort): ChatHistoryPositio
)
return { ...window, createdAt, id }
}
} catch {}
throw new OrchestrationError(
'validation',
'cursor is not a nextCursor from this tool for the same sortBy'
)
} catch (error) {
if (error instanceof OrchestrationError) throw error
}
/** Worded as every other paged organization tool words it, search_people among them. */
throw new OrchestrationError('validation', UNREADABLE_CURSOR_MESSAGE)
}

/** The window read: the end is now at the latest, the start a week before it unless given. */
Expand Down Expand Up @@ -207,6 +217,7 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({
id: copilotChats.id,
workspaceId: copilotChats.workspaceId,
slack: sql<boolean>`coalesce(${copilotChats.externalConversationKey} LIKE 'slack:%', false)`,
searchMcp: sql<boolean>`coalesce(${copilotChats.config}->>'surface' = ${SEARCH_MCP_CHAT_SURFACE}, false)`,
mode: conversationModeSelection,
})
.from(copilotChats)
Expand Down Expand Up @@ -337,10 +348,12 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({
? 'slack'
: chat.workspaceId || chat.mode !== 'assistant'
? 'agent'
: 'assistant'
: chat.searchMcp
? 'search_mcp'
: 'assistant'
const path = chat.workspaceId
? `/workspace/${chat.workspaceId}/chat/${chat.id}`
: surface === 'assistant'
: surface === 'assistant' || surface === 'search_mcp'
? routes.searchChat(chat.id)
: routes.chat(chat.id)
const excerpt = answerExcerpt(row.answer)
Expand Down
13 changes: 13 additions & 0 deletions apps/sim/lib/knowledge/application/chat.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* production code. Authorization, billing, the payload builder and the worker lifecycle are
* stood in, since only conversation ownership, locking and persistence are under test.
*/

import { createDeferred } from '@sim/testing/helpers/deferred'
import { billingAttributionMock } from '@sim/testing/mocks/billing-attribution.mock'
import { knowledgeAvailabilityMock } from '@sim/testing/mocks/knowledge-availability.mock'
Expand All @@ -20,6 +21,7 @@ import {
organizationAuthorizationMockFns,
} from '@sim/testing/mocks/organization-authorization.mock'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { SEARCH_MCP_CHAT_SURFACE } from '@/lib/knowledge/application/chat-history'

vi.mock('@/lib/core/application/organization-authorization', () => organizationAuthorizationMock)
vi.mock('@/lib/knowledge/access/availability', () => knowledgeAvailabilityMock)
Expand Down Expand Up @@ -149,6 +151,17 @@ describe('Search MCP chat follow-ups', () => {
expect(await liveChats(memberId)).toEqual([{ id: first.chatId }])
})

it('records that the conversation started from Search MCP, so chat history labels it', async () => {
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('Yes.'))
const { chatId } = await ask('Is it labelled?')
if (!chatId) throw new Error('Expected a saved conversation')
const [row] = await db
.select({ config: copilotChats.config })
.from(copilotChats)
.where(eq(copilotChats.id, chatId))
expect(row?.config).toMatchObject({ surface: SEARCH_MCP_CHAT_SURFACE })
})

it.each([
['another member’s conversation', 'other-member'],
['a conversation in another organization', 'other-organization'],
Expand Down
3 changes: 3 additions & 0 deletions apps/sim/lib/knowledge/application/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
type SearchChatCitation,
stripInteractiveCards,
} from '@/lib/knowledge/application/chat-citations'
import { SEARCH_MCP_CHAT_SURFACE } from '@/lib/knowledge/application/chat-history'
import { organizationSearchChatOperation } from '@/lib/knowledge/application/chat-operations'
import { loadCopilotSearchIntegrations } from '@/lib/mothership/application/load-search-integrations'
import { conversationModeSelection } from '@/lib/mothership/chat/intent'
Expand Down Expand Up @@ -128,6 +129,8 @@ async function createConversation(userId: string, organizationId: string, query:
model: MOTHERSHIP_CHAT_DEFAULT_MODEL,
title: truncate(query.replace(/\s+/g, ' '), 80),
lastSeenAt: new Date(),
/** Names where the conversation started, so chat history can tell it from the Assistant's. */
config: { surface: SEARCH_MCP_CHAT_SURFACE },
})
.returning({ id: copilotChats.id })
if (!chat) throw new OrchestrationError('internal', 'Unable to create a Search conversation')
Expand Down
Loading
Loading