Skip to content

Commit 56307f0

Browse files
committed
fix(search): post-merge activity audit fixes
1 parent c0f0908 commit 56307f0

19 files changed

Lines changed: 386 additions & 62 deletions

‎apps/sim/lib/api/contracts/mothership-assistant-tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -703,7 +703,7 @@ export const assistantToolContracts = [
703703
id: 'list_my_activity',
704704
route: 'sim',
705705
description:
706-
'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.',
706+
'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 and Linear issues you take part in, such as by being assigned, reviewing or commenting (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.',
707707
inputSchema: listMyActivityInputSchema,
708708
},
709709
{

‎apps/sim/lib/internal/organization-search/catalog.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ export const ORGANIZATION_TOOL_CATALOG = {
147147
surface === 'mcp'
148148
? ['you', 'you', 'your']
149149
: ['the person running the workflow', 'they', 'their']
150-
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 : ''}`
150+
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 and Linear issues ${they} take part in, such as by being assigned, reviewing or commenting (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 : ''}`
151151
},
152152
},
153153
} as const satisfies Record<OrganizationToolName, OrganizationToolEntry>

‎apps/sim/lib/knowledge/application/chat-citations.test.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { describe, expect, it } from 'vitest'
2-
import { stripInteractiveCards } from '@/lib/knowledge/application/chat-citations'
2+
import {
3+
resolveSearchChatCitations,
4+
stripInteractiveCards,
5+
} from '@/lib/knowledge/application/chat-citations'
36

47
describe('stripInteractiveCards', () => {
58
it('removes a JSON card, including closing markers inside its strings', () => {
@@ -15,3 +18,35 @@ describe('stripInteractiveCards', () => {
1518
expect(stripInteractiveCards('Connect here <credential>{"type":"link"')).toBe('Connect here ')
1619
})
1720
})
21+
22+
describe('resolveSearchChatCitations', () => {
23+
it('gives each cited source the documentId read_document reads', () => {
24+
const documentId = 'live:v2.reference'
25+
const { citations } = resolveSearchChatCitations(
26+
'See <source>{"id":"live:0123456789abcdef0123456789abcdef"}</source>.',
27+
[
28+
{
29+
id: 'call',
30+
name: 'search_workspace',
31+
status: 'success',
32+
result: {
33+
success: true,
34+
data: {
35+
results: [
36+
{
37+
citationId: 'live:0123456789abcdef0123456789abcdef',
38+
citationUrl: 'https://docs.example.com/plan',
39+
documentId,
40+
documentName: 'Plan',
41+
},
42+
],
43+
},
44+
},
45+
},
46+
]
47+
)
48+
expect(citations).toEqual([
49+
expect.objectContaining({ title: 'Plan', url: 'https://docs.example.com/plan', documentId }),
50+
])
51+
})
52+
})

‎apps/sim/lib/knowledge/application/chat-citations.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
import { isPlainRecord } from '@sim/utils/object'
2+
import {
3+
citationResults,
4+
parseCitationRecord,
5+
toCitationResult,
6+
} from '@/lib/mothership/chat/citation-evidence'
27
import { compactRetrievalCitations } from '@/lib/mothership/chat/retrieval-citations'
38
import type { ToolCallSummary } from '@/lib/mothership/request/types'
49

510
export interface SearchChatCitation {
611
id: string
712
title: string
813
url: string
14+
/** The cited document as search names it, for read_document; absent for a web page. */
15+
documentId?: string
916
}
1017

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

53+
/**
54+
* The document each citation of one tool result names, from the full result: the saved,
55+
* compacted evidence leaves document IDs out.
56+
*/
57+
function citedDocumentIds(toolName: string, raw: unknown): Map<string, string> {
58+
const output = parseCitationRecord(raw)
59+
const data = output && isPlainRecord(output.data) ? output.data : output
60+
const ids = new Map<string, string>()
61+
if (!data) return ids
62+
for (const item of citationResults(toolName, data)) {
63+
if (!isPlainRecord(item)) continue
64+
const { citationId, documentId } = toCitationResult(toolName, item)
65+
if (typeof citationId === 'string' && typeof documentId === 'string')
66+
ids.set(citationId, documentId)
67+
}
68+
return ids
69+
}
70+
4671
/** Resolves Assistant source tags only against successful, bounded retrieval evidence. */
4772
export function resolveSearchChatCitations(content: string, toolCalls: ToolCallSummary[]) {
4873
const evidence = new Map<string, SearchChatCitation>()
@@ -52,6 +77,7 @@ export function resolveSearchChatCitations(content: string, toolCalls: ToolCallS
5277
if (!isPlainRecord(compact) || !isPlainRecord(compact.data)) continue
5378
const results = compact.data.results
5479
if (!Array.isArray(results)) continue
80+
const documentIds = citedDocumentIds(tool.name, tool.result)
5581
for (const result of results) {
5682
if (
5783
evidence.size >= 50 ||
@@ -68,6 +94,9 @@ export function resolveSearchChatCitations(content: string, toolCalls: ToolCallS
6894
id: result.citationId,
6995
title: typeof result.documentName === 'string' ? result.documentName : 'Source',
7096
url: url.href,
97+
...(documentIds.has(result.citationId)
98+
? { documentId: documentIds.get(result.citationId) }
99+
: {}),
71100
})
72101
}
73102
}

‎apps/sim/lib/knowledge/application/chat-history.integration.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,14 @@ vi.mock('@/lib/mothership/feature-flags', async (importOriginal) => ({
3636
isPlanModeEnabled: async () => access.planEnabled,
3737
}))
3838

39+
import { UNREADABLE_CURSOR_MESSAGE } from '@/lib/api/cursor-binding'
40+
import { INVALID_CURSOR_MESSAGE } from '@/lib/api/list-query'
3941
import { OrganizationMembershipNotFoundError } from '@/lib/core/application/organization-authorization'
4042
import { PrincipalKindAuthorizationError } from '@/lib/core/application/workspace-authorization'
41-
import { listMyChatHistory } from '@/lib/knowledge/application/chat-history'
43+
import {
44+
listMyChatHistory,
45+
SEARCH_MCP_CHAT_SURFACE,
46+
} from '@/lib/knowledge/application/chat-history'
4247

4348
const organizationId = generateId()
4449
const otherOrganizationId = generateId()
@@ -190,6 +195,8 @@ describe('list_my_chat_history', () => {
190195
const assistant = await chat()
191196
const slack = await chat({ externalConversationKey: 'slack:["i","D1","t"]' })
192197
const agent = await chat({ config: { conversationMode: 'agent' } })
198+
const searchMcp = await chat({ config: { surface: SEARCH_MCP_CHAT_SURFACE } })
199+
await ask(searchMcp, 'fourth', '2026-11-04T08:00:00Z')
193200
await ask(assistant, 'second', '2026-11-02T10:00:00Z')
194201
await ask(slack, 'first', '2026-11-01T09:00:00Z')
195202
await ask(agent, 'third', '2026-11-03T08:00:00Z')
@@ -203,10 +210,14 @@ describe('list_my_chat_history', () => {
203210
['first', 'slack', '2026-11-01T09:00:00.000Z'],
204211
['second', 'assistant', '2026-11-02T10:00:00.000Z'],
205212
['third', 'agent', '2026-11-03T08:00:00.000Z'],
213+
['fourth', 'search_mcp', '2026-11-04T08:00:00.000Z'],
206214
])
207215
expect(questions[1]?.conversationUrl).toMatch(
208216
new RegExp(`/o/${organizationId}/search/chat/${assistant}$`)
209217
)
218+
expect(questions[3]?.conversationUrl).toMatch(
219+
new RegExp(`/o/${organizationId}/search/chat/${searchMcp}$`)
220+
)
210221
expect(nextCursor).toBeUndefined()
211222
})
212223

@@ -355,7 +366,7 @@ describe('list_my_chat_history', () => {
355366
} while (cursor)
356367

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

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

@@ -516,7 +527,7 @@ describe('list_my_chat_history', () => {
516527
generateId(),
517528
])
518529
).toString('base64url')
519-
await expect(list({ cursor: forged })).rejects.toThrow(/nextCursor/)
530+
await expect(list({ cursor: forged })).rejects.toThrow(UNREADABLE_CURSOR_MESSAGE)
520531
})
521532

522533
it('finds the answer to a question saved without a transcript seq', async () => {

‎apps/sim/lib/knowledge/application/chat-history.ts‎

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ import { truncateAtCodePoint } from '@sim/utils/string'
66
import { and, asc, desc, eq, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm'
77
import { z } from 'zod'
88
import type { ListMyChatHistoryInput } from '@/lib/api/contracts/mothership-assistant-tools'
9-
import { classifyTimestampCursor, preciseTimestampText } from '@/lib/api/list-query'
9+
import { UNREADABLE_CURSOR_MESSAGE } from '@/lib/api/cursor-binding'
10+
import {
11+
classifyTimestampCursor,
12+
INVALID_CURSOR_MESSAGE,
13+
preciseTimestampText,
14+
} from '@/lib/api/list-query'
1015
import {
1116
defineAuthorizedOrganizationUseCase,
1217
type OrganizationUseCaseContext,
@@ -34,7 +39,10 @@ const ANSWER_READ_CHARS = 4_000
3439
/** Orders a message without a transcript `seq` after every numbered one, as transcripts read. */
3540
const LAST_SEQ = sql.raw('2147483647')
3641

37-
type ChatHistorySurface = 'assistant' | 'agent' | 'slack'
42+
/** The `config.surface` of a conversation the Search MCP `chat` tool started. */
43+
export const SEARCH_MCP_CHAT_SURFACE = 'search_mcp'
44+
45+
type ChatHistorySurface = 'assistant' | 'agent' | 'slack' | 'search_mcp'
3846

3947
interface ChatHistoryQuestion {
4048
/** When the question was asked, as an ISO datetime in UTC. */
@@ -93,7 +101,9 @@ function encodeCursor(sort: ChatHistorySort, position: ChatHistoryPosition): str
93101
function decodeCursor(cursor: string, sort: ChatHistorySort): ChatHistoryPosition {
94102
try {
95103
const parsed = cursorSchema.safeParse(JSON.parse(Buffer.from(cursor, 'base64url').toString()))
96-
if (parsed.success && parsed.data[0] === sort) {
104+
if (parsed.success && parsed.data[0] !== sort)
105+
throw new OrchestrationError('validation', INVALID_CURSOR_MESSAGE)
106+
if (parsed.success) {
97107
const [, from, to, createdAt, id] = parsed.data
98108
const window = { from: new Date(from), to: new Date(to) }
99109
/** The cursor is not signed, so its window is held to the same bounds as a first page. */
@@ -103,11 +113,11 @@ function decodeCursor(cursor: string, sort: ChatHistorySort): ChatHistoryPositio
103113
)
104114
return { ...window, createdAt, id }
105115
}
106-
} catch {}
107-
throw new OrchestrationError(
108-
'validation',
109-
'cursor is not a nextCursor from this tool for the same sortBy'
110-
)
116+
} catch (error) {
117+
if (error instanceof OrchestrationError) throw error
118+
}
119+
/** Worded as every other paged organization tool words it, search_people among them. */
120+
throw new OrchestrationError('validation', UNREADABLE_CURSOR_MESSAGE)
111121
}
112122

113123
/** The window read: the end is now at the latest, the start a week before it unless given. */
@@ -207,6 +217,7 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({
207217
id: copilotChats.id,
208218
workspaceId: copilotChats.workspaceId,
209219
slack: sql<boolean>`coalesce(${copilotChats.externalConversationKey} LIKE 'slack:%', false)`,
220+
searchMcp: sql<boolean>`coalesce(${copilotChats.config}->>'surface' = ${SEARCH_MCP_CHAT_SURFACE}, false)`,
210221
mode: conversationModeSelection,
211222
})
212223
.from(copilotChats)
@@ -337,10 +348,12 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({
337348
? 'slack'
338349
: chat.workspaceId || chat.mode !== 'assistant'
339350
? 'agent'
340-
: 'assistant'
351+
: chat.searchMcp
352+
? 'search_mcp'
353+
: 'assistant'
341354
const path = chat.workspaceId
342355
? `/workspace/${chat.workspaceId}/chat/${chat.id}`
343-
: surface === 'assistant'
356+
: surface === 'assistant' || surface === 'search_mcp'
344357
? routes.searchChat(chat.id)
345358
: routes.chat(chat.id)
346359
const excerpt = answerExcerpt(row.answer)

‎apps/sim/lib/knowledge/application/chat.integration.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* production code. Authorization, billing, the payload builder and the worker lifecycle are
55
* stood in, since only conversation ownership, locking and persistence are under test.
66
*/
7+
78
import { createDeferred } from '@sim/testing/helpers/deferred'
89
import { billingAttributionMock } from '@sim/testing/mocks/billing-attribution.mock'
910
import { knowledgeAvailabilityMock } from '@sim/testing/mocks/knowledge-availability.mock'
@@ -20,6 +21,7 @@ import {
2021
organizationAuthorizationMockFns,
2122
} from '@sim/testing/mocks/organization-authorization.mock'
2223
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
24+
import { SEARCH_MCP_CHAT_SURFACE } from '@/lib/knowledge/application/chat-history'
2325

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

154+
it('records that the conversation started from Search MCP, so chat history labels it', async () => {
155+
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('Yes.'))
156+
const { chatId } = await ask('Is it labelled?')
157+
if (!chatId) throw new Error('Expected a saved conversation')
158+
const [row] = await db
159+
.select({ config: copilotChats.config })
160+
.from(copilotChats)
161+
.where(eq(copilotChats.id, chatId))
162+
expect(row?.config).toMatchObject({ surface: SEARCH_MCP_CHAT_SURFACE })
163+
})
164+
152165
it.each([
153166
['another member’s conversation', 'other-member'],
154167
['a conversation in another organization', 'other-organization'],

‎apps/sim/lib/knowledge/application/chat.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
type SearchChatCitation,
2222
stripInteractiveCards,
2323
} from '@/lib/knowledge/application/chat-citations'
24+
import { SEARCH_MCP_CHAT_SURFACE } from '@/lib/knowledge/application/chat-history'
2425
import { organizationSearchChatOperation } from '@/lib/knowledge/application/chat-operations'
2526
import { loadCopilotSearchIntegrations } from '@/lib/mothership/application/load-search-integrations'
2627
import { conversationModeSelection } from '@/lib/mothership/chat/intent'
@@ -128,6 +129,8 @@ async function createConversation(userId: string, organizationId: string, query:
128129
model: MOTHERSHIP_CHAT_DEFAULT_MODEL,
129130
title: truncate(query.replace(/\s+/g, ' '), 80),
130131
lastSeenAt: new Date(),
132+
/** Names where the conversation started, so chat history can tell it from the Assistant's. */
133+
config: { surface: SEARCH_MCP_CHAT_SURFACE },
131134
})
132135
.returning({ id: copilotChats.id })
133136
if (!chat) throw new OrchestrationError('internal', 'Unable to create a Search conversation')

0 commit comments

Comments
 (0)