From 581f52f7ffaaaa323585f9ec8ed4b9355757f180 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 20:50:29 -0800 Subject: [PATCH 01/13] feat(search): list_my_activity across connected sources for Search MCP and the Assistant Reads the caller's own activity live from each connected account: Slack messages sent and replied, Gmail mail sent and replied, Google Calendar meetings attended, Jira issues created and assigned, Confluence pages created or edited and comments. Pages merge newest first behind a per-stream horizon with a signed per-account cursor, so nothing is dropped between pages; every entry passes the source boundary check before it is returned. Each source reports ok, partial, not_connected (with where to connect), reconnect, unsupported or failed. Gated by the my-activity organization flag. --- .../home/components/message-content/utils.ts | 1 + apps/sim/lib/api/contracts/knowledge/mcp.ts | 11 + .../contracts/mothership-assistant-tools.ts | 130 +++++ apps/sim/lib/core/config/env.ts | 1 + apps/sim/lib/core/config/feature-flags.ts | 6 + .../lib/knowledge/application/operations.ts | 17 + apps/sim/lib/knowledge/mcp/my-activity.ts | 60 +++ apps/sim/lib/knowledge/mcp/route-handler.ts | 12 + apps/sim/lib/knowledge/mcp/server.ts | 5 + .../lib/mothership/assistant/tool-policy.ts | 1 + .../lib/mothership/chat/citation-evidence.ts | 27 +- apps/sim/lib/mothership/entitlements.ts | 6 + apps/sim/lib/mothership/generated/protocol.ts | 1 + .../sim-assistant-tools.generated.ts | 124 +++++ .../lib/mothership/tool-executor/executor.ts | 1 + apps/sim/lib/mothership/tools/activity.ts | 1 + apps/sim/lib/mothership/tools/display.ts | 1 + .../tools/server/knowledge/my-activity.ts | 72 +++ .../sim/lib/mothership/tools/server/router.ts | 2 + .../lib/sim-search/live/account-session.ts | 31 +- .../lib/sim-search/live/activity-page.test.ts | 221 +++++++++ apps/sim/lib/sim-search/live/activity-page.ts | 210 +++++++++ .../live/activity-providers.test.ts | 247 ++++++++++ .../sim-search/live/activity.integration.ts | 111 +++++ apps/sim/lib/sim-search/live/activity.ts | 444 ++++++++++++++++++ apps/sim/lib/sim-search/live/application.ts | 23 +- apps/sim/lib/sim-search/live/atlassian.ts | 290 +++++++++++- apps/sim/lib/sim-search/live/google.ts | 171 +++++++ apps/sim/lib/sim-search/live/providers.ts | 36 +- apps/sim/lib/sim-search/live/slack.ts | 61 +++ apps/sim/lib/sim-search/live/types.ts | 54 +++ 31 files changed, 2349 insertions(+), 29 deletions(-) create mode 100644 apps/sim/lib/knowledge/mcp/my-activity.ts create mode 100644 apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts create mode 100644 apps/sim/lib/sim-search/live/activity-page.test.ts create mode 100644 apps/sim/lib/sim-search/live/activity-page.ts create mode 100644 apps/sim/lib/sim-search/live/activity-providers.test.ts create mode 100644 apps/sim/lib/sim-search/live/activity.integration.ts create mode 100644 apps/sim/lib/sim-search/live/activity.ts diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/message-content/utils.ts b/apps/sim/app/workspace/[workspaceId]/home/components/message-content/utils.ts index 9c5690678d2..134cb55b8f4 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/message-content/utils.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/components/message-content/utils.ts @@ -158,6 +158,7 @@ export const TOOL_ICONS: Readonly> = { search_sources: Search, settings: Settings, list_workspaces: Search, + list_my_activity: Search, workspaces: Search, set_block_enabled: Pencil, set_environment_variables: Settings, diff --git a/apps/sim/lib/api/contracts/knowledge/mcp.ts b/apps/sim/lib/api/contracts/knowledge/mcp.ts index b74cf5df281..ad01138a124 100644 --- a/apps/sim/lib/api/contracts/knowledge/mcp.ts +++ b/apps/sim/lib/api/contracts/knowledge/mcp.ts @@ -5,7 +5,9 @@ import { } from '@/lib/api/contracts/knowledge/search' import { mcpJsonRpcMessageSchema } from '@/lib/api/contracts/mcp' import { + listMyActivityInputFieldsSchema, readDocumentInputSchema, + refineActivityWindow, refineSearchWorkspaceInput, searchWorkspaceInputFieldsSchema, } from '@/lib/api/contracts/mothership-assistant-tools' @@ -64,6 +66,15 @@ export const liveSearchMcpSchema = searchWorkspaceInputFieldsSchema .strict() .superRefine(refineSearchWorkspaceInput) +/** list_my_activity as the Search MCP presents it: a date without an offset reads as UTC. */ +export const listMyActivityMcpSchema = listMyActivityInputFieldsSchema + .extend({ + startDate: mcpDateFilter(listMyActivityInputFieldsSchema.shape.startDate), + endDate: mcpDateFilter(listMyActivityInputFieldsSchema.shape.endDate), + }) + .strict() + .superRefine(refineActivityWindow) + /** * Previews a search returns when the caller sets no topK. A query across every source shares one * list among all of them, so it gets more room than a search of one source, a native query, or a diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index 5ea374aff4f..f8b2df476ca 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -335,6 +335,129 @@ export const readDocumentInputSchema = z.object({ ), }) +/** Days one activity listing may span, about a quarter. */ +export const MAX_ACTIVITY_WINDOW_DAYS = 92 +/** Activity entries one page returns when the caller sets no topK. */ +export const DEFAULT_ACTIVITY_TOP_K = 25 + +/** The activity filters, shared by every surface; refine with {@link refineActivityWindow}. */ +export const listMyActivityInputFieldsSchema = z + .object({ + startDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + `Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.` + ), + endDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + 'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.' + ), + source: liveSearchProviderSchema + .optional() + .describe( + 'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.' + ), + topK: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe(`Maximum entries on this page: ${DEFAULT_ACTIVITY_TOP_K} by default.`), + cursor: z + .string() + .min(1) + .max(8000) + .optional() + .describe( + 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.' + ), + }) + .strict() + +/** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */ +export function refineActivityWindow( + input: { startDate?: string; endDate?: string }, + context: z.RefinementCtx +) { + if (!input.startDate || !input.endDate) return + const start = Date.parse(input.startDate) + const end = Date.parse(input.endDate) + if (start >= end) + context.addIssue({ + code: 'custom', + path: ['endDate'], + message: 'endDate must be after startDate.', + }) + else if (end - start > MAX_ACTIVITY_WINDOW_DAYS * 86_400_000) + context.addIssue({ + code: 'custom', + path: ['startDate'], + message: `The window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.`, + }) +} + +export const listMyActivityInputSchema = + listMyActivityInputFieldsSchema.superRefine(refineActivityWindow) + +/** + * How one source served a multi-source result. `not_connected` and `reconnect` carry `connect`: + * the provider to connect and the page where the caller connects it. + */ +export const liveSourceStatusSchema = z.object({ + source: liveSearchProviderSchema, + accountId: z.string().optional(), + displayName: z.string().optional(), + status: z.enum(['ok', 'partial', 'not_connected', 'reconnect', 'unsupported', 'failed']), + reason: z.enum(['rate_limited', 'timeout', 'unavailable']).optional(), + retryAfterSeconds: z.number().optional(), + message: z.string().optional(), + connect: z.object({ providerId: z.string(), url: z.string() }).optional(), +}) +export type LiveSourceStatus = z.output + +const activityItemSchema = z.object({ + /** Reads the item with read_document. */ + documentId: z.string(), + timestamp: z.string(), + source: liveSearchProviderSchema, + accountId: z.string(), + action: z.enum([ + 'created', + 'edited', + 'commented', + 'sent', + 'replied', + 'attended', + 'assigned', + 'mentioned', + ]), + title: z.string(), + url: z.string().nullable(), + container: z.string().optional(), + collaborators: z.array(z.string()), + snippet: z.string(), + /** The timestamp is the item's last update, possibly by someone else, not the person's action. */ + approximateTime: z.literal(true).optional(), +}) + +const listMyActivityResultSchema = z.object({ + window: z.object({ startDate: z.string(), endDate: z.string() }), + items: z.array(activityItemSchema), + /** More entries remain; continue with nextCursor. */ + truncated: z.boolean(), + nextCursor: z.string().optional(), + /** `complete` when every connected source that reports activity was read in full. */ + coverage: z.enum(['complete', 'partial']), + sources: z.array(liveSourceStatusSchema.extend({ itemCount: z.number().int().min(0) })), +}) +export type ListMyActivityResult = z.output + /** * Organization directory lookups. The bounds mirror the People page's search limits * (`lib/people/validation`) as literals, so the worker's generated copy stays standalone. @@ -490,6 +613,13 @@ export const assistantToolContracts = [ '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: 'list_my_activity', + route: 'sim', + description: + 'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', + inputSchema: listMyActivityInputSchema, + }, { id: 'oauth_get_auth_link', route: 'sim', diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 4d77ebc50d8..47aa7c809c6 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -627,6 +627,7 @@ export const env = createEnv({ CHANGELOG: z.boolean().optional(), // Fallback for the `changelog` feature flag off AppConfig SIM_LINKS: z.boolean().optional(), // Fallback for the `sim-links` feature flag off AppConfig PEOPLE: z.boolean().optional(), // Fallback for the `people` feature flag off AppConfig + MY_ACTIVITY: z.boolean().optional(), // Fallback for the `my-activity` feature flag off AppConfig ORGANIZATION_ACTIVITY_ROLLUP_READS: z.boolean().optional(), // Fallback for the `organization-activity-rollup-reads` feature flag off AppConfig ACTIVITY_ROLLUP_MAINTENANCE: z.boolean().optional(), // Fallback for the `activity-rollup-maintenance` feature flag off AppConfig ACTIVITY_ROLLUP_BACKFILL_ROWS_PER_SECOND: z.coerce.number().int().positive().optional(), // Source rows the activity rollup backfill reads per second (default 20000) diff --git a/apps/sim/lib/core/config/feature-flags.ts b/apps/sim/lib/core/config/feature-flags.ts index 2c3f643904b..0c2e3ca785d 100644 --- a/apps/sim/lib/core/config/feature-flags.ts +++ b/apps/sim/lib/core/config/feature-flags.ts @@ -76,6 +76,12 @@ const FEATURE_FLAGS = { 'Enable the organization People directory, org chart, profile imports, and directory sync. Supports organization rollout; disabled by default.', fallback: 'PEOPLE', }, + 'my-activity': { + description: + "Enable list_my_activity: the caller's own activity across their connected sources, in the " + + 'Search MCP and the organization Assistant. Supports organization rollout; disabled by default.', + fallback: 'MY_ACTIVITY', + }, 'mothership-model-selector': { description: 'Show the Mothership model selector, model-specific effort levels, and Fast for supported ' + diff --git a/apps/sim/lib/knowledge/application/operations.ts b/apps/sim/lib/knowledge/application/operations.ts index 3c4b43e5d5f..79c7c11db1a 100644 --- a/apps/sim/lib/knowledge/application/operations.ts +++ b/apps/sim/lib/knowledge/application/operations.ts @@ -420,6 +420,23 @@ export const knowledgeOperations = { }), { organizationDelegatedServices: ['copilot', 'slack-search', 'executor'] } ), + /** + * The caller's own activity across their connected sources. It always reads the person the + * principal represents, so a principal without one (a workspace API key, an actorless run) is + * refused rather than read as anyone else. + */ + listActivity: defineKnowledgeOperation( + defineWorkspaceOperation({ + id: 'knowledge.activity.list', + oauthScope: 'search:read', + minimumRole: 'read', + workspaceApiKey: 'deny', + capability: 'knowledge.use', + contentDelivery: 'sourced', + ...HUMAN_AND_COPILOT_PRINCIPAL_POLICY, + }), + { organizationDelegation: 'allow' } + ), listFolders: defineKnowledgeOperation( defineWorkspaceOperation({ id: 'knowledge.folders.list', diff --git a/apps/sim/lib/knowledge/mcp/my-activity.ts b/apps/sim/lib/knowledge/mcp/my-activity.ts new file mode 100644 index 00000000000..3853a1e3b90 --- /dev/null +++ b/apps/sim/lib/knowledge/mcp/my-activity.ts @@ -0,0 +1,60 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import type { Principal } from '@sim/auth/principal' +import type { NextRequest } from 'next/server' +import { listMyActivityMcpSchema } from '@/lib/api/contracts/knowledge/mcp' +import { knowledgeOperations } from '@/lib/knowledge/application/operations' +import { + KNOWLEDGE_MCP_READ_ONLY, + type KnowledgeMcpToolRunner, + projectResult, +} from '@/lib/knowledge/mcp/tool-runner' +import { listMyActivity } from '@/lib/sim-search/live/activity' + +interface ListMyActivityToolContext { + execute: KnowledgeMcpToolRunner + principal: Principal + organizationId: string + request: NextRequest +} + +/** + * Provider reads one call makes, for the rate limit: about one listing per connected source, + * which is more than a single search's share. + */ +const LIST_MY_ACTIVITY_COST = 2 + +/** + * Registers `list_my_activity`: what the caller did across their connected sources in a window, + * newest first, with a status per source that names the ones to connect. + */ +export function registerListMyActivityTool( + server: McpServer, + { execute, principal, organizationId, request }: ListMyActivityToolContext +) { + server.registerTool( + 'list_my_activity', + { + title: 'List my activity', + description: + 'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent or replied to, Google Calendar meetings you attended, Jira issues you created or are assigned, and Confluence pages you created or edited and comments you wrote. 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 read_document and its url to cite. approximateTime marks a time that is the item’s last update rather than your own action. When truncated is true, call again with nextCursor and the same arguments: pages continue without gaps. sources reports every source: not_connected and reconnect carry connect.url, where you connect that account.', + inputSchema: listMyActivityMcpSchema, + annotations: KNOWLEDGE_MCP_READ_ONLY, + }, + async (input: unknown, extra: { signal: AbortSignal }) => + execute( + 'list_my_activity', + knowledgeOperations.listActivity, + extra.signal, + async (registry, signal) => { + const parsed = listMyActivityMcpSchema.parse(input) + const result = await listMyActivity.execute({ + principal, + input: { ...parsed, organizationId, resultSecretRegistry: registry, signal }, + request, + }) + return projectResult(result, registry) + }, + LIST_MY_ACTIVITY_COST + ) + ) +} diff --git a/apps/sim/lib/knowledge/mcp/route-handler.ts b/apps/sim/lib/knowledge/mcp/route-handler.ts index c0d7f44602a..8c9d67bf2bf 100644 --- a/apps/sim/lib/knowledge/mcp/route-handler.ts +++ b/apps/sim/lib/knowledge/mcp/route-handler.ts @@ -20,6 +20,7 @@ import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server' import { repairToolCallMessage, toolCallInputIssues } from '@/lib/knowledge/mcp/tool-arguments' import { getSearchMcpUrl } from '@/lib/knowledge/mcp/urls' import { canLookUpPeople } from '@/lib/people/directory-lookup' +import { isMyActivityEnabled } from '@/lib/sim-search/live/activity' import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response' const logger = createLogger('KnowledgeMcp') @@ -42,6 +43,16 @@ function mcpAuth(resource: string) { return mcpCredentialAuth({ resource, allowUnboundApiTokens: true }) } +/** + * Whether this message needs list_my_activity registered: a call to it, which its use case + * authorizes, or a tools/list while the feature is on for this organization. + */ +async function offersListMyActivity(message: Record, organizationId: string) { + if (message.method === 'tools/call') + return isRecordLike(message.params) && message.params.name === 'list_my_activity' + return message.method === 'tools/list' && isMyActivityEnabled(organizationId) +} + export function createKnowledgeMcpHandlers() { /** JSON-RPC is a protocol boundary; SDK dispatch calls the same authorized knowledge use cases. */ const handler = withRouteHandler( @@ -82,6 +93,7 @@ export function createKnowledgeMcpHandlers() { auth: admission.auth, ...parsed.data.params, searchPeople: await offersSearchPeople(message, admission.auth.principal, organizationId), + listMyActivity: await offersListMyActivity(message, organizationId), }) return await serveStatelessMcp(server, request, message) } catch (error) { diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 319dfbbbb55..99224542db3 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -19,6 +19,7 @@ import { type SearchMcpActivityInput, } from '@/lib/knowledge/mcp/activity' import { registerListMyChatHistoryTool } from '@/lib/knowledge/mcp/chat-history' +import { registerListMyActivityTool } from '@/lib/knowledge/mcp/my-activity' import { callerErrorMessage, readOrganizationDocuments, @@ -49,6 +50,8 @@ interface KnowledgeMcpContext { auth: V2ApiKeyAuthContext /** Registers search_people, which its use cases authorize on every call. */ searchPeople?: boolean + /** Registers list_my_activity, which its use case authorizes on every call. */ + listMyActivity?: boolean } /** A request owns its server; no credential or principal survives into another HTTP request. */ @@ -206,6 +209,8 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe // Only a person has a chat history; a workspace API key acts for no one. if (resolvePrincipalSubjectUserId(principal)) registerListMyChatHistoryTool(server, { execute, principal, organizationId }) + if (context.listMyActivity) + registerListMyActivityTool(server, { execute, principal, organizationId, request }) return server } diff --git a/apps/sim/lib/mothership/assistant/tool-policy.ts b/apps/sim/lib/mothership/assistant/tool-policy.ts index 675d1417191..7a87495b29b 100644 --- a/apps/sim/lib/mothership/assistant/tool-policy.ts +++ b/apps/sim/lib/mothership/assistant/tool-policy.ts @@ -7,6 +7,7 @@ export const ASSISTANT_TOOLS = new Set([ 'read_document', 'search_people', 'list_my_chat_history', + 'list_my_activity', 'oauth_get_auth_link', 'run_function', ]) diff --git a/apps/sim/lib/mothership/chat/citation-evidence.ts b/apps/sim/lib/mothership/chat/citation-evidence.ts index ce7a48399cf..75bf193f27c 100644 --- a/apps/sim/lib/mothership/chat/citation-evidence.ts +++ b/apps/sim/lib/mothership/chat/citation-evidence.ts @@ -16,7 +16,12 @@ type RetrievalCitationSource = { const WEB_TOOLS = new Set(['web_search', 'web_fetch']) /** Tools whose successful results supply sources: connected-source retrieval and public web research. */ -const CITATION_TOOLS = new Set(['search_workspace', 'read_document', ...WEB_TOOLS]) +const CITATION_TOOLS = new Set([ + 'search_workspace', + 'read_document', + 'list_my_activity', + ...WEB_TOOLS, +]) /** Whether a successful result of this tool may supply source destinations. */ export function isCitationTool(toolName: string): boolean { @@ -68,7 +73,12 @@ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitat const output = parseCitationRecord(call.result.output) if (!output || output.success === false) continue const data = parseCitationRecord(output.data) ?? output - const results = Array.isArray(data.results) ? data.results : [data] + /** Activity lists its entries as `items`, each a source like a search result. */ + const results = Array.isArray(data.results) + ? data.results + : Array.isArray(data.items) + ? data.items + : [data] for (const raw of results) { const record = parseCitationRecord(raw) const result = record && toCitationResult(call.name, record) @@ -89,17 +99,18 @@ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitat if (evidence.has(result.citationId)) continue const siteName = typeof result.siteName === 'string' ? result.siteName : result.knowledgeBaseName - const updatedAt = result.sourceDate ?? result.sourceModifiedAt + const updatedAt = result.sourceDate ?? result.sourceModifiedAt ?? result.timestamp + const title = result.documentName ?? result.title + const connectorType = result.connectorType ?? result.source + const snippet = result.content ?? result.snippet evidence.set(result.citationId, { url: result.citationUrl, - ...(typeof result.documentName === 'string' ? { title: result.documentName } : {}), + ...(typeof title === 'string' ? { title } : {}), ...(typeof siteName === 'string' ? { siteName } : {}), - ...(typeof result.connectorType === 'string' - ? { connectorType: result.connectorType } - : {}), + ...(typeof connectorType === 'string' ? { connectorType } : {}), ...(typeof result.author === 'string' ? { author: result.author } : {}), ...(typeof updatedAt === 'string' ? { updatedAt } : {}), - ...(typeof result.content === 'string' ? { snippet: result.content.slice(0, 500) } : {}), + ...(typeof snippet === 'string' ? { snippet: snippet.slice(0, 500) } : {}), }) } } diff --git a/apps/sim/lib/mothership/entitlements.ts b/apps/sim/lib/mothership/entitlements.ts index c97472d4749..f18698e0ea3 100644 --- a/apps/sim/lib/mothership/entitlements.ts +++ b/apps/sim/lib/mothership/entitlements.ts @@ -5,6 +5,7 @@ import { readDashboardAvailability } from '@/lib/dashboards/application/availabi import { isDashboardsEnabled } from '@/lib/dashboards/feature-flag' import { ENTITLEMENTS, type Entitlement } from '@/lib/mothership/generated/protocol' import { canLookUpPeople } from '@/lib/people/directory-lookup' +import { isMyActivityEnabled } from '@/lib/sim-search/live/activity' import { readWorkflowTestAvailability } from '@/lib/workflow-tests/application/availability' import { isWorkflowTestsEnabled } from '@/lib/workflow-tests/feature-flag' import { readWorkflowCodeAvailability } from '@/lib/workflows/application/code-availability' @@ -87,6 +88,11 @@ const EVALUATORS: Record = { assistant: ({ principal, organizationId }) => principal ? canLookUpPeople(principal, organizationId) : Promise.resolve(false), }, + /** `list_my_activity` in organization chats; its use case re-checks the flag. */ + [ENTITLEMENTS.myActivity]: { + assistant: ({ organizationId }) => isMyActivityEnabled(organizationId), + organization: ({ organizationId }) => isMyActivityEnabled(organizationId), + }, } function evaluate(evaluator: EntitlementEvaluator, owner: EntitlementOwner): Promise { diff --git a/apps/sim/lib/mothership/generated/protocol.ts b/apps/sim/lib/mothership/generated/protocol.ts index 1ad8ffd3a88..eac0f02eb4b 100644 --- a/apps/sim/lib/mothership/generated/protocol.ts +++ b/apps/sim/lib/mothership/generated/protocol.ts @@ -149,6 +149,7 @@ export const ENTITLEMENTS = { changelog: "changelog", workflowCode: "workflow-code", people: "people", + myActivity: "my-activity", } as const; export type Entitlement = (typeof ENTITLEMENTS)[keyof typeof ENTITLEMENTS]; export const Entitlements = z.array(z.string().min(1).max(64)).max(32); diff --git a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts index ab69d7932ee..ab968868a88 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -355,6 +355,123 @@ export const readDocumentInputSchema = z.object({ ), }) +/** Days one activity listing may span, about a quarter. */ +export const MAX_ACTIVITY_WINDOW_DAYS = 92 +/** Activity entries one page returns when the caller sets no topK. */ +export const DEFAULT_ACTIVITY_TOP_K = 25 + +/** The activity filters, shared by every surface; refine with {@link refineActivityWindow}. */ +export const listMyActivityInputFieldsSchema = z + .object({ + startDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + `Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.` + ), + endDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + 'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.' + ), + source: liveSearchProviderSchema + .optional() + .describe('One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.'), + topK: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe(`Maximum entries on this page: ${DEFAULT_ACTIVITY_TOP_K} by default.`), + cursor: z + .string() + .min(1) + .max(8000) + .optional() + .describe( + 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.' + ), + }) + .strict() + +/** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */ +export function refineActivityWindow( + input: { startDate?: string; endDate?: string }, + context: z.RefinementCtx +) { + if (!input.startDate || !input.endDate) return + const start = Date.parse(input.startDate) + const end = Date.parse(input.endDate) + if (start >= end) + context.addIssue({ code: 'custom', path: ['endDate'], message: 'endDate must be after startDate.' }) + else if (end - start > MAX_ACTIVITY_WINDOW_DAYS * 86_400_000) + context.addIssue({ + code: 'custom', + path: ['startDate'], + message: `The window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.`, + }) +} + +export const listMyActivityInputSchema = + listMyActivityInputFieldsSchema.superRefine(refineActivityWindow) + +/** + * How one source served a multi-source result. `not_connected` and `reconnect` carry `connect`: + * the provider to connect and the page where the caller connects it. + */ +export const liveSourceStatusSchema = z.object({ + source: liveSearchProviderSchema, + accountId: z.string().optional(), + displayName: z.string().optional(), + status: z.enum(['ok', 'partial', 'not_connected', 'reconnect', 'unsupported', 'failed']), + reason: z.enum(['rate_limited', 'timeout', 'unavailable']).optional(), + retryAfterSeconds: z.number().optional(), + message: z.string().optional(), + connect: z.object({ providerId: z.string(), url: z.string() }).optional(), +}) +export type LiveSourceStatus = z.output + +const activityItemSchema = z.object({ + /** Reads the item with read_document. */ + documentId: z.string(), + timestamp: z.string(), + source: liveSearchProviderSchema, + accountId: z.string(), + action: z.enum([ + 'created', + 'edited', + 'commented', + 'sent', + 'replied', + 'attended', + 'assigned', + 'mentioned', + ]), + title: z.string(), + url: z.string().nullable(), + container: z.string().optional(), + collaborators: z.array(z.string()), + snippet: z.string(), + /** The timestamp is the item's last update, possibly by someone else, not the person's action. */ + approximateTime: z.literal(true).optional(), +}) + +const listMyActivityResultSchema = z.object({ + window: z.object({ startDate: z.string(), endDate: z.string() }), + items: z.array(activityItemSchema), + /** More entries remain; continue with nextCursor. */ + truncated: z.boolean(), + nextCursor: z.string().optional(), + /** `complete` when every connected source that reports activity was read in full. */ + coverage: z.enum(['complete', 'partial']), + sources: z.array(liveSourceStatusSchema.extend({ itemCount: z.number().int().min(0) })), +}) +export type ListMyActivityResult = z.output + /** * Organization directory lookups. The bounds mirror the People page's search limits * (`lib/people/validation`) as literals, so the worker's generated copy stays standalone. @@ -461,6 +578,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_activity', + route: 'sim', + description: + 'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', + inputSchema: listMyActivityInputSchema, + }, { id: 'oauth_get_auth_link', route: 'sim', diff --git a/apps/sim/lib/mothership/tool-executor/executor.ts b/apps/sim/lib/mothership/tool-executor/executor.ts index 2e40b193b48..55dbb06d3b2 100644 --- a/apps/sim/lib/mothership/tool-executor/executor.ts +++ b/apps/sim/lib/mothership/tool-executor/executor.ts @@ -89,6 +89,7 @@ export async function executeTool( 'list_workspaces', 'search_workspace', 'read_document', + 'list_my_activity', 'search_sources', ...(params.scope !== 'workspace' ? ['settings'] : []), ] diff --git a/apps/sim/lib/mothership/tools/activity.ts b/apps/sim/lib/mothership/tools/activity.ts index 527d13ba3fb..9d5b8dffe88 100644 --- a/apps/sim/lib/mothership/tools/activity.ts +++ b/apps/sim/lib/mothership/tools/activity.ts @@ -409,6 +409,7 @@ export const TOOL_ACTIVITIES: Readonly = { list_workspaces: 'Listing workspaces', read_document: 'Reading document', search_people: 'Looking up people', + list_my_activity: 'Listing your activity', open_resource: 'Opening resource', ffmpeg: 'Processing media', diff --git a/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts b/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts new file mode 100644 index 00000000000..6062166dc69 --- /dev/null +++ b/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts @@ -0,0 +1,72 @@ +import { createLogger } from '@sim/logger' +import { z } from 'zod' +import { listMyActivityInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' +import { getValidationErrorMessage } from '@/lib/api/server/validation' +import { liveCitationId } from '@/lib/knowledge/search/citation' +import { + executeCopilotOrganizationKnowledgeUseCase, + messageForCopilotKnowledgeError, +} from '@/lib/mothership/application/execute-knowledge-use-case' +import type { BaseServerTool, ServerToolContext } from '@/lib/mothership/tools/server/base-tool' +import { listMyActivity } from '@/lib/sim-search/live/activity' + +const logger = createLogger('ListMyActivityTool') + +/** + * `list_my_activity` for the organization Assistant: the same use case and result as the Search + * MCP tool of that name, with a citation ID on each entry. + */ +export const listMyActivityServerTool: BaseServerTool = { + name: 'list_my_activity', + inputSchema: listMyActivityInputSchema, + async execute(raw, context?: ServerToolContext) { + if (!context?.organizationId) + return { + success: false, + message: 'Your activity is available only in organization conversations.', + } + try { + const input = listMyActivityInputSchema.parse(raw) + const registry = context.resolvedSecretTraceRegistry + if (!registry) throw new Error('Knowledge result provenance is unavailable') + const data = await executeCopilotOrganizationKnowledgeUseCase(context, listMyActivity, { + ...input, + organizationId: context.organizationId, + resultSecretRegistry: registry, + signal: context.abortSignal, + }) + const unconnected = data.sources.filter( + (source) => source.status === 'not_connected' || source.status === 'reconnect' + ) + return { + success: true, + message: [ + `Listed ${data.items.length} activity entries, newest first.`, + data.truncated ? 'More remain: call again with nextCursor and the same arguments.' : '', + unconnected.length + ? `Not read: ${unconnected.map((source) => source.source).join(', ')}. Offer to connect each with oauth_get_auth_link using its connect.providerId.` + : '', + 'Cite entries as {"id":""}.', + ] + .filter(Boolean) + .join(' '), + data: { + ...data, + items: data.items.map((item) => ({ + ...item, + citationId: liveCitationId(item.documentId), + citationUrl: item.url, + })), + }, + } + } catch (error) { + if (error instanceof z.ZodError) + return { + success: false, + message: getValidationErrorMessage(error, 'Invalid activity arguments'), + } + logger.error('Activity listing failed', { error }) + return { success: false, message: messageForCopilotKnowledgeError(error) } + } + }, +} diff --git a/apps/sim/lib/mothership/tools/server/router.ts b/apps/sim/lib/mothership/tools/server/router.ts index c62322249ab..090d48e7d52 100644 --- a/apps/sim/lib/mothership/tools/server/router.ts +++ b/apps/sim/lib/mothership/tools/server/router.ts @@ -26,6 +26,7 @@ import { workspaceFileServerTool } from '@/lib/mothership/tools/server/files/wor 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 { listMyActivityServerTool } from '@/lib/mothership/tools/server/knowledge/my-activity' import { searchPeopleServerTool } from '@/lib/mothership/tools/server/knowledge/people' import { readDocumentServerTool, @@ -83,6 +84,7 @@ const baseServerToolRegistry: Record = { [readDocumentServerTool.name]: readDocumentServerTool, [searchPeopleServerTool.name]: searchPeopleServerTool, [listMyChatHistoryServerTool.name]: listMyChatHistoryServerTool, + [listMyActivityServerTool.name]: listMyActivityServerTool, // 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), diff --git a/apps/sim/lib/sim-search/live/account-session.ts b/apps/sim/lib/sim-search/live/account-session.ts index c2396e0d1a6..de9e634b4ec 100644 --- a/apps/sim/lib/sim-search/live/account-session.ts +++ b/apps/sim/lib/sim-search/live/account-session.ts @@ -26,6 +26,7 @@ import { livePolicyFor, loadLiveSearchPolicies } from '@/lib/sim-search/live/pol import { LIVE_SEARCH_PROVIDER_CATALOG } from '@/lib/sim-search/live/provider-catalog' import { isSearchProviderEnabled } from '@/lib/sim-search/live/provider-rollout' import { + activityNativeProvider, previewNativeText, readNativeProvider, requiresEveryTerm, @@ -34,7 +35,13 @@ import { import { searchWithinPolicy } from '@/lib/sim-search/live/scoped-search' import { createLiveServiceSession } from '@/lib/sim-search/live/service-session' import { searchWithAnyTermFallback } from '@/lib/sim-search/live/term-fallback' -import type { NativeDocument, NativePage, NativeSearchInput } from '@/lib/sim-search/live/types' +import type { + NativeActivityInput, + NativeActivityPage, + NativeDocument, + NativePage, + NativeSearchInput, +} from '@/lib/sim-search/live/types' import { readZoomMcp, searchZoomMcp } from '@/lib/sim-search/live/zoom-mcp' type Reference = Pick< @@ -66,6 +73,11 @@ export interface LiveAccountSession { /** Releases the operation-owned provider transport after all reads and checks settle. */ close(): Promise search(input: NativeSearchInput): Promise + /** + * The connected person's own activity under the effective policy. Its entries are candidates: + * each is verified against the source boundary like a search result before it is returned. + */ + activity(input: Omit): Promise /** True only when the document is inside the source boundary and the member may read it. */ verify(document: Reference): Promise read(reference: Reference, filters?: WorkspaceSearchFilters): Promise @@ -263,6 +275,23 @@ export async function openLiveAccountSession( : searchOnce(request)) return connectionBinding ? { ...page, documents: page.documents.map(bind) } : page }, + async activity(request) { + if (admin || !client) + throw new NativeSearchError('unavailable', 'This source does not report activity.') + const page = await activityNativeProvider(provider, client, { + ...request, + policy: boundary.policy, + signal: request.signal ?? signal, + }) + if (!connectionBinding) return page + return { + ...page, + streams: page.streams.map((stream) => ({ + ...stream, + events: stream.events.map((event) => ({ ...event, document: bind(event.document) })), + })), + } + }, verify, async read(reference, filters) { if (admin) return admin.read(reference) diff --git a/apps/sim/lib/sim-search/live/activity-page.test.ts b/apps/sim/lib/sim-search/live/activity-page.test.ts new file mode 100644 index 00000000000..4beef5250af --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity-page.test.ts @@ -0,0 +1,221 @@ +/** + * @vitest-environment node + */ +import { compareStrings } from '@sim/utils/string' +import { describe, expect, it } from 'vitest' +import { + type AccountActivity, + type ActivityBound, + type ActivityEntry, + mergeActivityPage, + readActivityCursor, + writeActivityCursor, +} from '@/lib/sim-search/live/activity-page' + +const START = '2026-11-01T00:00:00.000Z' +const END = '2026-11-08T00:00:00.000Z' + +const at = (hour: number) => new Date(Date.parse(START) + hour * 3_600_000).toISOString() + +interface FakeAccount { + id: string + /** Items the provider holds, newest first, read `limit` at a time like a provider listing. */ + items: ActivityEntry[] + limit: number +} + +/** One provider read under a bound: items up to `end` (inclusive), newest first. */ +function read(account: FakeAccount, bound: ActivityBound): AccountActivity { + const inWindow = account.items.filter( + (item) => Date.parse(item.at) <= Date.parse(bound.end) && item.at >= START + ) + const page = inWindow.slice(0, account.limit) + return { + accountId: account.id, + bound, + read: true, + streams: [{ entries: page, more: inWindow.length > page.length, scannedTo: page.at(-1)?.at }], + } +} + +/** Pages through every account until no cursor remains, as a caller following nextCursor. */ +function pageThrough( + accounts: FakeAccount[], + topK: number, + fail: (accountId: string, page: number) => boolean = () => false +) { + let bounds: Record = Object.fromEntries( + accounts.map((account) => [account.id, { end: END, seen: [] }]) + ) + const pages: string[][] = [] + const stalled: string[] = [] + for (let page = 0; page < 50; page++) { + const result = mergeActivityPage( + accounts + .filter((account) => bounds[account.id]) + .map((account) => { + const bound = bounds[account.id] as ActivityBound + return fail(account.id, page) + ? { accountId: account.id, bound, read: false as const } + : read(account, bound) + }), + { start: START }, + topK + ) + pages.push(result.entries.map((entry) => `${entry.accountId}:${entry.key}`)) + stalled.push(...result.stalled) + if (!result.next) return { pages, stalled } + bounds = result.next + } + throw new Error('Paging did not end') +} + +function newestFirst(accounts: FakeAccount[]): string[] { + return accounts + .flatMap((account) => account.items.map((item) => ({ ...item, accountId: account.id }))) + .sort( + (left, right) => + Date.parse(right.at) - Date.parse(left.at) || + compareStrings(left.accountId, right.accountId) || + compareStrings(left.key, right.key) + ) + .map((entry) => `${entry.accountId}:${entry.key}`) +} + +describe('mergeActivityPage', () => { + it('returns every entry once and newest first when a listing is read a few items at a time', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 3, + items: [ + { at: at(150), key: 'c1' }, + { at: at(120), key: 'c2' }, + { at: at(120), key: 'c3' }, + { at: at(90), key: 'c4' }, + { at: at(40), key: 'c5' }, + { at: at(30), key: 'c6' }, + { at: at(2), key: 'c7' }, + ], + }, + { + id: 'mail', + limit: 50, + items: [ + { at: at(160), key: 'm1' }, + { at: at(120), key: 'm2' }, + { at: at(60), key: 'm3' }, + { at: at(35), key: 'm4' }, + { at: at(1), key: 'm5' }, + ], + }, + ] + for (const topK of [2, 10]) { + const { pages, stalled } = pageThrough(accounts, topK) + expect(pages.flat()).toEqual(newestFirst(accounts)) + expect(pages.every((page) => page.length <= topK)).toBe(true) + expect(stalled).toEqual([]) + } + }) + + it('retries an account that failed from where it stopped, losing none of its entries', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [1, 2, 3, 4, 5, 6].map((hour) => ({ at: at(170 - hour * 20), key: `c${hour}` })), + }, + { + id: 'mail', + limit: 50, + items: [1, 2, 3].map((hour) => ({ at: at(165 - hour * 30), key: `m${hour}` })), + }, + ] + const { pages } = pageThrough( + accounts, + 3, + (accountId, page) => accountId === 'mail' && page === 0 + ) + expect(new Set(pages.flat())).toEqual(new Set(newestFirst(accounts))) + expect(pages.flat()).toHaveLength(newestFirst(accounts).length) + }) + + it('ends without a continuation when only failed accounts would continue', () => { + const result = mergeActivityPage( + [{ accountId: 'mail', bound: { end: END, seen: [] }, read: false }], + { start: START }, + 10 + ) + expect(result.next).toBeUndefined() + }) + + it('stops an account holding more entries at one instant than a read returns, instead of looping', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [1, 2, 3, 4, 5].map((index) => ({ at: at(100), key: `c${index}` })), + }, + ] + const { pages, stalled } = pageThrough(accounts, 10) + expect(new Set(pages.flat()).size).toBe(pages.flat().length) + expect(stalled).toEqual(['chat']) + }) + + it('leaves out entries outside the window and those an earlier page returned at its bound', () => { + const result = mergeActivityPage( + [ + { + accountId: 'chat', + bound: { end: at(100), seen: ['c1'] }, + read: true, + streams: [ + { + entries: [ + { at: at(110), key: 'later' }, + { at: at(100), key: 'c1' }, + { at: at(100), key: 'c2' }, + { at: '2026-10-31T23:00:00.000Z', key: 'earlier' }, + ], + more: false, + }, + ], + }, + ], + { start: START }, + 10 + ) + expect(result.entries.map((entry) => entry.key)).toEqual(['c2']) + expect(result.next).toBeUndefined() + }) +}) + +describe('activity cursors', () => { + const cursor = { + v: 1 as const, + scope: 'A'.repeat(22), + start: START, + end: END, + accounts: { chat: { end: at(50), seen: ['c1'] } }, + } + + it('reads back a cursor minted for the same caller and request', () => { + expect( + readActivityCursor(writeActivityCursor(cursor, 'secret'), cursor.scope, 'secret') + ).toEqual(cursor) + }) + + it('refuses a cursor minted for another caller or request', () => { + const value = writeActivityCursor(cursor, 'secret') + expect(readActivityCursor(value, 'B'.repeat(22), 'secret')).toBeUndefined() + }) + + it('refuses a cursor whose bounds were altered', () => { + const decoded = JSON.parse( + Buffer.from(writeActivityCursor(cursor, 'secret'), 'base64url').toString('utf8') + ) + decoded.accounts.chat.end = END + const altered = Buffer.from(JSON.stringify(decoded)).toString('base64url') + expect(readActivityCursor(altered, cursor.scope, 'secret')).toBeUndefined() + }) +}) diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts new file mode 100644 index 00000000000..8e761eb6bc8 --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -0,0 +1,210 @@ +import { safeCompare } from '@sim/security/compare' +import { hmacSha256Hex } from '@sim/security/hmac' +import { canonicalJson } from '@sim/utils/object' +import { compareStrings } from '@sim/utils/string' +import { z } from 'zod' + +/** People named on one activity entry, besides the person whose activity it is. */ +export const MAX_ACTIVITY_COLLABORATORS = 10 +/** + * Entries one account may have returned at the instant a page stopped. A continuation skips + * them; an account with more than this many entries at one instant stops there. + */ +const MAX_SEEN_AT_BOUND = 50 + +/** The earliest of the valid instants, as ISO, or undefined when none parses. */ +export function oldestInstant(values: readonly (string | undefined)[]): string | undefined { + let oldest: number | undefined + for (const value of values) { + const time = Date.parse(value ?? '') + if (Number.isFinite(time) && (oldest === undefined || time < oldest)) oldest = time + } + return oldest === undefined ? undefined : new Date(oldest).toISOString() +} + +/** + * Where one account's next page resumes: its streams are read again up to `end` (inclusive), and + * the entries at exactly `end` that an earlier page returned, named by `seen`, are skipped. + */ +export interface ActivityBound { + end: string + seen: string[] +} + +/** One activity entry ready to merge: when it happened and the key naming it within its account. */ +export interface ActivityEntry { + at: string + key: string +} + +interface ActivityStreamRead { + entries: E[] + more: boolean + scannedTo?: string +} + +/** One account's part of a page: the bound it was read with and what it returned. */ +export type AccountActivity = { + accountId: string + bound: ActivityBound +} & ({ read: true; streams: ActivityStreamRead[] } | { read: false }) + +export interface ActivityPageResult { + /** Newest first. */ + entries: (E & { accountId: string })[] + /** Each continuing account's bound, or undefined when no page follows. */ + next?: Record + /** Accounts that stopped without reading all their activity, for partial coverage. */ + stalled: string[] +} + +function instant(value: string): number { + return Date.parse(value) +} + +function sameBound(left: ActivityBound, right: ActivityBound): boolean { + return ( + instant(left.end) === instant(right.end) && + left.seen.length === right.seen.length && + left.seen.every((key) => right.seen.includes(key)) + ) +} + +/** + * Merges one page of several accounts' activity, newest first, without dropping anything a + * later page could not reach. Every stream is read newest first, so its unread items sort at or + * before the oldest instant it scanned; past the latest such instant of any stream with more, an + * entry might be preceded by one not yet read. Entries before that horizon wait for the next + * page, which reads every account again up to where this page stopped. An account that failed + * keeps its bound, so the next page retries it from there; a page with only failed accounts left + * has no continuation. + */ +export function mergeActivityPage( + accounts: readonly AccountActivity[], + window: { start: string }, + topK: number +): ActivityPageResult { + const start = instant(window.start) + let horizon: number | undefined + const pending: (E & { accountId: string })[] = [] + const unfinished = new Set() + for (const account of accounts) { + if (!account.read) continue + const end = instant(account.bound.end) + const seen = new Set(account.bound.seen) + const keys = new Set() + for (const stream of account.streams) { + if (stream.more) { + const scanned = stream.scannedTo ? instant(stream.scannedTo) : end + const floor = Number.isFinite(scanned) ? Math.min(scanned, end) : end + horizon = horizon === undefined ? floor : Math.max(horizon, floor) + unfinished.add(account.accountId) + } + for (const entry of stream.entries) { + const at = instant(entry.at) + if (!Number.isFinite(at) || at < start || at > end) continue + if (at === end && seen.has(entry.key)) continue + if (keys.has(entry.key)) continue + keys.add(entry.key) + pending.push({ ...entry, accountId: account.accountId }) + } + } + } + pending.sort( + (left, right) => + instant(right.at) - instant(left.at) || + compareStrings(left.accountId, right.accountId) || + compareStrings(left.key, right.key) + ) + const ready = + horizon === undefined ? pending : pending.filter((entry) => instant(entry.at) >= horizon) + const entries = ready.slice(0, topK) + const cut = ready.length > topK + const last = entries.at(-1) + const resume = cut && last ? instant(last.at) : horizon + const next: Record = {} + const stalled: string[] = [] + const continuing: string[] = [] + let progressed = false + for (const account of accounts) { + if (!account.read) { + next[account.accountId] = account.bound + continue + } + const remaining = pending.some( + (entry) => entry.accountId === account.accountId && !entries.includes(entry) + ) + if (resume === undefined || (!unfinished.has(account.accountId) && !remaining)) continue + const resumeAt = new Date(resume).toISOString() + const returnedAtResume = entries + .filter((entry) => entry.accountId === account.accountId && instant(entry.at) === resume) + .map((entry) => entry.key) + const bound: ActivityBound = { + end: resumeAt, + seen: [ + ...new Set([ + ...(instant(account.bound.end) === resume ? account.bound.seen : []), + ...returnedAtResume, + ]), + ], + } + if (bound.seen.length > MAX_SEEN_AT_BOUND) { + stalled.push(account.accountId) + continue + } + if (!sameBound(bound, account.bound)) progressed = true + next[account.accountId] = bound + continuing.push(account.accountId) + } + /** A page that moves no account's bound would be read again unchanged, so it ends here. */ + if (continuing.length && !progressed) return { entries, stalled: [...stalled, ...continuing] } + return { entries, ...(continuing.length ? { next } : {}), stalled } +} + +const boundSchema = z.object({ + end: z.string().datetime({ offset: true }), + seen: z.array(z.string().max(32)).max(MAX_SEEN_AT_BOUND), +}) +const cursorSchema = z + .object({ + v: z.literal(1), + /** Fingerprint of the caller and the request the cursor continues. */ + scope: z.string().regex(/^[A-Za-z0-9_-]{22}$/), + start: z.string().datetime({ offset: true }), + end: z.string().datetime({ offset: true }), + accounts: z.record(z.string().max(200), boundSchema), + }) + .strict() +export type ActivityCursor = z.output +const signedCursorSchema = cursorSchema.extend({ signature: z.string().regex(/^[a-f0-9]{64}$/) }) + +function cursorSignature(cursor: ActivityCursor, secret: string): string { + return hmacSha256Hex(`live-activity-cursor:${canonicalJson(cursor)}`, secret) +} + +/** A signed, opaque continuation of one activity listing. */ +export function writeActivityCursor(cursor: ActivityCursor, secret: string): string { + return Buffer.from( + JSON.stringify({ ...cursor, signature: cursorSignature(cursor, secret) }) + ).toString('base64url') +} + +/** + * The continuation a cursor names, or undefined when it is malformed, altered, or minted for + * another caller or request than `scope`. + */ +export function readActivityCursor( + value: string, + scope: string, + secret: string +): ActivityCursor | undefined { + try { + const { signature, ...cursor } = signedCursorSchema.parse( + JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) + ) + if (!safeCompare(signature, cursorSignature(cursor, secret))) return undefined + return cursor.scope === scope ? cursor : undefined + } catch { + return undefined + } +} diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts new file mode 100644 index 00000000000..09f6f93ef7f --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -0,0 +1,247 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it, vi } from 'vitest' +import { atlassianActivity } from '@/lib/sim-search/live/atlassian' +import { calendarActivity, gmailActivity } from '@/lib/sim-search/live/google' +import { slackActivity } from '@/lib/sim-search/live/slack' +import type { NativeActivityInput, NativeClient } from '@/lib/sim-search/live/types' + +const WINDOW: NativeActivityInput = { + start: '2026-11-01T00:00:00.000Z', + end: '2026-11-08T00:00:00.000Z', + limit: 20, + scopes: ['search:read.public'], +} + +/** Answers the paths a test names; any other request fails the test. */ +function client(answer: (path: string, options?: { query?: Record }) => unknown) { + return { + json: vi.fn(async (path: string, options?: { query?: Record }) => { + const value = answer(path, options) + if (value === undefined) throw new Error(`Unexpected request: ${path}`) + return value + }), + text: vi.fn(), + bytes: vi.fn(), + } satisfies NativeClient +} + +describe('Slack activity', () => { + it('names a message inside a thread it did not start a reply, and leaves out file hits', async () => { + const api = client((path) => + path === '/api/assistant.search.context' + ? { + ok: true, + results: { + messages: [ + { + message_ts: '1762300000.000200', + thread_ts: '1762290000.000100', + channel_id: 'C1', + channel_name: 'eng', + permalink: 'https://acme.slack.com/archives/C1/p1', + content: 'Looks good', + }, + { + message_ts: '1762200000.000100', + thread_ts: '1762200000.000100', + channel_id: 'C1', + channel_name: 'eng', + permalink: 'https://acme.slack.com/archives/C1/p2', + content: 'Starting the deploy', + }, + ], + files: [{ file_id: 'F1', title: 'notes', date_updated: 1762400000 }], + }, + response_metadata: { next_cursor: 'next' }, + } + : undefined + ) + const page = await slackActivity(api, WINDOW) + expect(page.streams).toHaveLength(1) + const [stream] = page.streams + expect(stream?.events.map((event) => [event.document.id, event.action])).toEqual([ + ['1762300000.000200', 'replied'], + ['1762200000.000100', 'sent'], + ]) + expect(stream).toMatchObject({ more: true, scannedTo: new Date(1762200000000).toISOString() }) + }) +}) + +describe('Gmail activity', () => { + it('names mail answering another a reply and lists its recipients', async () => { + const message = (id: string, headers: Record, internalDate: number) => ({ + id, + internalDate: String(internalDate), + snippet: 'Hi', + payload: { headers: Object.entries(headers).map(([name, value]) => ({ name, value })) }, + }) + const api = client((path) => { + if (path === '/gmail/v1/users/me/messages') return { messages: [{ id: 'a' }, { id: 'b' }] } + if (path === '/gmail/v1/users/me/messages/a') + return message( + 'a', + { + Subject: 'Re: plan', + To: 'Ann Lee , "Park, Bo" ', + Cc: 'cy@example.com', + 'In-Reply-To': '', + }, + 1762300000000 + ) + if (path === '/gmail/v1/users/me/messages/b') + return message('b', { Subject: 'Plan', To: 'ann@example.com' }, 1762200000000) + return undefined + }) + const [stream] = (await gmailActivity(api, WINDOW)).streams + expect( + stream?.events.map((event) => [event.document.id, event.action, event.collaborators]) + ).toEqual([ + ['a', 'replied', ['Ann Lee', 'Park, Bo', 'cy@example.com']], + ['b', 'sent', ['ann@example.com']], + ]) + }) +}) + +describe('Calendar activity', () => { + it('counts only meetings the member organized or accepted with someone else, newest first', async () => { + const self = (responseStatus: string) => ({ email: 'me@x.com', self: true, responseStatus }) + const other = { email: 'ann@x.com', displayName: 'Ann' } + const event = (id: string, day: number, extra: Record) => ({ + id, + summary: id, + start: { dateTime: `2026-11-0${day}T15:00:00Z` }, + end: { dateTime: `2026-11-0${day}T16:00:00Z` }, + ...extra, + }) + const api = client((path) => + path === '/calendar/v3/calendars/primary/events' + ? { + items: [ + event('accepted', 2, { attendees: [self('accepted'), other] }), + event('declined', 3, { attendees: [self('declined'), other] }), + event('unanswered', 3, { attendees: [self('needsAction'), other] }), + event('alone', 4, { organizer: { self: true }, attendees: [self('accepted')] }), + event('focus', 4, { + eventType: 'focusTime', + organizer: { self: true }, + attendees: [self('accepted'), other], + }), + event('organized', 5, { organizer: { self: true }, attendees: [other] }), + ], + } + : undefined + ) + const [stream] = (await calendarActivity(api, WINDOW)).streams + expect(stream?.events.map((entry) => [entry.document.id, entry.collaborators])).toEqual([ + ['organized', ['Ann']], + ['accepted', ['Ann']], + ]) + expect(stream?.events.every((entry) => entry.action === 'attended')).toBe(true) + }) +}) + +describe('Atlassian activity', () => { + const site = { id: 'cloud', url: 'https://acme.atlassian.net' } + + it('marks a page whose last edit is someone else’s approximate, and reads a comment’s page', async () => { + const api = client((path, options) => { + if (path === '/oauth/token/accessible-resources') return [site] + if (path === '/ex/confluence/cloud/wiki/rest/api/user/current') return { accountId: 'me' } + if (path !== '/ex/confluence/cloud/wiki/rest/api/search') return undefined + const cql = String(options?.query?.cql) + return cql.startsWith('type = comment') + ? { + results: [ + { + content: { + id: 'c1', + type: 'comment', + container: { id: '42', type: 'page', title: 'Runbook' }, + history: { createdDate: '2026-11-05T10:00:00.000Z' }, + _links: { webui: '/spaces/ENG/pages/42?focusedCommentId=c1' }, + }, + excerpt: 'Agreed', + }, + ], + _links: {}, + } + : { + results: [ + { + content: { + id: '7', + type: 'page', + title: 'Plan', + version: { + when: '2026-11-06T10:00:00.000Z', + number: 3, + by: { accountId: 'ann', displayName: 'Ann' }, + }, + }, + }, + { + content: { + id: '8', + type: 'page', + title: 'Notes', + version: { + when: '2026-11-04T10:00:00.000Z', + number: 1, + by: { accountId: 'me', displayName: 'Me' }, + }, + }, + }, + ], + _links: { next: '/wiki/rest/api/search?cursor=abc' }, + } + }) + const [pages, comments] = (await atlassianActivity(api, 'confluence', WINDOW)).streams + expect( + pages?.events.map((event) => [event.document.id, event.action, event.approximateTime]) + ).toEqual([ + ['7', 'edited', true], + ['8', 'created', undefined], + ]) + expect(pages).toMatchObject({ more: true, scannedTo: '2026-11-04T10:00:00.000Z' }) + expect(comments?.events).toEqual([ + expect.objectContaining({ + action: 'commented', + document: expect.objectContaining({ id: '42', kind: 'page', title: 'Runbook' }), + }), + ]) + }) + + it('reports an assigned Jira issue at its last update, marked approximate', async () => { + const api = client((path, options) => { + if (path === '/oauth/token/accessible-resources') return [site] + if (path !== '/ex/jira/cloud/rest/api/3/search/jql') return undefined + const jql = String((options as { body?: { jql?: string } } | undefined)?.body?.jql) + return jql.includes('assignee = currentUser()') + ? { + issues: [ + { + key: 'ENG-2', + fields: { + summary: 'Fix login', + updated: '2026-11-06T09:00:00.000+0000', + assignee: { accountId: 'me', displayName: 'Me' }, + reporter: { accountId: 'ann', displayName: 'Ann' }, + }, + }, + ], + } + : { issues: [] } + }) + const streams = (await atlassianActivity(api, 'jira', WINDOW)).streams + expect(streams.flatMap((stream) => stream.events)).toEqual([ + expect.objectContaining({ + action: 'assigned', + at: '2026-11-06T09:00:00.000Z', + approximateTime: true, + collaborators: ['Ann'], + }), + ]) + }) +}) diff --git a/apps/sim/lib/sim-search/live/activity.integration.ts b/apps/sim/lib/sim-search/live/activity.integration.ts new file mode 100644 index 00000000000..9cb3f70cf27 --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity.integration.ts @@ -0,0 +1,111 @@ +/** + * `list_my_activity` for the organization Assistant against real Postgres: the copilot delegation + * bound to the member's own chat, the organization's source approvals and the member's own + * connections decide which sources are read and which the member is asked to connect. + */ +import { db } from '@sim/db' +import { + copilotChats, + member, + organization, + organizationSearchIntegration, + user, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, expect, it, vi } from 'vitest' +import { listMyActivityServerTool } from '@/lib/mothership/tools/server/knowledge/my-activity' +import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' + +vi.hoisted(() => vi.stubEnv('MY_ACTIVITY', 'true')) + +const org = generateId() +const readerId = generateId() +const otherId = generateId() +const readerChat = generateId() +const otherChat = generateId() + +function turn(userId: string, chatId: string) { + return { + userId, + organizationId: org, + chatId, + toolCallId: generateId(), + copilotToolExecution: true, + requestMode: 'assistant', + resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry(), + } +} + +beforeAll(async () => { + await db.insert(organization).values({ + id: org, + slug: org, + name: 'Assistant activity fixture', + createdAt: new Date(), + }) + await db.insert(user).values( + [readerId, otherId].map((id) => ({ + id, + name: 'Activity reader', + email: `${id}@example.test`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + })) + ) + await db.insert(member).values([ + { id: generateId(), organizationId: org, userId: readerId, role: 'member' }, + { id: generateId(), organizationId: org, userId: otherId, role: 'member' }, + ]) + await db.insert(copilotChats).values([ + { id: readerChat, userId: readerId, organizationId: org, type: 'mothership' }, + { id: otherChat, userId: otherId, organizationId: org, type: 'mothership' }, + ]) + await db.insert(organizationSearchIntegration).values([ + { organizationId: org, connectorType: 'slack', approved: true }, + { organizationId: org, connectorType: 'gmail', approved: true }, + { organizationId: org, connectorType: 'jira', approved: false }, + { organizationId: org, connectorType: 'notion', approved: true }, + ]) +}) + +afterAll(async () => { + await db.delete(organization).where(eq(organization.id, org)) + await db.delete(user).where(inArray(user.id, [readerId, otherId])) + vi.unstubAllEnvs() +}) + +it('asks the member to connect each approved source that reports activity, and only those', async () => { + const result = await listMyActivityServerTool.execute({}, turn(readerId, readerChat)) + expect(result).toMatchObject({ + success: true, + data: { items: [], truncated: false, coverage: 'complete' }, + }) + const data = (result as { data: { sources: Record[] } }).data + expect(data.sources.map((source) => [source.source, source.status])).toEqual([ + ['gmail', 'not_connected'], + ['slack', 'not_connected'], + ]) + expect(data.sources[0]).toMatchObject({ + connect: { providerId: 'google-email', url: expect.stringContaining(`/${org}/`) }, + }) + expect((result as { message: string }).message).toContain('oauth_get_auth_link') +}) + +it('refuses a delegation naming another member’s chat', async () => { + const result = await listMyActivityServerTool.execute({}, turn(readerId, otherChat)) + expect(result).toMatchObject({ success: false }) +}) + +it('refuses a window longer than a quarter and a cursor it did not mint', async () => { + expect( + await listMyActivityServerTool.execute( + { startDate: '2026-01-01T00:00:00Z', endDate: '2026-06-01T00:00:00Z' }, + turn(readerId, readerChat) + ) + ).toMatchObject({ success: false, message: expect.stringContaining('92 days') }) + expect( + await listMyActivityServerTool.execute({ cursor: 'not-a-cursor' }, turn(readerId, readerChat)) + ).toMatchObject({ success: false, message: expect.stringContaining('Invalid cursor') }) +}) diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts new file mode 100644 index 00000000000..f52f424229e --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -0,0 +1,444 @@ +import { requirePrincipalSubjectUserId } from '@sim/auth/principal' +import { createLogger } from '@sim/logger' +import { canonicalJson } from '@sim/utils/object' +import { truncateAtCodePoint } from '@sim/utils/string' +import { + DEFAULT_ACTIVITY_TOP_K, + type ListMyActivityResult, + type LiveSearchProvider, + type LiveSourceStatus, + listMyActivityInputSchema, + MAX_ACTIVITY_WINDOW_DAYS, +} from '@/lib/api/contracts/mothership-assistant-tools' +import { fingerprint, instantScopePart } from '@/lib/api/cursor-binding' +import { admitContent } from '@/lib/core/application' +import { env } from '@/lib/core/config/env' +import { isFeatureEnabled } from '@/lib/core/config/feature-flags' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { resourceScopeFromOwner, resourceScopeKey } from '@/lib/core/resource-scope' +import { createPinnedConnectionPool } from '@/lib/core/security/input-validation.server' +import { createConcurrencyLimit, waitWithAbort } from '@/lib/core/utils/concurrency' +import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability' +import { defineAuthorizedKnowledgeUseCase } from '@/lib/knowledge/application/authorized-knowledge-use-case' +import { resolveKnowledgeOrganizationContext } from '@/lib/knowledge/application/contexts' +import { knowledgeOperations } from '@/lib/knowledge/application/operations' +import { listOrganizationSearchApprovals } from '@/lib/knowledge/search/integration-policy' +import { isKnowledgeSourceUrl } from '@/lib/knowledge/search/source-url' +import { openLiveAccountSession } from '@/lib/sim-search/live/account-session' +import { listLiveAccounts, resolveListedLiveAccount } from '@/lib/sim-search/live/accounts' +import { + type AccountActivity, + type ActivityBound, + type ActivityEntry, + mergeActivityPage, + readActivityCursor, + writeActivityCursor, +} from '@/lib/sim-search/live/activity-page' +import { + candidateFor, + compareAccounts, + type LiveCandidate, + liveIntegrationsUrl, + safeContent, + verifyCandidates, +} from '@/lib/sim-search/live/application' +import { NativeSearchError } from '@/lib/sim-search/live/http' +import { loadLiveSearchPolicies } from '@/lib/sim-search/live/policy-store' +import { + LIVE_SEARCH_PROVIDER_CATALOG, + LIVE_SEARCH_PROVIDER_IDS, +} from '@/lib/sim-search/live/provider-catalog' +import { supportsActivity } from '@/lib/sim-search/live/providers' +import { liveReferenceOwner } from '@/lib/sim-search/live/reference' +import type { LiveAccount, NativeActivityEvent } from '@/lib/sim-search/live/types' +import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' + +const logger = createLogger('LiveActivity') + +const DAY_MS = 86_400_000 +const DEFAULT_WINDOW_DAYS = 7 +/** Accounts one call reads, as one search does. */ +const MAX_ACTIVITY_ACCOUNTS = 20 +/** Accounts resolving their credential and opening their session at once, as for search. */ +const ACCOUNT_OPEN_CONCURRENCY = 6 +/** Milliseconds a whole call may take, and one account once it gets a slot, as for search. */ +const ACTIVITY_DEADLINE_MS = 20_000 +const ACCOUNT_DEADLINE_MS = 12_000 +/** Characters of each entry's text the caller sees; read_document returns the rest. */ +const SNIPPET_CHARACTERS = 300 +/** Raw items each provider listing reads per page; at least a page's worth of entries. */ +const MIN_STREAM_ITEMS = 20 + +export interface ListMyActivityInput { + organizationId: string + startDate?: string + endDate?: string + source?: LiveSearchProvider + topK?: number + cursor?: string + signal?: AbortSignal + resultSecretRegistry?: ResolvedSecretTraceRegistry +} + +export function isMyActivityEnabled(organizationId: string): Promise { + return isFeatureEnabled('my-activity', { orgId: organizationId }) +} + +const INVALID_CURSOR_MESSAGE = + 'Invalid cursor. Continue with the same startDate, endDate, source and topK, or start again without a cursor.' + +/** The window a first page reads: the requested bounds, defaulted and clamped to now. */ +function resolveWindow(input: ListMyActivityInput, now: number) { + const requestedEnd = input.endDate ? Date.parse(input.endDate) : now + const end = Math.min(requestedEnd, now) + const start = input.startDate ? Date.parse(input.startDate) : end - DEFAULT_WINDOW_DAYS * DAY_MS + if (!Number.isFinite(start) || !Number.isFinite(end)) + throw new OrchestrationError('validation', 'startDate and endDate must be ISO datetimes') + if (start >= end) + throw new OrchestrationError( + 'validation', + input.startDate && start >= now + ? 'startDate is in the future; activity covers only what already happened.' + : 'endDate must be after startDate.' + ) + if (end - start > MAX_ACTIVITY_WINDOW_DAYS * DAY_MS) + throw new OrchestrationError( + 'validation', + `The window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.` + ) + return { start: new Date(start).toISOString(), end: new Date(end).toISOString() } +} + +/** The connection a source's status asks the caller to make. */ +function connectHint(provider: LiveSearchProvider, organizationId: string) { + return { + providerId: LIVE_SEARCH_PROVIDER_CATALOG[provider].credentialProviderIds[0] ?? provider, + url: liveIntegrationsUrl({ organizationId }), + } +} + +/** An account's own activity as entries ready to merge, keyed within the account. */ +interface Entry extends ActivityEntry { + event: NativeActivityEvent + documentId: string +} + +/** The seen-key of an entry: short and opaque, since a cursor carries it. */ +function entryKey(event: NativeActivityEvent): string { + return fingerprint( + JSON.stringify([event.action, event.document.dedupeKey ?? event.document.id]) + ).slice(0, 16) +} + +type AccountRead = + | { + account: LiveAccount + ok: true + streams: { entries: Entry[]; more: boolean; scannedTo?: string }[] + partial: boolean + message?: string + } + | { account: LiveAccount; ok: false; error: NativeSearchError } + +function failureStatus( + account: LiveAccount, + error: NativeSearchError, + organizationId: string +): LiveSourceStatus { + const base = { + source: account.provider, + accountId: account.id, + displayName: account.displayName, + message: error.message, + } + if (error.status === 'reconnect') + return { ...base, status: 'reconnect', connect: connectHint(account.provider, organizationId) } + return { + ...base, + status: 'failed', + reason: error.status, + ...(error.retryAfterSeconds === undefined + ? {} + : { retryAfterSeconds: error.retryAfterSeconds }), + } +} + +/** + * The caller's own activity across the sources they connected in this organization, newest + * first, read live from each provider with the caller's own connection. Always the person the + * principal represents; a principal without one is refused. + */ +export const listMyActivity = defineAuthorizedKnowledgeUseCase({ + operation: knowledgeOperations.listActivity, + resolveContext: ({ input }: { input: ListMyActivityInput }) => + resolveKnowledgeOrganizationContext({ organizationId: input.organizationId }), + async execute({ principal, input }): Promise { + const userId = requirePrincipalSubjectUserId(principal) + /** Live provider results carry no stored provenance; they are projected through `safeContent`. */ + await admitContent(principal, []) + const { organizationId } = input + await requireOrganizationSearchAvailable(organizationId) + if (!(await isMyActivityEnabled(organizationId))) + throw new OrchestrationError( + 'forbidden', + 'Activity listing is not enabled for this organization' + ) + const parsed = listMyActivityInputSchema.parse({ + startDate: input.startDate, + endDate: input.endDate, + source: input.source, + topK: input.topK, + cursor: input.cursor, + }) + const topK = parsed.topK ?? DEFAULT_ACTIVITY_TOP_K + const owner = { organizationId } + const referenceOwner = liveReferenceOwner( + userId, + resourceScopeKey(resourceScopeFromOwner(owner)) + ) + const scope = fingerprint( + canonicalJson({ + user: userId, + organizationId, + startDate: instantScopePart(parsed.startDate), + endDate: instantScopePart(parsed.endDate), + source: parsed.source, + topK, + }) + ) + const cursor = parsed.cursor + ? readActivityCursor(parsed.cursor, scope, env.BETTER_AUTH_SECRET) + : undefined + if (parsed.cursor && !cursor) throw new OrchestrationError('validation', INVALID_CURSOR_MESSAGE) + const window = cursor ?? resolveWindow(parsed, Date.now()) + input.signal?.throwIfAborted() + + const [policies, connected, approvals] = await Promise.all([ + loadLiveSearchPolicies(owner), + listLiveAccounts(owner, userId), + listOrganizationSearchApprovals(organizationId), + ]) + const accounts = connected + .filter((account) => !parsed.source || account.provider === parsed.source) + .sort(compareAccounts) + const statuses: (LiveSourceStatus & { itemCount: number })[] = [] + if (!cursor) + for (const provider of LIVE_SEARCH_PROVIDER_IDS) { + if (parsed.source && provider !== parsed.source) continue + if (!supportsActivity(provider) || approvals.get(provider) !== true) continue + if (accounts.some((account) => account.provider === provider)) continue + statuses.push({ + source: provider, + status: 'not_connected', + message: `Connect your ${provider} account to include it.`, + connect: connectHint(provider, organizationId), + itemCount: 0, + }) + } + const readable = (account: LiveAccount) => + supportsActivity(account.provider) && + account.type !== 'managed_mcp' && + account.type !== 'admin_source' + if (!cursor) + for (const account of accounts.filter((candidate) => !readable(candidate))) + statuses.push({ + source: account.provider, + accountId: account.id, + displayName: account.displayName, + status: 'unsupported', + message: 'This source does not report activity yet.', + itemCount: 0, + }) + const eligible = accounts.filter(readable) + const selected = cursor + ? eligible.filter((account) => cursor.accounts[account.id]) + : eligible.slice(0, MAX_ACTIVITY_ACCOUNTS) + if (!cursor) + for (const account of eligible.slice(MAX_ACTIVITY_ACCOUNTS)) + statuses.push({ + source: account.provider, + accountId: account.id, + displayName: account.displayName, + status: 'failed', + reason: 'unavailable', + message: `One call reads at most ${MAX_ACTIVITY_ACCOUNTS} accounts. Pass source to read this one.`, + itemCount: 0, + }) + const boundOf = (account: LiveAccount): ActivityBound => + cursor?.accounts[account.id] ?? { end: window.end, seen: [] } + + const deadline = AbortSignal.timeout(ACTIVITY_DEADLINE_MS) + const callSignal = input.signal ? AbortSignal.any([input.signal, deadline]) : deadline + const opening = createConcurrencyLimit(ACCOUNT_OPEN_CONCURRENCY) + const pool = createPinnedConnectionPool() + const streamItems = Math.max(MIN_STREAM_ITEMS, topK) + const readAccount = async (account: LiveAccount): Promise => { + const settled = new AbortController() + const signal = AbortSignal.any([ + callSignal, + settled.signal, + AbortSignal.timeout(ACCOUNT_DEADLINE_MS), + ]) + let session: Awaited> | undefined + try { + session = await opening(async () => { + const resolved = await waitWithAbort( + resolveListedLiveAccount(owner, userId, account, signal), + signal + ) + return waitWithAbort( + openLiveAccountSession({ owner, userId, resolved, policies, signal, pool }), + signal + ) + }) + const bound = boundOf(account) + const page = await session.activity({ + start: window.start, + end: bound.end, + limit: streamItems, + scopes: account.scopes, + signal, + }) + const events = page.streams.flatMap((stream) => stream.events) + const candidates = events.map((event) => + candidateFor(event.document, account, referenceOwner) + ) + const verification = await verifyCandidates(session, candidates) + const permitted = new Set(verification.permitted) + const allowed = new Map() + events.forEach((event, index) => { + const candidate = candidates[index] + if (candidate && permitted.has(candidate)) allowed.set(event, candidate.documentId) + }) + return { + account, + ok: true, + partial: Boolean(page.partial || verification.unverified || session.servicePartial), + message: page.message, + streams: page.streams.map((stream) => ({ + more: stream.more, + scannedTo: stream.scannedTo, + entries: stream.events.flatMap((event): Entry[] => { + const documentId = allowed.get(event) + return documentId ? [{ at: event.at, key: entryKey(event), event, documentId }] : [] + }), + })), + } + } catch (error) { + input.signal?.throwIfAborted() + if (!(error instanceof NativeSearchError)) + logger.warn('Activity listing failed for an account', { + provider: account.provider, + error: error instanceof Error ? error.message : String(error), + }) + return { + account, + ok: false, + error: + error instanceof NativeSearchError + ? error + : signal.aborted + ? new NativeSearchError('timeout', 'This source did not answer in time. Try again.') + : new NativeSearchError( + 'unavailable', + 'This source could not be read. Check the connection and try again.' + ), + } + } finally { + settled.abort() + await session?.close() + } + } + let reads: AccountRead[] + try { + reads = await Promise.all(selected.map(readAccount)) + } finally { + pool.destroy() + } + input.signal?.throwIfAborted() + + const merged = mergeActivityPage( + reads.map( + (read): AccountActivity => + read.ok + ? { + accountId: read.account.id, + bound: boundOf(read.account), + read: true, + streams: read.streams, + } + : { accountId: read.account.id, bound: boundOf(read.account), read: false } + ), + window, + topK + ) + const registry = input.resultSecretRegistry + const byId = new Map(selected.map((account) => [account.id, account])) + const items = merged.entries.flatMap(({ event, documentId, accountId }) => { + const account = byId.get(accountId) + if (!account) return [] + const { document } = event + return [ + { + documentId, + timestamp: new Date(event.at).toISOString(), + source: account.provider, + accountId, + action: event.action, + title: safeContent(document.title, registry), + url: isKnowledgeSourceUrl(document.url) ? document.url : null, + ...(document.containerName && document.containerName !== document.title + ? { container: safeContent(document.containerName, registry) } + : {}), + collaborators: event.collaborators.map((name) => safeContent(name, registry)), + snippet: truncateAtCodePoint( + safeContent(document.content, registry).trim(), + SNIPPET_CHARACTERS + ), + ...(event.approximateTime ? { approximateTime: true as const } : {}), + }, + ] + }) + const stalled = new Set(merged.stalled) + for (const read of reads) { + if (!read.ok) { + statuses.push({ + ...failureStatus(read.account, read.error, organizationId), + itemCount: 0, + }) + continue + } + const partial = read.partial || stalled.has(read.account.id) + statuses.push({ + source: read.account.provider, + accountId: read.account.id, + displayName: read.account.displayName, + status: partial ? 'partial' : 'ok', + ...(stalled.has(read.account.id) + ? { message: 'More activity at one instant than a page can return; later pages skip it.' } + : read.partial && read.message + ? { message: read.message } + : {}), + itemCount: items.filter((item) => item.accountId === read.account.id).length, + }) + } + const nextCursor = merged.next + ? writeActivityCursor( + { v: 1, scope, start: window.start, end: window.end, accounts: merged.next }, + env.BETTER_AUTH_SECRET + ) + : undefined + return { + window: { startDate: window.start, endDate: window.end }, + items, + truncated: Boolean(nextCursor), + ...(nextCursor ? { nextCursor } : {}), + coverage: statuses.some((status) => + ['partial', 'reconnect', 'failed'].includes(status.status) + ) + ? 'partial' + : 'complete', + sources: statuses, + } + }, +}) diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index 6198f8365a0..3dd8d1cd07d 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -171,7 +171,7 @@ interface LiveSearchOptions { } export type LiveSearchInput = ResourceOwner & LiveSearchOptions -function safeContent(content: string, registry?: ResolvedSecretTraceRegistry): string { +export function safeContent(content: string, registry?: ResolvedSecretTraceRegistry): string { if (!registry) return content const projected = projectResolvedSecretModelContent(content, registry) if (!projected.safe || typeof projected.value !== 'string') @@ -206,12 +206,12 @@ export function matchesLiveFilters( return true } /** A provider result with the ID that locates it within its account. */ -interface LiveCandidate { +export interface LiveCandidate { document: NativeDocument documentId: string } -function candidateFor( +export function candidateFor( document: NativeDocument, account: LiveAccount, owner: string @@ -329,7 +329,7 @@ function readWindowEnd(content: string, start: number, scaledWindow: boolean | u * Verifies candidates in rank order. A revoked grant fails the whole account; any other * verification failure only omits that candidate, and is reported as incomplete coverage. */ -async function verifyCandidates( +export async function verifyCandidates( session: LiveAccountSession, candidates: LiveCandidate[], onVerified?: (candidate: LiveCandidate, permitted: boolean) => void @@ -450,7 +450,7 @@ function targetsAccount(query: NativeSearchQuery, account: LiveAccount): boolean } /** Stable account order so equal-rank results from different accounts always merge the same way. */ -function compareAccounts(left: LiveAccount, right: LiveAccount): number { +export function compareAccounts(left: LiveAccount, right: LiveAccount): number { return ( LIVE_SEARCH_PROVIDER_IDS.indexOf(left.provider) - LIVE_SEARCH_PROVIDER_IDS.indexOf(right.provider) || @@ -459,6 +459,14 @@ function compareAccounts(left: LiveAccount, right: LiveAccount): number { ) } +/** The page where the caller connects their own accounts in this scope. */ +export function liveIntegrationsUrl(owner: ResourceOwner): string { + const path = owner.organizationId + ? organizationRoutes(owner.organizationId).integrations + : `/workspace/${owner.workspaceId}/integrations` + return new URL(path, getBaseUrl()).href +} + /** * Why a plain search that reached no account returned nothing, and where the caller connects one; * an empty result would otherwise read as a search that found nothing. @@ -468,10 +476,7 @@ function nothingSearchedGuidance( source: string | undefined, hasOtherAccounts: boolean ): string { - const path = owner.organizationId - ? organizationRoutes(owner.organizationId).integrations - : `/workspace/${owner.workspaceId}/integrations` - const connect = new URL(path, getBaseUrl()).href + const connect = liveIntegrationsUrl(owner) return source && hasOtherAccounts ? `Nothing was searched: you have no connected ${source} account here. Connect one at ${connect}, or search without the source filter.` : `Nothing was searched: you have no connected sources here. Connect your accounts at ${connect}, then search again.` diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 3077bda4986..698994ba8c9 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -1,3 +1,4 @@ +import { MAX_ACTIVITY_COLLABORATORS, oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates' import { array, @@ -8,6 +9,7 @@ import { textContent, } from '@/lib/sim-search/live/http' import { interleaveByRank } from '@/lib/sim-search/live/pages' +import type { LiveSearchPolicy } from '@/lib/sim-search/live/policy-schema' import { providerText } from '@/lib/sim-search/live/text' import { confluenceTextClause, @@ -15,6 +17,10 @@ import { jiraTextClause, } from '@/lib/sim-search/live/text-match' import type { + NativeActivityEvent, + NativeActivityInput, + NativeActivityPage, + NativeActivityStream, NativeClient, NativeDocument, NativePage, @@ -209,6 +215,24 @@ async function atlassianPersonClause( return `(assignee = ${user} OR reporter = ${user})` } +/** The sites a grant can reach that the source settings allow. */ +async function policySites(client: NativeClient, policy: LiveSearchPolicy | undefined) { + return (await sites(client)).filter( + (site) => + !policy?.sites.length || policy.sites.includes(new URL(string(site.url)).host.toLowerCase()) + ) +} + +/** The JQL or CQL clause keeping a query to the projects or spaces the source settings select. */ +function policyClause( + provider: 'jira' | 'confluence', + policy: LiveSearchPolicy | undefined +): string | undefined { + return policy?.mode === 'selected' + ? `(${policy.included.map((id) => `${provider === 'jira' ? 'project' : 'space'} = ${JSON.stringify(id)}`).join(' OR ')})` + : undefined +} + export async function searchAtlassian( client: NativeClient, provider: 'jira' | 'confluence', @@ -220,11 +244,7 @@ export async function searchAtlassian( ? confluenceTextClause(text, input.textMatch) : '' if (confluenceClause === undefined) return { documents: [] } - const allSites = (await sites(client)).filter( - (site) => - !input.policy?.sites.length || - input.policy.sites.includes(new URL(string(site.url)).host.toLowerCase()) - ) + const allSites = await policySites(client, input.policy) const selected = input.native?.project ? allSites.filter((site) => string(site.id) === input.native?.project) : allSites.slice(0, 4) @@ -234,10 +254,7 @@ export async function searchAtlassian( 'No accessible Atlassian site matches this account or site ID.' ) const single = selected.length === 1 - const policyScope = - input.policy?.mode === 'selected' - ? `(${input.policy.included.map((id) => `${provider === 'jira' ? 'project' : 'space'} = ${JSON.stringify(id)}`).join(' OR ')})` - : undefined + const policyScope = policyClause(provider, input.policy) const dates = nativeDateBounds(input) const field = provider === 'jira' ? 'updated' : 'lastmodified' const person = await atlassianPersonClause(client, provider, input.involving, selected) @@ -364,6 +381,261 @@ export async function searchAtlassian( } } +/** Sites one activity call reads, as for search. */ +const MAX_ACTIVITY_SITES = 4 + +/** + * JQL and CQL compare dates in the member's profile time zone at day or minute precision, so each + * bound is widened by a day; the caller checks every returned instant exactly. + */ +function activityDay(instant: string, offsetDays: number): string { + return new Date(Date.parse(instant) + offsetDays * 86_400_000).toISOString().slice(0, 10) +} + +function activityRange(field: string, input: NativeActivityInput): string { + return `${field} >= "${activityDay(input.start, -1)}" AND ${field} <= "${activityDay(input.end, 1)}"` +} + +function displayNames(people: unknown[], except?: string): string[] { + return [ + ...new Set( + people + .map(object) + .filter((person) => string(person.accountId) && string(person.accountId) !== except) + .map((person) => string(person.displayName)) + .filter(Boolean) + ), + ].slice(0, MAX_ACTIVITY_COLLABORATORS) +} + +/** + * One Jira listing ordered newest first by `field`: issues the member reported, by creation, or + * issues assigned to them, by their last update. Jira's `updatedBy()` cannot be bounded reliably + * by date, so an assigned issue's time is its last update, by anyone. + */ +async function jiraActivityStream( + client: NativeClient, + site: Record, + input: NativeActivityInput, + kind: 'created' | 'assigned' +): Promise { + const cloudId = string(site.id) + const field = kind === 'created' ? 'created' : 'updated' + const person = kind === 'created' ? 'reporter = currentUser()' : 'assignee = currentUser()' + const data = object( + await client.json(`/ex/jira/${segment(cloudId)}/rest/api/3/search/jql`, { + body: { + jql: `${[policyClause('jira', input.policy), person, activityRange(field, input)] + .filter(Boolean) + .join(' AND ')} ORDER BY ${field} DESC`, + maxResults: input.limit, + fields: [ + 'summary', + 'description', + 'status', + 'created', + 'updated', + 'creator', + 'reporter', + 'assignee', + ], + }, + signal: input.signal, + }) + ) + const rows = array(data.issues) + const origin = string(site.url).replace(/\/$/, '') + return { + events: rows.flatMap((row): NativeActivityEvent[] => { + const fields = object(row.fields) + const at = string(fields[field]) + if (!Number.isFinite(Date.parse(at))) return [] + const self = object(kind === 'created' ? fields.reporter : fields.assignee) + return [ + { + document: issue(row, cloudId, origin), + at: new Date(at).toISOString(), + action: kind, + collaborators: displayNames( + kind === 'created' ? [fields.assignee] : [fields.reporter], + string(self.accountId) + ), + ...(kind === 'assigned' ? { approximateTime: true as const } : {}), + }, + ] + }), + more: Boolean(string(data.nextPageToken)), + scannedTo: oldestInstant(rows.map((row) => string(object(row.fields)[field]))), + } +} + +/** + * Pages and blog posts the member contributed to, newest first by last modification. When the + * last version is the member's, its time is their edit; otherwise the time is someone else's + * later edit and is marked approximate. + */ +async function confluencePageStream( + client: NativeClient, + site: Record, + input: NativeActivityInput, + accountId: string +): Promise { + const cloudId = string(site.id) + const origin = string(site.url).replace(/\/$/, '') + const data = object( + await client.json(`/ex/confluence/${segment(cloudId)}/wiki/rest/api/search`, { + query: { + cql: `${[ + 'type IN (page, blogpost)', + policyClause('confluence', input.policy), + 'contributor = currentUser()', + activityRange('lastmodified', input), + ] + .filter(Boolean) + .join(' AND ')} ORDER BY lastmodified DESC`, + limit: String(input.limit), + expand: 'content.version,content.space,content.history', + }, + signal: input.signal, + }) + ) + const rows = array(data.results) + return { + events: rows.flatMap((row): NativeActivityEvent[] => { + const document = page(row, cloudId, origin) + const content = object(row.content) + const version = object(content.version) + if (!document?.modifiedAt || !Number.isFinite(Date.parse(document.modifiedAt))) return [] + const mine = Boolean(accountId) && string(object(version.by).accountId) === accountId + return [ + { + document, + at: new Date(document.modifiedAt).toISOString(), + action: mine && version.number === 1 ? 'created' : 'edited', + collaborators: displayNames( + [object(content.history).createdBy, version.by], + accountId || undefined + ), + ...(mine ? {} : { approximateTime: true as const }), + }, + ] + }), + more: Boolean(string(object(data._links).next)), + scannedTo: oldestInstant( + rows.map( + (row) => string(object(object(row.content).version).when) || string(row.lastModified) + ) + ), + } +} + +/** + * Comments the member wrote, newest first. A comment is not readable on its own, so its entry + * reads the page or blog post it belongs to and links to the comment itself. + */ +async function confluenceCommentStream( + client: NativeClient, + site: Record, + input: NativeActivityInput +): Promise { + const cloudId = string(site.id) + const origin = string(site.url).replace(/\/$/, '') + const data = object( + await client.json(`/ex/confluence/${segment(cloudId)}/wiki/rest/api/search`, { + query: { + cql: `${[ + 'type = comment', + policyClause('confluence', input.policy), + 'creator = currentUser()', + activityRange('created', input), + ] + .filter(Boolean) + .join(' AND ')} ORDER BY created DESC`, + limit: String(input.limit), + expand: 'content.container,content.history,content.space', + }, + signal: input.signal, + }) + ) + const rows = array(data.results) + const createdAt = (row: Record) => + string(object(object(row.content).history).createdDate) + return { + events: rows.flatMap((row): NativeActivityEvent[] => { + const content = object(row.content) + const container = object(content.container) + const kind = string(container.type) + const at = createdAt(row) + if ((kind !== 'page' && kind !== 'blogpost') || !string(container.id)) return [] + if (!Number.isFinite(Date.parse(at))) return [] + const spaceKey = string(object(content.space).key) + return [ + { + document: { + id: string(container.id), + kind, + ...(spaceKey ? { accessMetadata: { spaceKey } } : {}), + container: cloudId, + title: string(container.title) || string(row.title), + url: `${origin}/wiki${string(object(content._links).webui) || string(row.url)}`, + content: providerText(string(row.excerpt).replace(/@@@(?:end)?hl@@@/g, ''), 'html'), + modifiedAt: at, + }, + at: new Date(at).toISOString(), + action: 'commented', + collaborators: [], + }, + ] + }), + more: Boolean(string(object(data._links).next)), + scannedTo: oldestInstant(rows.map(createdAt)), + } +} + +/** + * The member's Jira or Confluence activity on each site the grant reaches (up to four), one + * newest-first listing per kind and site. + */ +export async function atlassianActivity( + client: NativeClient, + provider: 'jira' | 'confluence', + input: NativeActivityInput +): Promise { + const allSites = await policySites(client, input.policy) + if (!allSites.length) + throw new NativeSearchError('reconnect', 'No accessible Atlassian site matches this account.') + const selected = allSites.slice(0, MAX_ACTIVITY_SITES) + const streams = await Promise.all( + selected.map(async (site) => { + if (provider === 'jira') + return Promise.all([ + jiraActivityStream(client, site, input, 'created'), + jiraActivityStream(client, site, input, 'assigned'), + ]) + const current = object( + await client.json(`/ex/confluence/${segment(string(site.id))}/wiki/rest/api/user/current`, { + memo: true, + signal: input.signal, + }) + ) + return Promise.all([ + confluencePageStream(client, site, input, string(current.accountId)), + confluenceCommentStream(client, site, input), + ]) + }) + ) + const skipped = allSites.length > selected.length + return { + streams: streams.flat(), + ...(skipped + ? { + partial: true, + message: `Activity covers the first ${MAX_ACTIVITY_SITES} accessible Atlassian sites.`, + } + : {}), + } +} + export async function readAtlassian( client: NativeClient, provider: 'jira' | 'confluence', diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index 1942c5ec9df..73aa9f866f0 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -2,6 +2,7 @@ import { mapWithConcurrency } from '@sim/utils/concurrency' import { toArray } from '@sim/utils/object' import { compareStrings, truncate } from '@sim/utils/string' import { zonedWallClockToUtc } from '@sim/utils/timezone' +import { MAX_ACTIVITY_COLLABORATORS, oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, hasDateBounds, @@ -15,6 +16,8 @@ import { interleaveByRank } from '@/lib/sim-search/live/pages' import { permitsResources } from '@/lib/sim-search/live/policy' import { providerText } from '@/lib/sim-search/live/text' import type { + NativeActivityInput, + NativeActivityPage, NativeClient, NativeDocument, NativePage, @@ -311,6 +314,80 @@ export async function searchGmail( } } +/** Gmail lists at most this many sent messages per activity page; each costs a metadata read. */ +const GMAIL_ACTIVITY_PAGE_SIZE = 20 + +/** The display name, or else the address, of each mailbox in an address-list header. */ +function mailParticipants(value: string): string[] { + return (value.match(/(?:"[^"]*"|[^,])+/g) ?? []).flatMap((entry) => { + const named = entry.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/) + const label = named ? named[1].trim() || named[2].trim() : entry.trim() + return label ? [label] : [] + }) +} + +/** + * Mail the connected member sent, newest first. A message answering another (it carries + * In-Reply-To) is a reply; its recipients are its collaborators. + */ +export async function gmailActivity( + client: NativeClient, + input: NativeActivityInput +): Promise { + const data = object( + await client.json('/gmail/v1/users/me/messages', { + query: { + q: `in:sent after:${Math.floor(Date.parse(input.start) / 1000) - 1} before:${Math.ceil(Date.parse(input.end) / 1000) + 1}`, + maxResults: String(Math.min(input.limit, GMAIL_ACTIVITY_PAGE_SIZE)), + }, + }) + ) + const rows = await mapWithConcurrency( + array(data.messages), + GMAIL_METADATA_CONCURRENCY, + async (message) => + object( + await client.json(`/gmail/v1/users/me/messages/${segment(string(message.id))}`, { + query: { + format: 'metadata', + metadataHeaders: ['Subject', 'From', 'To', 'Cc', 'In-Reply-To'], + fields: GMAIL_METADATA_FIELDS, + }, + }) + ) + ) + const documents = rows.map((row) => { + const headers = array(object(row.payload).headers) + const header = (name: string) => + string(headers.find((h) => string(h.name).toLowerCase() === name)?.value) + return { + document: gmailDocument(row), + replied: Boolean(header('in-reply-to')), + recipients: [...mailParticipants(header('to')), ...mailParticipants(header('cc'))], + } + }) + return { + streams: [ + { + events: documents.flatMap(({ document, replied, recipients }) => + document.modifiedAt + ? [ + { + document, + at: document.modifiedAt, + action: replied ? ('replied' as const) : ('sent' as const), + collaborators: [...new Set(recipients)].slice(0, MAX_ACTIVITY_COLLABORATORS), + }, + ] + : [] + ), + more: Boolean(string(data.nextPageToken)), + scannedTo: oldestInstant(documents.map(({ document }) => document.modifiedAt)), + }, + ], + } +} + /** The response byte cap does not bound recursive MIME depth or per-part processing work. */ const GMAIL_MIME_DEPTH_LIMIT = 32 const GMAIL_MIME_PART_LIMIT = 256 @@ -696,6 +773,100 @@ export async function searchCalendar( } } +/** Calendar event pages one activity call reads; the API lists a window oldest first. */ +const CALENDAR_ACTIVITY_PAGES = 4 +/** Personal blocks Calendar records as events, which nobody attends. */ +const NON_MEETING_EVENT_TYPES = new Set(['focusTime', 'outOfOffice', 'workingLocation', 'birthday']) + +/** + * Whether the connected member took part in a meeting: they organize it or accepted it, and + * someone else was invited. Declined and unanswered invitations are not attendance. + */ +function attendedMeeting(event: Record): boolean { + if (event.status === 'cancelled' || NON_MEETING_EVENT_TYPES.has(string(event.eventType))) + return false + const attendees = array(event.attendees) + if (!attendees.some((attendee) => attendee.self !== true)) return false + const self = attendees.find((attendee) => attendee.self === true) + return ( + object(event.organizer).self === true || + (self !== undefined && ['accepted', 'tentative'].includes(string(self.responseStatus))) + ) +} + +/** + * Meetings on the member's primary calendar that started in the window, up to now. Calendar + * lists a window oldest first, so the whole window is read (up to a bounded number of pages) + * and ordered newest first here; a window with more meetings than that reports partial coverage. + */ +export async function calendarActivity( + client: NativeClient, + input: NativeActivityInput +): Promise { + const end = Math.min(Date.parse(input.end), Date.now()) + if (end < Date.parse(input.start)) return { streams: [{ events: [], more: false }] } + const events: Record[] = [] + let timeZone = '' + let pageToken: string | undefined + for (let page = 0; page < CALENDAR_ACTIVITY_PAGES; page++) { + const data = object( + await client.json('/calendar/v3/calendars/primary/events', { + query: { + timeMin: input.start, + timeMax: new Date(end + 1).toISOString(), + singleEvents: 'true', + orderBy: 'startTime', + maxResults: '250', + showDeleted: 'false', + ...(pageToken ? { pageToken } : {}), + }, + }) + ) + timeZone ||= string(data.timeZone) + events.push(...array(data.items)) + pageToken = string(data.nextPageToken) || undefined + if (!pageToken) break + } + const includeAttendees = input.policy?.includeAttendees !== false + return { + streams: [ + { + events: events + .filter(attendedMeeting) + .flatMap((event) => { + const document = { + ...eventDocument(event, 'primary', includeAttendees, timeZone || undefined), + dedupeKey: calendarOccurrenceKey(event), + } + if (!document.eventStartAt) return [] + return [ + { + document, + at: document.eventStartAt, + action: 'attended' as const, + collaborators: includeAttendees + ? array(event.attendees) + .filter((attendee) => attendee.self !== true && attendee.resource !== true) + .map((attendee) => string(attendee.displayName) || string(attendee.email)) + .filter(Boolean) + .slice(0, MAX_ACTIVITY_COLLABORATORS) + : [], + }, + ] + }) + .sort((left, right) => Date.parse(right.at) - Date.parse(left.at)), + more: false, + }, + ], + ...(pageToken + ? { + partial: true, + message: 'This window holds more meetings than one call reads. Narrow the dates.', + } + : {}), + } +} + export async function readCalendar( client: NativeClient, id: string, diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 3012ae37103..7804603e4a8 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -1,10 +1,17 @@ import { MAX_NATIVE_QUERIES_PER_ACCOUNT } from '@/lib/api/contracts/mothership-assistant-tools' -import { previewConfluence, readAtlassian, searchAtlassian } from '@/lib/sim-search/live/atlassian' +import { + atlassianActivity, + previewConfluence, + readAtlassian, + searchAtlassian, +} from '@/lib/sim-search/live/atlassian' import { readCoda, searchCoda } from '@/lib/sim-search/live/coda' import { readFlow, searchFlow } from '@/lib/sim-search/live/flow' import { readGitHub, searchGitHub } from '@/lib/sim-search/live/github' import { readGitLab, searchGitLab } from '@/lib/sim-search/live/gitlab' import { + calendarActivity, + gmailActivity, previewDrive, readCalendar, readDrive, @@ -21,8 +28,10 @@ import { LIVE_SEARCH_PROVIDER_IDS, type LiveSearchProviderId, } from '@/lib/sim-search/live/provider-catalog' -import { readSlack, searchSlack } from '@/lib/sim-search/live/slack' +import { readSlack, searchSlack, slackActivity } from '@/lib/sim-search/live/slack' import type { + NativeActivityInput, + NativeActivityPage, NativeClient, NativeDocument, NativePage, @@ -62,6 +71,8 @@ interface NativeProvider { */ previewText?(client: NativeClient, document: NativeDocument): Promise search(client: NativeClient, input: NativeSearchInput, origin?: string): Promise + /** The connected person's own activity, newest first; providers without it report unsupported. */ + activity?(client: NativeClient, input: NativeActivityInput): Promise read( client: NativeClient, reference: Pick, @@ -127,6 +138,7 @@ export const LIVE_SEARCH_PROVIDERS = { 'listing alternatives with spaces, which requires all of them, or lowercase or; join alternatives with uppercase OR. Search matches individual messages, and a result shows only the opening of its message, not a passage around the match: read it before concluding what the rest of the message says. Reading a match includes up to eight independently authorized messages from its conversation, with per-message dates and URLs. Context can fall outside the search dates or keywords; use the message timestamps and incomplete notices, and never claim the entire thread was searched.', }, search: searchGmail, + activity: gmailActivity, read: (client, reference, options) => readGmail(client, reference.id, options), }, google_meet: { @@ -166,6 +178,7 @@ export const LIVE_SEARCH_PROVIDERS = { 'OR, quotes or field operators, which q does not support; run alternatives as separate native queries.', }, search: searchCalendar, + activity: calendarActivity, read: (client, reference, options) => readCalendar( client, @@ -188,6 +201,7 @@ export const LIVE_SEARCH_PROVIDERS = { 'joining alternatives with OR or spaces in one query, which keyword retrieval treats as all required; send them as separate native queries.', }, search: searchSlack, + activity: slackActivity, read: (client, reference, options) => readSlack( client, @@ -211,6 +225,7 @@ export const LIVE_SEARCH_PROVIDERS = { }, requiresEveryTerm: true, search: (client, input) => searchAtlassian(client, 'jira', input), + activity: (client, input) => atlassianActivity(client, 'jira', input), read: (client, reference) => readAtlassian(client, 'jira', reference.id, reference.container), }, confluence: { @@ -228,6 +243,7 @@ export const LIVE_SEARCH_PROVIDERS = { requiresEveryTerm: true, previewText: previewConfluence, search: (client, input) => searchAtlassian(client, 'confluence', input), + activity: (client, input) => atlassianActivity(client, 'confluence', input), read: (client, reference) => readAtlassian(client, 'confluence', reference.id, reference.container, reference.kind), }, @@ -379,6 +395,22 @@ export function searchNativeProvider( return adapter.search(client, input, origin) } +/** True when the provider reports the connected person's own activity. */ +export function supportsActivity(provider: LiveSearchProviderId): boolean { + return 'activity' in LIVE_SEARCH_PROVIDERS[provider] +} + +export function activityNativeProvider( + provider: LiveSearchProviderId, + client: NativeClient, + input: NativeActivityInput +): Promise { + const adapter: NativeProvider | ManagedMcpProvider = LIVE_SEARCH_PROVIDERS[provider] + if (!('activity' in adapter) || !adapter.activity) + throw new NativeSearchError('unavailable', `${provider} does not report activity`) + return adapter.activity(client, input) +} + /** * True when the account can limit a search to the items this person (`me` or an email) took part * in: the provider supports the filter and, for an email, the account holds the scope finding diff --git a/apps/sim/lib/sim-search/live/slack.ts b/apps/sim/lib/sim-search/live/slack.ts index 53e2366153f..4ecd7142649 100644 --- a/apps/sim/lib/sim-search/live/slack.ts +++ b/apps/sim/lib/sim-search/live/slack.ts @@ -1,5 +1,6 @@ import { slackFileDownloadUrl } from '@/lib/internal/slack/file-download' import { recordSearchProviderSignal } from '@/lib/knowledge/search/diagnostics' +import { oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates' import { documentExtension, @@ -22,6 +23,8 @@ import { } from '@/lib/sim-search/live/slack-format' import { providerText } from '@/lib/sim-search/live/text' import type { + NativeActivityInput, + NativeActivityPage, NativeClient, NativeDocument, NativePage, @@ -247,6 +250,64 @@ async function slackPersonModifier( return `from:<@${id}>` } +/** + * Messages the connected member posted, newest first: one Real-time Search page of `from:me`, + * sorted by timestamp. A message inside a thread it did not start is a reply. File hits come from + * a separately ordered collection, so they are left out; a shared file also posts a message. + */ +export async function slackActivity( + client: NativeClient, + input: NativeActivityInput +): Promise { + if (!input.scopes.includes('search:read.public')) + throw new NativeSearchError( + 'reconnect', + 'Reconnect your Slack account to grant permission to search.' + ) + const page = await searchSlackPage( + client, + { + query: '', + filters: { + startDate: input.start, + endDate: new Date(Date.parse(input.end) + 1000).toISOString(), + sortBy: 'newest', + }, + policy: input.policy, + limit: SLACK_PAGE_SIZE, + scopes: input.scopes, + signal: input.signal, + }, + undefined, + Math.min(input.limit, SLACK_PAGE_SIZE), + 'from:me' + ) + const messages = page.documents.filter((document) => document.kind !== 'file') + return { + streams: [ + { + events: messages.flatMap((document) => + document.modifiedAt + ? [ + { + document, + at: document.modifiedAt, + action: + document.threadId && document.threadId !== document.id + ? ('replied' as const) + : ('sent' as const), + collaborators: [], + }, + ] + : [] + ), + more: Boolean(page.nextCursor), + scannedTo: oldestInstant(messages.map((document) => document.modifiedAt)), + }, + ], + } +} + async function searchSlackPage( client: NativeClient, input: NativeSearchInput, diff --git a/apps/sim/lib/sim-search/live/types.ts b/apps/sim/lib/sim-search/live/types.ts index 6a5b382be3c..c2c7b3a4382 100644 --- a/apps/sim/lib/sim-search/live/types.ts +++ b/apps/sim/lib/sim-search/live/types.ts @@ -128,3 +128,57 @@ export interface NativeSearchInput { */ signal?: AbortSignal } + +/** What the connected person did to an item, as one activity entry reports it. */ +export type ActivityAction = + | 'created' + | 'edited' + | 'commented' + | 'sent' + | 'replied' + | 'attended' + | 'assigned' + | 'mentioned' + +/** + * One account's activity request. `end` is inclusive so a continuation can resume at the instant + * an earlier page stopped; the caller drops entries it already returned at that instant. + */ +export interface NativeActivityInput { + start: string + end: string + /** Raw provider items one stream reads per call. */ + limit: number + scopes: readonly string[] + policy?: LiveSearchPolicy + signal?: AbortSignal +} + +/** One thing the connected person did, at the time of the provider order the stream reads in. */ +export interface NativeActivityEvent { + document: NativeDocument + /** The instant this entry sorts by: never later than its stream's `scannedTo` when more remain. */ + at: string + action: ActivityAction + collaborators: string[] + /** `at` is the item's last update, which may be someone else's, not the person's own action. */ + approximateTime?: true +} + +/** + * One provider listing read newest first. Every unread item of the stream sorts at or before + * `scannedTo`, so the events at or after it are complete for this stream. + */ +export interface NativeActivityStream { + events: NativeActivityEvent[] + /** Older items remain in the window; requires `scannedTo`. */ + more: boolean + /** The sort instant of the oldest item read, including items that produced no event. */ + scannedTo?: string +} + +export interface NativeActivityPage { + streams: NativeActivityStream[] + partial?: boolean + message?: string +} From f376c292cac599cde83860d9406b94ec14687ed0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 20:57:41 -0800 Subject: [PATCH 02/13] refactor(search): share live candidate helpers and provider date clauses with activity --- .../contracts/mothership-assistant-tools.ts | 24 +- .../lib/mothership/chat/citation-evidence.ts | 33 +-- .../sim-assistant-tools.generated.ts | 34 ++- apps/sim/lib/sim-search/live/activity-page.ts | 76 ++++--- apps/sim/lib/sim-search/live/activity.ts | 215 +++++++++--------- apps/sim/lib/sim-search/live/application.ts | 87 +------ apps/sim/lib/sim-search/live/atlassian.ts | 176 +++++++------- apps/sim/lib/sim-search/live/candidates.ts | 89 ++++++++ apps/sim/lib/sim-search/live/google.ts | 66 +++--- apps/sim/lib/sim-search/live/types.ts | 12 +- 10 files changed, 433 insertions(+), 379 deletions(-) create mode 100644 apps/sim/lib/sim-search/live/candidates.ts diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index f8b2df476ca..b69d36f2b8a 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -421,22 +421,26 @@ export const liveSourceStatusSchema = z.object({ }) export type LiveSourceStatus = z.output +/** What the person did to an item, as one activity entry reports it. */ +const activityActionSchema = z.enum([ + 'created', + 'edited', + 'commented', + 'sent', + 'replied', + 'attended', + 'assigned', + 'mentioned', +]) +export type ActivityAction = z.output + const activityItemSchema = z.object({ /** Reads the item with read_document. */ documentId: z.string(), timestamp: z.string(), source: liveSearchProviderSchema, accountId: z.string(), - action: z.enum([ - 'created', - 'edited', - 'commented', - 'sent', - 'replied', - 'attended', - 'assigned', - 'mentioned', - ]), + action: activityActionSchema, title: z.string(), url: z.string().nullable(), container: z.string().optional(), diff --git a/apps/sim/lib/mothership/chat/citation-evidence.ts b/apps/sim/lib/mothership/chat/citation-evidence.ts index 75bf193f27c..fddcbb28061 100644 --- a/apps/sim/lib/mothership/chat/citation-evidence.ts +++ b/apps/sim/lib/mothership/chat/citation-evidence.ts @@ -36,12 +36,21 @@ export function isWebResearchTool(toolName: string): boolean { /** * A result in retrieval's citation fields. A web page names its address `url` and its heading * `title`, and leaves its site name and summary to the link preview; a compacted page already - * carries the citation fields. + * carries the citation fields. An activity entry names its title, source, time and snippet. */ export function toCitationResult( toolName: string, result: Record ): Record { + if (toolName === 'list_my_activity') + return { + citationId: result.citationId, + citationUrl: result.citationUrl, + documentName: result.title, + connectorType: result.source, + sourceDate: result.timestamp, + content: result.snippet, + } if (!isWebResearchTool(toolName) || typeof result.citationUrl === 'string') return result return { citationId: result.citationId, @@ -73,12 +82,9 @@ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitat const output = parseCitationRecord(call.result.output) if (!output || output.success === false) continue const data = parseCitationRecord(output.data) ?? output - /** Activity lists its entries as `items`, each a source like a search result. */ - const results = Array.isArray(data.results) - ? data.results - : Array.isArray(data.items) - ? data.items - : [data] + /** Activity lists its entries, each a source, under `items`. */ + const list = call.name === 'list_my_activity' ? data.items : data.results + const results = Array.isArray(list) ? list : [data] for (const raw of results) { const record = parseCitationRecord(raw) const result = record && toCitationResult(call.name, record) @@ -99,18 +105,17 @@ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitat if (evidence.has(result.citationId)) continue const siteName = typeof result.siteName === 'string' ? result.siteName : result.knowledgeBaseName - const updatedAt = result.sourceDate ?? result.sourceModifiedAt ?? result.timestamp - const title = result.documentName ?? result.title - const connectorType = result.connectorType ?? result.source - const snippet = result.content ?? result.snippet + const updatedAt = result.sourceDate ?? result.sourceModifiedAt evidence.set(result.citationId, { url: result.citationUrl, - ...(typeof title === 'string' ? { title } : {}), + ...(typeof result.documentName === 'string' ? { title: result.documentName } : {}), ...(typeof siteName === 'string' ? { siteName } : {}), - ...(typeof connectorType === 'string' ? { connectorType } : {}), + ...(typeof result.connectorType === 'string' + ? { connectorType: result.connectorType } + : {}), ...(typeof result.author === 'string' ? { author: result.author } : {}), ...(typeof updatedAt === 'string' ? { updatedAt } : {}), - ...(typeof snippet === 'string' ? { snippet: snippet.slice(0, 500) } : {}), + ...(typeof result.content === 'string' ? { snippet: result.content.slice(0, 500) } : {}), }) } } diff --git a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts index ab968868a88..a722af6fe2c 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -379,7 +379,9 @@ export const listMyActivityInputFieldsSchema = z ), source: liveSearchProviderSchema .optional() - .describe('One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.'), + .describe( + 'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.' + ), topK: z .number() .int() @@ -407,7 +409,11 @@ export function refineActivityWindow( const start = Date.parse(input.startDate) const end = Date.parse(input.endDate) if (start >= end) - context.addIssue({ code: 'custom', path: ['endDate'], message: 'endDate must be after startDate.' }) + context.addIssue({ + code: 'custom', + path: ['endDate'], + message: 'endDate must be after startDate.', + }) else if (end - start > MAX_ACTIVITY_WINDOW_DAYS * 86_400_000) context.addIssue({ code: 'custom', @@ -435,22 +441,26 @@ export const liveSourceStatusSchema = z.object({ }) export type LiveSourceStatus = z.output +/** What the person did to an item, as one activity entry reports it. */ +const activityActionSchema = z.enum([ + 'created', + 'edited', + 'commented', + 'sent', + 'replied', + 'attended', + 'assigned', + 'mentioned', +]) +export type ActivityAction = z.output + const activityItemSchema = z.object({ /** Reads the item with read_document. */ documentId: z.string(), timestamp: z.string(), source: liveSearchProviderSchema, accountId: z.string(), - action: z.enum([ - 'created', - 'edited', - 'commented', - 'sent', - 'replied', - 'attended', - 'assigned', - 'mentioned', - ]), + action: activityActionSchema, title: z.string(), url: z.string().nullable(), container: z.string().optional(), diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts index 8e761eb6bc8..cd30d5dcd5a 100644 --- a/apps/sim/lib/sim-search/live/activity-page.ts +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -5,13 +5,21 @@ import { compareStrings } from '@sim/utils/string' import { z } from 'zod' /** People named on one activity entry, besides the person whose activity it is. */ -export const MAX_ACTIVITY_COLLABORATORS = 10 +const MAX_ACTIVITY_COLLABORATORS = 10 /** * Entries one account may have returned at the instant a page stopped. A continuation skips * them; an account with more than this many entries at one instant stops there. */ const MAX_SEEN_AT_BOUND = 50 +/** The distinct, nonempty names on one activity entry, at most {@link MAX_ACTIVITY_COLLABORATORS}. */ +export function collaboratorNames(names: readonly string[]): string[] { + return [...new Set(names.map((name) => name.trim()).filter(Boolean))].slice( + 0, + MAX_ACTIVITY_COLLABORATORS + ) +} + /** The earliest of the valid instants, as ISO, or undefined when none parses. */ export function oldestInstant(values: readonly (string | undefined)[]): string | undefined { let oldest: number | undefined @@ -49,7 +57,7 @@ export type AccountActivity = { bound: ActivityBound } & ({ read: true; streams: ActivityStreamRead[] } | { read: false }) -export interface ActivityPageResult { +interface ActivityPageResult { /** Newest first. */ entries: (E & { accountId: string })[] /** Each continuing account's bound, or undefined when no page follows. */ @@ -58,13 +66,9 @@ export interface ActivityPageResult { stalled: string[] } -function instant(value: string): number { - return Date.parse(value) -} - function sameBound(left: ActivityBound, right: ActivityBound): boolean { return ( - instant(left.end) === instant(right.end) && + Date.parse(left.end) === Date.parse(right.end) && left.seen.length === right.seen.length && left.seen.every((key) => right.seen.includes(key)) ) @@ -84,44 +88,47 @@ export function mergeActivityPage( window: { start: string }, topK: number ): ActivityPageResult { - const start = instant(window.start) + const start = Date.parse(window.start) let horizon: number | undefined - const pending: (E & { accountId: string })[] = [] + const pending: { entry: E & { accountId: string }; time: number }[] = [] const unfinished = new Set() for (const account of accounts) { if (!account.read) continue - const end = instant(account.bound.end) + const end = Date.parse(account.bound.end) const seen = new Set(account.bound.seen) const keys = new Set() for (const stream of account.streams) { if (stream.more) { - const scanned = stream.scannedTo ? instant(stream.scannedTo) : end + const scanned = stream.scannedTo ? Date.parse(stream.scannedTo) : end const floor = Number.isFinite(scanned) ? Math.min(scanned, end) : end horizon = horizon === undefined ? floor : Math.max(horizon, floor) unfinished.add(account.accountId) } for (const entry of stream.entries) { - const at = instant(entry.at) - if (!Number.isFinite(at) || at < start || at > end) continue - if (at === end && seen.has(entry.key)) continue - if (keys.has(entry.key)) continue + const time = Date.parse(entry.at) + if (!Number.isFinite(time) || time < start || time > end) continue + if ((time === end && seen.has(entry.key)) || keys.has(entry.key)) continue keys.add(entry.key) - pending.push({ ...entry, accountId: account.accountId }) + pending.push({ entry: { ...entry, accountId: account.accountId }, time }) } } } pending.sort( (left, right) => - instant(right.at) - instant(left.at) || - compareStrings(left.accountId, right.accountId) || - compareStrings(left.key, right.key) + right.time - left.time || + compareStrings(left.entry.accountId, right.entry.accountId) || + compareStrings(left.entry.key, right.entry.key) ) - const ready = - horizon === undefined ? pending : pending.filter((entry) => instant(entry.at) >= horizon) - const entries = ready.slice(0, topK) + const ready = horizon === undefined ? pending : pending.filter(({ time }) => time >= horizon) + const returned = ready.slice(0, topK) const cut = ready.length > topK - const last = entries.at(-1) - const resume = cut && last ? instant(last.at) : horizon + const last = returned.at(-1) + const resume = cut && last ? last.time : horizon + /** Accounts with an entry this page read but did not return, which the next page must reach. */ + const returnedItems = new Set(returned) + const remaining = new Set( + pending.filter((item) => !returnedItems.has(item)).map(({ entry }) => entry.accountId) + ) const next: Record = {} const stalled: string[] = [] const continuing: string[] = [] @@ -131,19 +138,19 @@ export function mergeActivityPage( next[account.accountId] = account.bound continue } - const remaining = pending.some( - (entry) => entry.accountId === account.accountId && !entries.includes(entry) + if ( + resume === undefined || + (!unfinished.has(account.accountId) && !remaining.has(account.accountId)) ) - if (resume === undefined || (!unfinished.has(account.accountId) && !remaining)) continue - const resumeAt = new Date(resume).toISOString() - const returnedAtResume = entries - .filter((entry) => entry.accountId === account.accountId && instant(entry.at) === resume) - .map((entry) => entry.key) + continue + const returnedAtResume = returned + .filter(({ entry, time }) => entry.accountId === account.accountId && time === resume) + .map(({ entry }) => entry.key) const bound: ActivityBound = { - end: resumeAt, + end: new Date(resume).toISOString(), seen: [ ...new Set([ - ...(instant(account.bound.end) === resume ? account.bound.seen : []), + ...(Date.parse(account.bound.end) === resume ? account.bound.seen : []), ...returnedAtResume, ]), ], @@ -156,6 +163,7 @@ export function mergeActivityPage( next[account.accountId] = bound continuing.push(account.accountId) } + const entries = returned.map(({ entry }) => entry) /** A page that moves no account's bound would be read again unchanged, so it ends here. */ if (continuing.length && !progressed) return { entries, stalled: [...stalled, ...continuing] } return { entries, ...(continuing.length ? { next } : {}), stalled } @@ -175,7 +183,7 @@ const cursorSchema = z accounts: z.record(z.string().max(200), boundSchema), }) .strict() -export type ActivityCursor = z.output +type ActivityCursor = z.output const signedCursorSchema = cursorSchema.extend({ signature: z.string().regex(/^[a-f0-9]{64}$/) }) function cursorSignature(cursor: ActivityCursor, secret: string): string { diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index f52f424229e..e2e4afdd243 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -34,14 +34,13 @@ import { readActivityCursor, writeActivityCursor, } from '@/lib/sim-search/live/activity-page' +import { liveIntegrationsUrl } from '@/lib/sim-search/live/application' import { candidateFor, compareAccounts, - type LiveCandidate, - liveIntegrationsUrl, safeContent, verifyCandidates, -} from '@/lib/sim-search/live/application' +} from '@/lib/sim-search/live/candidates' import { NativeSearchError } from '@/lib/sim-search/live/http' import { loadLiveSearchPolicies } from '@/lib/sim-search/live/policy-store' import { @@ -130,37 +129,42 @@ function entryKey(event: NativeActivityEvent): string { ).slice(0, 16) } -type AccountRead = - | { - account: LiveAccount - ok: true - streams: { entries: Entry[]; more: boolean; scannedTo?: string }[] - partial: boolean - message?: string - } - | { account: LiveAccount; ok: false; error: NativeSearchError } +/** One account's page: what it read for the merge, or why it could not be read. */ +type AccountRead = AccountActivity & + ({ read: true; partial: boolean; message?: string } | { read: false; error: NativeSearchError }) -function failureStatus( - account: LiveAccount, - error: NativeSearchError, - organizationId: string -): LiveSourceStatus { - const base = { +type SourceStatus = LiveSourceStatus & { itemCount: number } + +function accountStatus(account: LiveAccount, status: Omit): SourceStatus { + return { source: account.provider, accountId: account.id, displayName: account.displayName, - message: error.message, + ...status, } +} + +function failureStatus( + account: LiveAccount, + error: NativeSearchError, + organizationId: string +): SourceStatus { if (error.status === 'reconnect') - return { ...base, status: 'reconnect', connect: connectHint(account.provider, organizationId) } - return { - ...base, + return accountStatus(account, { + status: 'reconnect', + message: error.message, + connect: connectHint(account.provider, organizationId), + itemCount: 0, + }) + return accountStatus(account, { status: 'failed', reason: error.status, + message: error.message, ...(error.retryAfterSeconds === undefined ? {} : { retryAfterSeconds: error.retryAfterSeconds }), - } + itemCount: 0, + }) } /** @@ -174,11 +178,14 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ resolveKnowledgeOrganizationContext({ organizationId: input.organizationId }), async execute({ principal, input }): Promise { const userId = requirePrincipalSubjectUserId(principal) - /** Live provider results carry no stored provenance; they are projected through `safeContent`. */ - await admitContent(principal, []) const { organizationId } = input - await requireOrganizationSearchAvailable(organizationId) - if (!(await isMyActivityEnabled(organizationId))) + const [, , enabled] = await Promise.all([ + /** Live provider results carry no stored provenance; they are projected through `safeContent`. */ + admitContent(principal, []), + requireOrganizationSearchAvailable(organizationId), + isMyActivityEnabled(organizationId), + ]) + if (!enabled) throw new OrchestrationError( 'forbidden', 'Activity listing is not enabled for this organization' @@ -216,54 +223,56 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ const [policies, connected, approvals] = await Promise.all([ loadLiveSearchPolicies(owner), listLiveAccounts(owner, userId), - listOrganizationSearchApprovals(organizationId), + /** Later pages continue the accounts their cursor names, so only the first reports the rest. */ + cursor ? undefined : listOrganizationSearchApprovals(organizationId), ]) const accounts = connected .filter((account) => !parsed.source || account.provider === parsed.source) .sort(compareAccounts) - const statuses: (LiveSourceStatus & { itemCount: number })[] = [] - if (!cursor) - for (const provider of LIVE_SEARCH_PROVIDER_IDS) { - if (parsed.source && provider !== parsed.source) continue - if (!supportsActivity(provider) || approvals.get(provider) !== true) continue - if (accounts.some((account) => account.provider === provider)) continue - statuses.push({ - source: provider, - status: 'not_connected', - message: `Connect your ${provider} account to include it.`, - connect: connectHint(provider, organizationId), - itemCount: 0, - }) - } const readable = (account: LiveAccount) => supportsActivity(account.provider) && account.type !== 'managed_mcp' && account.type !== 'admin_source' - if (!cursor) - for (const account of accounts.filter((candidate) => !readable(candidate))) - statuses.push({ - source: account.provider, - accountId: account.id, - displayName: account.displayName, - status: 'unsupported', - message: 'This source does not report activity yet.', - itemCount: 0, - }) const eligible = accounts.filter(readable) const selected = cursor ? eligible.filter((account) => cursor.accounts[account.id]) : eligible.slice(0, MAX_ACTIVITY_ACCOUNTS) - if (!cursor) - for (const account of eligible.slice(MAX_ACTIVITY_ACCOUNTS)) - statuses.push({ - source: account.provider, - accountId: account.id, - displayName: account.displayName, - status: 'failed', - reason: 'unavailable', - message: `One call reads at most ${MAX_ACTIVITY_ACCOUNTS} accounts. Pass source to read this one.`, - itemCount: 0, - }) + const statuses: SourceStatus[] = approvals + ? [ + ...LIVE_SEARCH_PROVIDER_IDS.filter( + (provider) => + (!parsed.source || provider === parsed.source) && + supportsActivity(provider) && + approvals.get(provider) === true && + !accounts.some((account) => account.provider === provider) + ).map( + (provider): SourceStatus => ({ + source: provider, + status: 'not_connected', + message: `Connect your ${provider} account to include it.`, + connect: connectHint(provider, organizationId), + itemCount: 0, + }) + ), + ...accounts + .filter((account) => !readable(account)) + .map((account) => + accountStatus(account, { + status: 'unsupported', + message: 'This source does not report activity yet.', + itemCount: 0, + }) + ), + ...eligible.slice(MAX_ACTIVITY_ACCOUNTS).map((account) => + accountStatus(account, { + status: 'failed', + reason: 'unavailable', + message: `One call reads at most ${MAX_ACTIVITY_ACCOUNTS} accounts. Pass source to read this one.`, + itemCount: 0, + }) + ), + ] + : [] const boundOf = (account: LiveAccount): ActivityBound => cursor?.accounts[account.id] ?? { end: window.end, seen: [] } @@ -304,22 +313,24 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ candidateFor(event.document, account, referenceOwner) ) const verification = await verifyCandidates(session, candidates) - const permitted = new Set(verification.permitted) - const allowed = new Map() - events.forEach((event, index) => { - const candidate = candidates[index] - if (candidate && permitted.has(candidate)) allowed.set(event, candidate.documentId) - }) + const permitted = new Set(verification.permitted) + const documentIds = new Map( + candidates.flatMap((candidate, index) => { + const event = events[index] + return event && permitted.has(candidate) ? [[event, candidate.documentId] as const] : [] + }) + ) return { - account, - ok: true, + accountId: account.id, + bound, + read: true, partial: Boolean(page.partial || verification.unverified || session.servicePartial), message: page.message, streams: page.streams.map((stream) => ({ more: stream.more, scannedTo: stream.scannedTo, entries: stream.events.flatMap((event): Entry[] => { - const documentId = allowed.get(event) + const documentId = documentIds.get(event) return documentId ? [{ at: event.at, key: entryKey(event), event, documentId }] : [] }), })), @@ -332,8 +343,9 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ error: error instanceof Error ? error.message : String(error), }) return { - account, - ok: false, + accountId: account.id, + bound: boundOf(account), + read: false, error: error instanceof NativeSearchError ? error @@ -357,26 +369,14 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ } input.signal?.throwIfAborted() - const merged = mergeActivityPage( - reads.map( - (read): AccountActivity => - read.ok - ? { - accountId: read.account.id, - bound: boundOf(read.account), - read: true, - streams: read.streams, - } - : { accountId: read.account.id, bound: boundOf(read.account), read: false } - ), - window, - topK - ) + const merged = mergeActivityPage(reads, window, topK) const registry = input.resultSecretRegistry const byId = new Map(selected.map((account) => [account.id, account])) + const itemCounts = new Map() const items = merged.entries.flatMap(({ event, documentId, accountId }) => { const account = byId.get(accountId) if (!account) return [] + itemCounts.set(accountId, (itemCounts.get(accountId) ?? 0) + 1) const { document } = event return [ { @@ -401,26 +401,27 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ }) const stalled = new Set(merged.stalled) for (const read of reads) { - if (!read.ok) { - statuses.push({ - ...failureStatus(read.account, read.error, organizationId), - itemCount: 0, - }) + const account = byId.get(read.accountId) + if (!account) continue + if (!read.read) { + statuses.push(failureStatus(account, read.error, organizationId)) continue } - const partial = read.partial || stalled.has(read.account.id) - statuses.push({ - source: read.account.provider, - accountId: read.account.id, - displayName: read.account.displayName, - status: partial ? 'partial' : 'ok', - ...(stalled.has(read.account.id) - ? { message: 'More activity at one instant than a page can return; later pages skip it.' } - : read.partial && read.message - ? { message: read.message } - : {}), - itemCount: items.filter((item) => item.accountId === read.account.id).length, - }) + const stopped = stalled.has(account.id) + statuses.push( + accountStatus(account, { + status: read.partial || stopped ? 'partial' : 'ok', + ...(stopped + ? { + message: + 'More activity at one instant than a page can return; later pages skip it.', + } + : read.partial && read.message + ? { message: read.message } + : {}), + itemCount: itemCounts.get(account.id) ?? 0, + }) + ) } const nextCursor = merged.next ? writeActivityCursor( diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index 3dd8d1cd07d..cbdfebf49f8 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -2,7 +2,6 @@ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js' import { requirePrincipalSubjectUserId } from '@sim/auth/principal' import { safeCompare } from '@sim/security/compare' import { hmacSha256Hex } from '@sim/security/hmac' -import { mapWithConcurrency } from '@sim/utils/concurrency' import { canonicalJson } from '@sim/utils/object' import { compareStrings } from '@sim/utils/string' import { z } from 'zod' @@ -66,6 +65,13 @@ import { resolveListedLiveAccount, resolveLiveAccount, } from '@/lib/sim-search/live/accounts' +import { + candidateFor, + compareAccounts, + type LiveCandidate, + safeContent, + verifyCandidates, +} from '@/lib/sim-search/live/candidates' import { dateSortDirection, hasDateBounds, @@ -83,7 +89,6 @@ import { import { isManagedSearchMcpProvider } from '@/lib/sim-search/live/managed-mcp-config' import { joinMessages } from '@/lib/sim-search/live/pages' import { loadLiveSearchPolicies } from '@/lib/sim-search/live/policy-store' -import { LIVE_SEARCH_PROVIDER_IDS } from '@/lib/sim-search/live/provider-catalog' import { filtersByPerson, liveSearchGuidance } from '@/lib/sim-search/live/providers' import { LiveReadError } from '@/lib/sim-search/live/read-error' import { encodedWindowEnd, READ_WINDOW_CHARACTERS } from '@/lib/sim-search/live/read-window' @@ -96,7 +101,6 @@ import { } from '@/lib/sim-search/live/reference' import { queryRelevance } from '@/lib/sim-search/live/text-match' import type { LiveAccount, NativeDocument } from '@/lib/sim-search/live/types' -import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' const boundContinuationSchema = z @@ -171,13 +175,6 @@ interface LiveSearchOptions { } export type LiveSearchInput = ResourceOwner & LiveSearchOptions -export function safeContent(content: string, registry?: ResolvedSecretTraceRegistry): string { - if (!registry) return content - const projected = projectResolvedSecretModelContent(content, registry) - if (!projected.safe || typeof projected.value !== 'string') - throw new Error('Search content projection is unavailable') - return projected.value -} export function matchesLiveFilters( document: NativeDocument, documentId: string, @@ -205,35 +202,6 @@ export function matchesLiveFilters( } return true } -/** A provider result with the ID that locates it within its account. */ -export interface LiveCandidate { - document: NativeDocument - documentId: string -} - -export function candidateFor( - document: NativeDocument, - account: LiveAccount, - owner: string -): LiveCandidate { - return { - document, - documentId: encodeLiveReference( - { - account: account.id, - provider: account.provider, - id: document.id, - ...(document.container ? { container: document.container } : {}), - ...(document.kind ? { kind: document.kind } : {}), - ...(document.revision ? { revision: document.revision } : {}), - ...(document.connectionBinding ? { connectionBinding: document.connectionBinding } : {}), - ...(document.threadId ? { threadId: document.threadId } : {}), - }, - owner - ), - } -} - function resultFor( { document, documentId }: LiveCandidate, account: LiveAccount, @@ -284,8 +252,6 @@ const SEARCH_DEADLINE_MS = 20_000 const ACCOUNT_DEADLINE_MS = 12_000 /** An account reaching its turn with less than this left before its deadline is not searched. */ const ACCOUNT_START_FLOOR_MS = 1500 -/** Candidates verified at once; each verification is one or more provider requests. */ -const VERIFY_CONCURRENCY = 5 const MAX_ACCOUNTS = 20 /** Account status when a merge cut results that its cursor would skip. */ @@ -325,35 +291,6 @@ function readWindowEnd(content: string, start: number, scaledWindow: boolean | u : standardEnd } -/** - * Verifies candidates in rank order. A revoked grant fails the whole account; any other - * verification failure only omits that candidate, and is reported as incomplete coverage. - */ -export async function verifyCandidates( - session: LiveAccountSession, - candidates: LiveCandidate[], - onVerified?: (candidate: LiveCandidate, permitted: boolean) => void -) { - const outcomes = await mapWithConcurrency(candidates, VERIFY_CONCURRENCY, async (candidate) => { - const outcome = await session.verify(candidate.document).then( - (permitted) => (permitted ? ('permitted' as const) : ('denied' as const)), - (error: unknown) => { - if (error instanceof NativeSearchError && error.status === 'reconnect') throw error - return error instanceof NativeSearchError && error.status === 'rate_limited' - ? ('rate_limited' as const) - : ('unverified' as const) - } - ) - onVerified?.(candidate, outcome === 'permitted') - return outcome - }) - return { - permitted: candidates.filter((_, index) => outcomes[index] === 'permitted'), - unverified: outcomes.some((outcome) => outcome === 'unverified' || outcome === 'rate_limited'), - rateLimited: outcomes.includes('rate_limited'), - } -} - /** Top results per account read for a passage when their provider returns only an excerpt. */ const PREVIEW_READS = 3 /** A slow preview read keeps the provider's excerpt rather than delaying the search. */ @@ -449,16 +386,6 @@ function targetsAccount(query: NativeSearchQuery, account: LiveAccount): boolean return query.provider === account.provider && (!query.accountId || query.accountId === account.id) } -/** Stable account order so equal-rank results from different accounts always merge the same way. */ -export function compareAccounts(left: LiveAccount, right: LiveAccount): number { - return ( - LIVE_SEARCH_PROVIDER_IDS.indexOf(left.provider) - - LIVE_SEARCH_PROVIDER_IDS.indexOf(right.provider) || - compareStrings(left.displayName, right.displayName) || - compareStrings(left.id, right.id) - ) -} - /** The page where the caller connects their own accounts in this scope. */ export function liveIntegrationsUrl(owner: ResourceOwner): string { const path = owner.organizationId diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 698994ba8c9..10a0dc2b593 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -1,4 +1,4 @@ -import { MAX_ACTIVITY_COLLABORATORS, oldestInstant } from '@/lib/sim-search/live/activity-page' +import { collaboratorNames, oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates' import { array, @@ -259,16 +259,7 @@ export async function searchAtlassian( const field = provider === 'jira' ? 'updated' : 'lastmodified' const person = await atlassianPersonClause(client, provider, input.involving, selected) const scope = - [ - policyScope, - person, - dates.start - ? `${field} >= "${new Date(Date.parse(dates.start) - 86400000).toISOString().slice(0, 10)}"` - : '', - dates.end - ? `${field} <= "${new Date(Date.parse(dates.end) + 86400000).toISOString().slice(0, 10)}"` - : '', - ] + [policyScope, person, ...atlassianDateClauses(field, dates.start, dates.end)] .filter(Boolean) .join(' AND ') || undefined const direction = dateSortDirection(input.filters) @@ -385,49 +376,66 @@ export async function searchAtlassian( const MAX_ACTIVITY_SITES = 4 /** - * JQL and CQL compare dates in the member's profile time zone at day or minute precision, so each - * bound is widened by a day; the caller checks every returned instant exactly. + * JQL and CQL compare dates in the member's profile time zone at day precision, so each bound is + * widened by a day; returned instants are checked exactly. */ -function activityDay(instant: string, offsetDays: number): string { - return new Date(Date.parse(instant) + offsetDays * 86_400_000).toISOString().slice(0, 10) +function atlassianDateClauses(field: string, start?: string, end?: string): string[] { + const day = (instant: string, offsetDays: number) => + new Date(Date.parse(instant) + offsetDays * 86_400_000).toISOString().slice(0, 10) + return [ + start ? `${field} >= "${day(start, -1)}"` : '', + end ? `${field} <= "${day(end, 1)}"` : '', + ].filter(Boolean) } -function activityRange(field: string, input: NativeActivityInput): string { - return `${field} >= "${activityDay(input.start, -1)}" AND ${field} <= "${activityDay(input.end, 1)}"` +/** A JQL or CQL query of every clause given, newest first by `field`. */ +function activityQuery(clauses: (string | undefined)[], field: string): string { + return `${clauses.filter(Boolean).join(' AND ')} ORDER BY ${field} DESC` } function displayNames(people: unknown[], except?: string): string[] { - return [ - ...new Set( - people - .map(object) - .filter((person) => string(person.accountId) && string(person.accountId) !== except) - .map((person) => string(person.displayName)) - .filter(Boolean) - ), - ].slice(0, MAX_ACTIVITY_COLLABORATORS) + return collaboratorNames( + people + .map(object) + .filter((person) => string(person.accountId) && string(person.accountId) !== except) + .map((person) => string(person.displayName)) + ) +} + +/** The base URL of a site's pages, without a trailing slash. */ +function siteOrigin(site: Record): string { + return string(site.url).replace(/\/$/, '') } /** - * One Jira listing ordered newest first by `field`: issues the member reported, by creation, or - * issues assigned to them, by their last update. Jira's `updatedBy()` cannot be bounded reliably - * by date, so an assigned issue's time is its last update, by anyone. + * The two Jira listings: issues the member reported, by creation, and issues assigned to them, by + * last update. Jira's `updatedBy()` cannot be bounded reliably by date, so an assigned issue's + * time is its last update, by anyone. */ +const JIRA_ACTIVITY = { + created: { field: 'created', self: 'reporter', other: 'assignee' }, + assigned: { field: 'updated', self: 'assignee', other: 'reporter' }, +} as const + async function jiraActivityStream( client: NativeClient, site: Record, input: NativeActivityInput, - kind: 'created' | 'assigned' + kind: keyof typeof JIRA_ACTIVITY ): Promise { const cloudId = string(site.id) - const field = kind === 'created' ? 'created' : 'updated' - const person = kind === 'created' ? 'reporter = currentUser()' : 'assignee = currentUser()' + const { field, self, other } = JIRA_ACTIVITY[kind] const data = object( await client.json(`/ex/jira/${segment(cloudId)}/rest/api/3/search/jql`, { body: { - jql: `${[policyClause('jira', input.policy), person, activityRange(field, input)] - .filter(Boolean) - .join(' AND ')} ORDER BY ${field} DESC`, + jql: activityQuery( + [ + policyClause('jira', input.policy), + `${self} = currentUser()`, + ...atlassianDateClauses(field, input.start, input.end), + ], + field + ), maxResults: input.limit, fields: [ 'summary', @@ -444,22 +452,17 @@ async function jiraActivityStream( }) ) const rows = array(data.issues) - const origin = string(site.url).replace(/\/$/, '') return { events: rows.flatMap((row): NativeActivityEvent[] => { const fields = object(row.fields) const at = string(fields[field]) if (!Number.isFinite(Date.parse(at))) return [] - const self = object(kind === 'created' ? fields.reporter : fields.assignee) return [ { - document: issue(row, cloudId, origin), + document: issue(row, cloudId, siteOrigin(site)), at: new Date(at).toISOString(), action: kind, - collaborators: displayNames( - kind === 'created' ? [fields.assignee] : [fields.reporter], - string(self.accountId) - ), + collaborators: displayNames([fields[other]], string(object(fields[self]).accountId)), ...(kind === 'assigned' ? { approximateTime: true as const } : {}), }, ] @@ -469,6 +472,36 @@ async function jiraActivityStream( } } +/** One Confluence CQL listing for activity: its rows and whether more follow. */ +async function confluenceActivitySearch( + client: NativeClient, + site: Record, + input: NativeActivityInput, + clauses: string[], + field: string, + expand: string +) { + const data = object( + await client.json(`/ex/confluence/${segment(string(site.id))}/wiki/rest/api/search`, { + query: { + cql: activityQuery( + [ + clauses[0], + policyClause('confluence', input.policy), + ...clauses.slice(1), + ...atlassianDateClauses(field, input.start, input.end), + ], + field + ), + limit: String(input.limit), + expand, + }, + signal: input.signal, + }) + ) + return { rows: array(data.results), more: Boolean(string(object(data._links).next)) } +} + /** * Pages and blog posts the member contributed to, newest first by last modification. When the * last version is the member's, its time is their edit; otherwise the time is someone else's @@ -480,29 +513,17 @@ async function confluencePageStream( input: NativeActivityInput, accountId: string ): Promise { - const cloudId = string(site.id) - const origin = string(site.url).replace(/\/$/, '') - const data = object( - await client.json(`/ex/confluence/${segment(cloudId)}/wiki/rest/api/search`, { - query: { - cql: `${[ - 'type IN (page, blogpost)', - policyClause('confluence', input.policy), - 'contributor = currentUser()', - activityRange('lastmodified', input), - ] - .filter(Boolean) - .join(' AND ')} ORDER BY lastmodified DESC`, - limit: String(input.limit), - expand: 'content.version,content.space,content.history', - }, - signal: input.signal, - }) + const { rows, more } = await confluenceActivitySearch( + client, + site, + input, + ['type IN (page, blogpost)', 'contributor = currentUser()'], + 'lastmodified', + 'content.version,content.space,content.history' ) - const rows = array(data.results) return { events: rows.flatMap((row): NativeActivityEvent[] => { - const document = page(row, cloudId, origin) + const document = page(row, string(site.id), siteOrigin(site)) const content = object(row.content) const version = object(content.version) if (!document?.modifiedAt || !Number.isFinite(Date.parse(document.modifiedAt))) return [] @@ -520,7 +541,7 @@ async function confluencePageStream( }, ] }), - more: Boolean(string(object(data._links).next)), + more, scannedTo: oldestInstant( rows.map( (row) => string(object(object(row.content).version).when) || string(row.lastModified) @@ -539,25 +560,14 @@ async function confluenceCommentStream( input: NativeActivityInput ): Promise { const cloudId = string(site.id) - const origin = string(site.url).replace(/\/$/, '') - const data = object( - await client.json(`/ex/confluence/${segment(cloudId)}/wiki/rest/api/search`, { - query: { - cql: `${[ - 'type = comment', - policyClause('confluence', input.policy), - 'creator = currentUser()', - activityRange('created', input), - ] - .filter(Boolean) - .join(' AND ')} ORDER BY created DESC`, - limit: String(input.limit), - expand: 'content.container,content.history,content.space', - }, - signal: input.signal, - }) + const { rows, more } = await confluenceActivitySearch( + client, + site, + input, + ['type = comment', 'creator = currentUser()'], + 'created', + 'content.container,content.history,content.space' ) - const rows = array(data.results) const createdAt = (row: Record) => string(object(object(row.content).history).createdDate) return { @@ -577,7 +587,7 @@ async function confluenceCommentStream( ...(spaceKey ? { accessMetadata: { spaceKey } } : {}), container: cloudId, title: string(container.title) || string(row.title), - url: `${origin}/wiki${string(object(content._links).webui) || string(row.url)}`, + url: `${siteOrigin(site)}/wiki${string(object(content._links).webui) || string(row.url)}`, content: providerText(string(row.excerpt).replace(/@@@(?:end)?hl@@@/g, ''), 'html'), modifiedAt: at, }, @@ -587,7 +597,7 @@ async function confluenceCommentStream( }, ] }), - more: Boolean(string(object(data._links).next)), + more, scannedTo: oldestInstant(rows.map(createdAt)), } } diff --git a/apps/sim/lib/sim-search/live/candidates.ts b/apps/sim/lib/sim-search/live/candidates.ts new file mode 100644 index 00000000000..03c662a28c5 --- /dev/null +++ b/apps/sim/lib/sim-search/live/candidates.ts @@ -0,0 +1,89 @@ +import { mapWithConcurrency } from '@sim/utils/concurrency' +import { compareStrings } from '@sim/utils/string' +import type { LiveAccountSession } from '@/lib/sim-search/live/account-session' +import { NativeSearchError } from '@/lib/sim-search/live/http' +import { LIVE_SEARCH_PROVIDER_IDS } from '@/lib/sim-search/live/provider-catalog' +import { encodeLiveReference } from '@/lib/sim-search/live/reference' +import type { LiveAccount, NativeDocument } from '@/lib/sim-search/live/types' +import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' +import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' + +/** Candidates verified at once; each verification is one or more provider requests. */ +const VERIFY_CONCURRENCY = 5 + +/** Provider text as the caller may see it: resolved secrets the run supplied are projected out. */ +export function safeContent(content: string, registry?: ResolvedSecretTraceRegistry): string { + if (!registry) return content + const projected = projectResolvedSecretModelContent(content, registry) + if (!projected.safe || typeof projected.value !== 'string') + throw new Error('Search content projection is unavailable') + return projected.value +} + +/** A provider result with the ID that locates it within its account. */ +export interface LiveCandidate { + document: NativeDocument + documentId: string +} + +export function candidateFor( + document: NativeDocument, + account: LiveAccount, + owner: string +): LiveCandidate { + return { + document, + documentId: encodeLiveReference( + { + account: account.id, + provider: account.provider, + id: document.id, + ...(document.container ? { container: document.container } : {}), + ...(document.kind ? { kind: document.kind } : {}), + ...(document.revision ? { revision: document.revision } : {}), + ...(document.connectionBinding ? { connectionBinding: document.connectionBinding } : {}), + ...(document.threadId ? { threadId: document.threadId } : {}), + }, + owner + ), + } +} + +/** + * Verifies candidates in rank order. A revoked grant fails the whole account; any other + * verification failure only omits that candidate, and is reported as incomplete coverage. + */ +export async function verifyCandidates( + session: LiveAccountSession, + candidates: LiveCandidate[], + onVerified?: (candidate: LiveCandidate, permitted: boolean) => void +) { + const outcomes = await mapWithConcurrency(candidates, VERIFY_CONCURRENCY, async (candidate) => { + const outcome = await session.verify(candidate.document).then( + (permitted) => (permitted ? ('permitted' as const) : ('denied' as const)), + (error: unknown) => { + if (error instanceof NativeSearchError && error.status === 'reconnect') throw error + return error instanceof NativeSearchError && error.status === 'rate_limited' + ? ('rate_limited' as const) + : ('unverified' as const) + } + ) + onVerified?.(candidate, outcome === 'permitted') + return outcome + }) + return { + permitted: candidates.filter((_, index) => outcomes[index] === 'permitted'), + unverified: outcomes.some((outcome) => outcome === 'unverified' || outcome === 'rate_limited'), + rateLimited: outcomes.includes('rate_limited'), + } +} + +/** Stable account order so equal-rank results from different accounts always merge the same way. */ +export function compareAccounts(left: LiveAccount, right: LiveAccount): number { + return ( + LIVE_SEARCH_PROVIDER_IDS.indexOf(left.provider) - + LIVE_SEARCH_PROVIDER_IDS.indexOf(right.provider) || + compareStrings(left.displayName, right.displayName) || + compareStrings(left.id, right.id) + ) +} diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index 73aa9f866f0..0be33090245 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -2,7 +2,7 @@ import { mapWithConcurrency } from '@sim/utils/concurrency' import { toArray } from '@sim/utils/object' import { compareStrings, truncate } from '@sim/utils/string' import { zonedWallClockToUtc } from '@sim/utils/timezone' -import { MAX_ACTIVITY_COLLABORATORS, oldestInstant } from '@/lib/sim-search/live/activity-page' +import { collaboratorNames, oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, hasDateBounds, @@ -234,11 +234,26 @@ const GMAIL_METADATA_CONCURRENCY = 10 /** Only the fields a result uses; labels double as member-policy evidence. */ const GMAIL_METADATA_FIELDS = 'id,labelIds,snippet,internalDate,payload/headers' +/** A message header's value by its lowercase name, or empty when the message has none. */ +function gmailHeader(row: Record, name: string): string { + return string( + array(object(row.payload).headers).find((h) => string(h.name).toLowerCase() === name)?.value + ) +} + +/** + * Gmail `after:`/`before:` take whole seconds and compare exclusively, so each bound widens by a + * second; results are checked against the exact instants. + */ +function gmailDateClauses(start?: string, end?: string): string[] { + return [ + start ? `after:${Math.floor(Date.parse(start) / 1000) - 1}` : '', + end ? `before:${Math.ceil(Date.parse(end) / 1000) + 1}` : '', + ].filter(Boolean) +} + function gmailDocument(row: Record): NativeDocument { - const payload = object(row.payload) - const headers = array(payload.headers) - const header = (name: string) => - string(headers.find((h) => string(h.name).toLowerCase() === name)?.value) + const header = (name: string) => gmailHeader(row, name) const timestamp = Number(row.internalDate) return { ...(Array.isArray(row.labelIds) @@ -276,8 +291,7 @@ export async function searchGmail( const query = [ text ? (dates.start || dates.end || person ? `(${text})` : text) : '', person, - dates.start ? `after:${Math.floor(Date.parse(dates.start) / 1000) - 1}` : '', - dates.end ? `before:${Math.ceil(Date.parse(dates.end) / 1000) + 1}` : '', + ...gmailDateClauses(dates.start, dates.end), ] .filter(Boolean) .join(' ') @@ -337,7 +351,7 @@ export async function gmailActivity( const data = object( await client.json('/gmail/v1/users/me/messages', { query: { - q: `in:sent after:${Math.floor(Date.parse(input.start) / 1000) - 1} before:${Math.ceil(Date.parse(input.end) / 1000) + 1}`, + q: ['in:sent', ...gmailDateClauses(input.start, input.end)].join(' '), maxResults: String(Math.min(input.limit, GMAIL_ACTIVITY_PAGE_SIZE)), }, }) @@ -356,16 +370,14 @@ export async function gmailActivity( }) ) ) - const documents = rows.map((row) => { - const headers = array(object(row.payload).headers) - const header = (name: string) => - string(headers.find((h) => string(h.name).toLowerCase() === name)?.value) - return { - document: gmailDocument(row), - replied: Boolean(header('in-reply-to')), - recipients: [...mailParticipants(header('to')), ...mailParticipants(header('cc'))], - } - }) + const documents = rows.map((row) => ({ + document: gmailDocument(row), + replied: Boolean(gmailHeader(row, 'in-reply-to')), + recipients: [ + ...mailParticipants(gmailHeader(row, 'to')), + ...mailParticipants(gmailHeader(row, 'cc')), + ], + })) return { streams: [ { @@ -376,7 +388,7 @@ export async function gmailActivity( document, at: document.modifiedAt, action: replied ? ('replied' as const) : ('sent' as const), - collaborators: [...new Set(recipients)].slice(0, MAX_ACTIVITY_COLLABORATORS), + collaborators: collaboratorNames(recipients), }, ] : [] @@ -795,7 +807,7 @@ function attendedMeeting(event: Record): boolean { } /** - * Meetings on the member's primary calendar that started in the window, up to now. Calendar + * Meetings on the member's primary calendar that started in the window. Calendar * lists a window oldest first, so the whole window is read (up to a bounded number of pages) * and ordered newest first here; a window with more meetings than that reports partial coverage. */ @@ -803,8 +815,6 @@ export async function calendarActivity( client: NativeClient, input: NativeActivityInput ): Promise { - const end = Math.min(Date.parse(input.end), Date.now()) - if (end < Date.parse(input.start)) return { streams: [{ events: [], more: false }] } const events: Record[] = [] let timeZone = '' let pageToken: string | undefined @@ -813,7 +823,7 @@ export async function calendarActivity( await client.json('/calendar/v3/calendars/primary/events', { query: { timeMin: input.start, - timeMax: new Date(end + 1).toISOString(), + timeMax: new Date(Date.parse(input.end) + 1).toISOString(), singleEvents: 'true', orderBy: 'startTime', maxResults: '250', @@ -845,11 +855,11 @@ export async function calendarActivity( at: document.eventStartAt, action: 'attended' as const, collaborators: includeAttendees - ? array(event.attendees) - .filter((attendee) => attendee.self !== true && attendee.resource !== true) - .map((attendee) => string(attendee.displayName) || string(attendee.email)) - .filter(Boolean) - .slice(0, MAX_ACTIVITY_COLLABORATORS) + ? collaboratorNames( + array(event.attendees) + .filter((attendee) => attendee.self !== true && attendee.resource !== true) + .map((attendee) => string(attendee.displayName) || string(attendee.email)) + ) : [], }, ] diff --git a/apps/sim/lib/sim-search/live/types.ts b/apps/sim/lib/sim-search/live/types.ts index c2c7b3a4382..8584ad20560 100644 --- a/apps/sim/lib/sim-search/live/types.ts +++ b/apps/sim/lib/sim-search/live/types.ts @@ -1,5 +1,6 @@ import type { WorkspaceSearchFilters } from '@/lib/api/contracts/knowledge' import type { + ActivityAction, LiveSearchProvider, NativeSearchQuery, } from '@/lib/api/contracts/mothership-assistant-tools' @@ -129,17 +130,6 @@ export interface NativeSearchInput { signal?: AbortSignal } -/** What the connected person did to an item, as one activity entry reports it. */ -export type ActivityAction = - | 'created' - | 'edited' - | 'commented' - | 'sent' - | 'replied' - | 'attended' - | 'assigned' - | 'mentioned' - /** * One account's activity request. `end` is inclusive so a continuation can resume at the instant * an earlier page stopped; the caller drops entries it already returned at that instant. From fa9053f7d9e376e15d6c23dda0b786898d4a74cd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:00:19 -0800 Subject: [PATCH 03/13] chore(search): tighten activity test assertions and comments --- apps/sim/lib/mothership/chat/citation-evidence.ts | 3 +-- apps/sim/lib/sim-search/live/activity-providers.test.ts | 1 - apps/sim/lib/sim-search/live/activity.integration.ts | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/apps/sim/lib/mothership/chat/citation-evidence.ts b/apps/sim/lib/mothership/chat/citation-evidence.ts index fddcbb28061..71a0add0002 100644 --- a/apps/sim/lib/mothership/chat/citation-evidence.ts +++ b/apps/sim/lib/mothership/chat/citation-evidence.ts @@ -36,7 +36,7 @@ export function isWebResearchTool(toolName: string): boolean { /** * A result in retrieval's citation fields. A web page names its address `url` and its heading * `title`, and leaves its site name and summary to the link preview; a compacted page already - * carries the citation fields. An activity entry names its title, source, time and snippet. + * carries the citation fields. */ export function toCitationResult( toolName: string, @@ -82,7 +82,6 @@ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitat const output = parseCitationRecord(call.result.output) if (!output || output.success === false) continue const data = parseCitationRecord(output.data) ?? output - /** Activity lists its entries, each a source, under `items`. */ const list = call.name === 'list_my_activity' ? data.items : data.results const results = Array.isArray(list) ? list : [data] for (const raw of results) { diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts index 09f6f93ef7f..be5bc479908 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -59,7 +59,6 @@ describe('Slack activity', () => { : undefined ) const page = await slackActivity(api, WINDOW) - expect(page.streams).toHaveLength(1) const [stream] = page.streams expect(stream?.events.map((event) => [event.document.id, event.action])).toEqual([ ['1762300000.000200', 'replied'], diff --git a/apps/sim/lib/sim-search/live/activity.integration.ts b/apps/sim/lib/sim-search/live/activity.integration.ts index 9cb3f70cf27..169b4fac221 100644 --- a/apps/sim/lib/sim-search/live/activity.integration.ts +++ b/apps/sim/lib/sim-search/live/activity.integration.ts @@ -95,7 +95,7 @@ it('asks the member to connect each approved source that reports activity, and o it('refuses a delegation naming another member’s chat', async () => { const result = await listMyActivityServerTool.execute({}, turn(readerId, otherChat)) - expect(result).toMatchObject({ success: false }) + expect(result).toMatchObject({ success: false, message: 'Conversation not found' }) }) it('refuses a window longer than a quarter and a cursor it did not mint', async () => { From 5197f3a53e525a17833228843e81488807d79c7b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:17:15 -0800 Subject: [PATCH 04/13] fix(search): keep activity paging lossless across failures, busy days and comments Bounds never move later when an account recovers, a failed account is retried after a page with progress, Jira and Confluence read past items newer than the bound, Calendar reads newest week slices first, the window end stays exclusive, comments keep their own keys, Slack entries carry only the member's message, saved Assistant answers keep activity citations, and the type and lint gates pass. --- .../contracts/mothership-assistant-tools.ts | 7 +- .../lib/mothership/chat/citation-evidence.ts | 14 +- .../mothership/chat/retrieval-citations.ts | 3 +- .../sim-assistant-tools.generated.ts | 7 +- .../tools/server/knowledge/my-activity.ts | 2 +- .../lib/sim-search/live/activity-page.test.ts | 43 +++++ apps/sim/lib/sim-search/live/activity-page.ts | 34 ++-- .../live/activity-providers.test.ts | 27 +++ apps/sim/lib/sim-search/live/activity.ts | 28 ++-- apps/sim/lib/sim-search/live/atlassian.ts | 156 +++++++++++------- apps/sim/lib/sim-search/live/google.ts | 134 +++++++++------ apps/sim/lib/sim-search/live/slack.ts | 9 +- apps/sim/lib/sim-search/live/types.ts | 2 +- 13 files changed, 319 insertions(+), 147 deletions(-) diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index b69d36f2b8a..3c9e07b6090 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -394,7 +394,10 @@ export function refineActivityWindow( path: ['endDate'], message: 'endDate must be after startDate.', }) - else if (end - start > MAX_ACTIVITY_WINDOW_DAYS * 86_400_000) + /** A later endDate reads up to now, so the span counts only up to now. */ else if ( + Math.min(end, Date.now()) - start > + MAX_ACTIVITY_WINDOW_DAYS * 86_400_000 + ) context.addIssue({ code: 'custom', path: ['startDate'], @@ -409,7 +412,7 @@ export const listMyActivityInputSchema = * How one source served a multi-source result. `not_connected` and `reconnect` carry `connect`: * the provider to connect and the page where the caller connects it. */ -export const liveSourceStatusSchema = z.object({ +const liveSourceStatusSchema = z.object({ source: liveSearchProviderSchema, accountId: z.string().optional(), displayName: z.string().optional(), diff --git a/apps/sim/lib/mothership/chat/citation-evidence.ts b/apps/sim/lib/mothership/chat/citation-evidence.ts index 71a0add0002..8a54f8abc40 100644 --- a/apps/sim/lib/mothership/chat/citation-evidence.ts +++ b/apps/sim/lib/mothership/chat/citation-evidence.ts @@ -42,7 +42,7 @@ export function toCitationResult( toolName: string, result: Record ): Record { - if (toolName === 'list_my_activity') + if (toolName === 'list_my_activity' && typeof result.documentName !== 'string') return { citationId: result.citationId, citationUrl: result.citationUrl, @@ -72,6 +72,15 @@ export function parseCitationRecord(value: unknown): Record | n return toRecordOrNull(value) } +/** + * The entries of one tool result that may each be a source. Activity lists its entries under + * `items`; a saved result, once compacted, keeps them under `results` like every other tool. + */ +export function citationResults(toolName: string, data: Record): unknown[] { + if (toolName === 'list_my_activity' && Array.isArray(data.items)) return data.items + return Array.isArray(data.results) ? data.results : [data] +} + /** Only successful retrieval and web research results may supply source destinations. */ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitationBlock[]) { const evidence = new Map() @@ -82,8 +91,7 @@ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitat const output = parseCitationRecord(call.result.output) if (!output || output.success === false) continue const data = parseCitationRecord(output.data) ?? output - const list = call.name === 'list_my_activity' ? data.items : data.results - const results = Array.isArray(list) ? list : [data] + const results = citationResults(call.name, data) for (const raw of results) { const record = parseCitationRecord(raw) const result = record && toCitationResult(call.name, record) diff --git a/apps/sim/lib/mothership/chat/retrieval-citations.ts b/apps/sim/lib/mothership/chat/retrieval-citations.ts index 9a7c2c0a580..fb91b4156ed 100644 --- a/apps/sim/lib/mothership/chat/retrieval-citations.ts +++ b/apps/sim/lib/mothership/chat/retrieval-citations.ts @@ -1,5 +1,6 @@ import { isRecordLike } from '@sim/utils/object' import { + citationResults, isCitationTool, isWebResearchTool, toCitationResult, @@ -21,7 +22,7 @@ export function compactRetrievalCitations(toolName: string, raw: unknown): unkno } if (!isRecordLike(output) || output.success === false) return undefined const data = isRecordLike(output.data) ? output.data : output - const results = Array.isArray(data.results) ? data.results : [data] + const results = citationResults(toolName, data) // A live document reference permits 4,000 characters, plus the document: citation prefix. const citations = results.slice(0, 50).flatMap((raw) => { const item = isRecordLike(raw) ? toCitationResult(toolName, raw) : raw diff --git a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts index a722af6fe2c..8b760a222f7 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -414,7 +414,10 @@ export function refineActivityWindow( path: ['endDate'], message: 'endDate must be after startDate.', }) - else if (end - start > MAX_ACTIVITY_WINDOW_DAYS * 86_400_000) + /** A later endDate reads up to now, so the span counts only up to now. */ else if ( + Math.min(end, Date.now()) - start > + MAX_ACTIVITY_WINDOW_DAYS * 86_400_000 + ) context.addIssue({ code: 'custom', path: ['startDate'], @@ -429,7 +432,7 @@ export const listMyActivityInputSchema = * How one source served a multi-source result. `not_connected` and `reconnect` carry `connect`: * the provider to connect and the page where the caller connects it. */ -export const liveSourceStatusSchema = z.object({ +const liveSourceStatusSchema = z.object({ source: liveSearchProviderSchema, accountId: z.string().optional(), displayName: z.string().optional(), diff --git a/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts b/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts index 6062166dc69..a92f9722561 100644 --- a/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts +++ b/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts @@ -46,7 +46,7 @@ export const listMyActivityServerTool: BaseServerTool = { unconnected.length ? `Not read: ${unconnected.map((source) => source.source).join(', ')}. Offer to connect each with oauth_get_auth_link using its connect.providerId.` : '', - 'Cite entries as {"id":""}.', + 'Cite entries with a non-null citationUrl as {"id":""}.', ] .filter(Boolean) .join(' '), diff --git a/apps/sim/lib/sim-search/live/activity-page.test.ts b/apps/sim/lib/sim-search/live/activity-page.test.ts index 4beef5250af..acd973e2302 100644 --- a/apps/sim/lib/sim-search/live/activity-page.test.ts +++ b/apps/sim/lib/sim-search/live/activity-page.test.ts @@ -140,6 +140,49 @@ describe('mergeActivityPage', () => { expect(pages.flat()).toHaveLength(newestFirst(accounts).length) }) + it('carries a failed account to the next page when the others finish on this one', () => { + const accounts: FakeAccount[] = [ + { id: 'chat', limit: 50, items: [{ at: at(100), key: 'c1' }] }, + { id: 'mail', limit: 50, items: [{ at: at(90), key: 'm1' }] }, + ] + const { pages } = pageThrough( + accounts, + 10, + (accountId, page) => accountId === 'mail' && page === 0 + ) + expect(pages.flat()).toEqual(['chat:c1', 'mail:m1']) + }) + + it('returns no entry twice when a recovered account resumes above the others', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [ + { at: at(80), key: 'c1' }, + { at: at(70), key: 'c2' }, + { at: at(60), key: 'c3' }, + ], + }, + { + id: 'mail', + limit: 2, + items: [ + { at: at(95), key: 'm1' }, + { at: at(90), key: 'm2' }, + { at: at(50), key: 'm3' }, + ], + }, + ] + const { pages } = pageThrough( + accounts, + 1, + (accountId, page) => accountId === 'mail' && page === 0 + ) + expect(pages.flat()).toHaveLength(6) + expect(new Set(pages.flat()).size).toBe(6) + }) + it('ends without a continuation when only failed accounts would continue', () => { const result = mergeActivityPage( [{ accountId: 'mail', bound: { end: END, seen: [] }, read: false }], diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts index cd30d5dcd5a..39b2ac6ac3b 100644 --- a/apps/sim/lib/sim-search/live/activity-page.ts +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -80,8 +80,8 @@ function sameBound(left: ActivityBound, right: ActivityBound): boolean { * before the oldest instant it scanned; past the latest such instant of any stream with more, an * entry might be preceded by one not yet read. Entries before that horizon wait for the next * page, which reads every account again up to where this page stopped. An account that failed - * keeps its bound, so the next page retries it from there; a page with only failed accounts left - * has no continuation. + * keeps its bound, so the next page retries it from there; its entries, newer than the others' + * bounds, then arrive out of order on that page rather than being lost. */ export function mergeActivityPage( accounts: readonly AccountActivity[], @@ -143,17 +143,18 @@ export function mergeActivityPage( (!unfinished.has(account.accountId) && !remaining.has(account.accountId)) ) continue - const returnedAtResume = returned - .filter(({ entry, time }) => entry.accountId === account.accountId && time === resume) + /** + * A bound never moves later: an account that recovers after a failure resumes above the + * others, and moving theirs up to it would return their entries again. + */ + const ownEnd = Date.parse(account.bound.end) + const end = Math.min(resume, ownEnd) + const returnedAtEnd = returned + .filter(({ entry, time }) => entry.accountId === account.accountId && time === end) .map(({ entry }) => entry.key) const bound: ActivityBound = { - end: new Date(resume).toISOString(), - seen: [ - ...new Set([ - ...(Date.parse(account.bound.end) === resume ? account.bound.seen : []), - ...returnedAtResume, - ]), - ], + end: new Date(end).toISOString(), + seen: [...new Set([...(ownEnd === end ? account.bound.seen : []), ...returnedAtEnd])], } if (bound.seen.length > MAX_SEEN_AT_BOUND) { stalled.push(account.accountId) @@ -166,7 +167,16 @@ export function mergeActivityPage( const entries = returned.map(({ entry }) => entry) /** A page that moves no account's bound would be read again unchanged, so it ends here. */ if (continuing.length && !progressed) return { entries, stalled: [...stalled, ...continuing] } - return { entries, ...(continuing.length ? { next } : {}), stalled } + /** + * An account that failed is retried on the next page while this one made progress; a page + * where only failed accounts were left, and failed again, ends the listing. + */ + const retrying = accounts.some((account) => !account.read) + return { + entries, + ...(continuing.length || (retrying && entries.length) ? { next } : {}), + stalled, + } } const boundSchema = z.object({ diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts index be5bc479908..3fe30e372ac 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -122,6 +122,10 @@ describe('Calendar activity', () => { event('declined', 3, { attendees: [self('declined'), other] }), event('unanswered', 3, { attendees: [self('needsAction'), other] }), event('alone', 4, { organizer: { self: true }, attendees: [self('accepted')] }), + event('room', 4, { + organizer: { self: true }, + attendees: [self('accepted'), { email: 'room@x.com', resource: true }], + }), event('focus', 4, { eventType: 'focusTime', organizer: { self: true }, @@ -212,6 +216,29 @@ describe('Atlassian activity', () => { ]) }) + it('reads past a page of issues newer than the bound instead of stopping on it', async () => { + const issue = (key: string, created: string) => ({ + key, + fields: { summary: key, created, reporter: { accountId: 'me' } }, + }) + const api = client((path, options) => { + if (path === '/oauth/token/accessible-resources') return [site] + if (path !== '/ex/jira/cloud/rest/api/3/search/jql') return undefined + const body = (options as { body?: { jql?: string; nextPageToken?: string } } | undefined) + ?.body + if (!body?.jql?.includes('reporter = currentUser()')) return { issues: [] } + return body.nextPageToken + ? { issues: [issue('ENG-1', '2026-11-07T10:00:00.000Z')] } + : { issues: [issue('ENG-3', '2026-11-08T10:00:00.000Z')], nextPageToken: 'p2' } + }) + const streams = (await atlassianActivity(api, 'jira', WINDOW)).streams + expect(streams.flatMap((stream) => stream.events.map((event) => event.document.id))).toEqual([ + 'ENG-3', + 'ENG-1', + ]) + expect(streams[0]).toMatchObject({ more: false, scannedTo: '2026-11-07T10:00:00.000Z' }) + }) + it('reports an assigned Jira issue at its last update, marked approximate', async () => { const api = client((path, options) => { if (path === '/oauth/token/accessible-resources') return [site] diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index e2e4afdd243..ed7ceb6687f 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -87,7 +87,7 @@ const INVALID_CURSOR_MESSAGE = 'Invalid cursor. Continue with the same startDate, endDate, source and topK, or start again without a cursor.' /** The window a first page reads: the requested bounds, defaulted and clamped to now. */ -function resolveWindow(input: ListMyActivityInput, now: number) { +function resolveWindow(input: { startDate?: string; endDate?: string }, now: number) { const requestedEnd = input.endDate ? Date.parse(input.endDate) : now const end = Math.min(requestedEnd, now) const start = input.startDate ? Date.parse(input.startDate) : end - DEFAULT_WINDOW_DAYS * DAY_MS @@ -263,18 +263,24 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ itemCount: 0, }) ), - ...eligible.slice(MAX_ACTIVITY_ACCOUNTS).map((account) => - accountStatus(account, { - status: 'failed', - reason: 'unavailable', - message: `One call reads at most ${MAX_ACTIVITY_ACCOUNTS} accounts. Pass source to read this one.`, - itemCount: 0, - }) - ), ] : [] + /** Every page reports the accounts no page reads, so its coverage never reads complete. */ + for (const account of eligible.slice(MAX_ACTIVITY_ACCOUNTS)) + statuses.push( + accountStatus(account, { + status: 'failed', + reason: 'unavailable', + message: `One call reads at most ${MAX_ACTIVITY_ACCOUNTS} accounts. Pass source to read this one.`, + itemCount: 0, + }) + ) + /** The window's end is exclusive; a continuation's bound is the inclusive instant it resumes at. */ const boundOf = (account: LiveAccount): ActivityBound => - cursor?.accounts[account.id] ?? { end: window.end, seen: [] } + cursor?.accounts[account.id] ?? { + end: new Date(Date.parse(window.end) - 1).toISOString(), + seen: [], + } const deadline = AbortSignal.timeout(ACTIVITY_DEADLINE_MS) const callSignal = input.signal ? AbortSignal.any([input.signal, deadline]) : deadline @@ -340,7 +346,7 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ if (!(error instanceof NativeSearchError)) logger.warn('Activity listing failed for an account', { provider: account.provider, - error: error instanceof Error ? error.message : String(error), + error: 'unexpected_error', }) return { accountId: account.id, diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 10a0dc2b593..6cad0c2dc11 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -402,6 +402,30 @@ function displayNames(people: unknown[], except?: string): string[] { ) } +/** Provider pages one listing may read to get past items newer than its end. */ +const MAX_ACTIVITY_PAGES = 3 + +/** + * Reads a newest-first listing until a page reaches items at or before `end`. The widened date + * range returns items newer than `end` first, which a continuation has already returned, so + * stopping at the first page would leave a busy day's older items unreachable. + */ +async function readPastEnd( + readPage: (cursor?: string) => Promise<{ rows: Record[]; next?: string }>, + sortKey: (row: Record) => string, + end: string +) { + const rows: Record[] = [] + let next: string | undefined + for (let page = 0; page < MAX_ACTIVITY_PAGES; page++) { + const result = await readPage(next) + rows.push(...result.rows) + next = result.next + if (!next || result.rows.some((row) => Date.parse(sortKey(row)) <= Date.parse(end))) break + } + return { rows, more: Boolean(next) } +} + /** The base URL of a site's pages, without a trailing slash. */ function siteOrigin(site: Record): string { return string(site.url).replace(/\/$/, '') @@ -425,33 +449,41 @@ async function jiraActivityStream( ): Promise { const cloudId = string(site.id) const { field, self, other } = JIRA_ACTIVITY[kind] - const data = object( - await client.json(`/ex/jira/${segment(cloudId)}/rest/api/3/search/jql`, { - body: { - jql: activityQuery( - [ - policyClause('jira', input.policy), - `${self} = currentUser()`, - ...atlassianDateClauses(field, input.start, input.end), - ], - field - ), - maxResults: input.limit, - fields: [ - 'summary', - 'description', - 'status', - 'created', - 'updated', - 'creator', - 'reporter', - 'assignee', - ], - }, - signal: input.signal, - }) + const sortKey = (row: Record) => string(object(row.fields)[field]) + const { rows, more } = await readPastEnd( + async (cursor) => { + const data = object( + await client.json(`/ex/jira/${segment(cloudId)}/rest/api/3/search/jql`, { + body: { + jql: activityQuery( + [ + policyClause('jira', input.policy), + `${self} = currentUser()`, + ...atlassianDateClauses(field, input.start, input.end), + ], + field + ), + maxResults: input.limit, + fields: [ + 'summary', + 'description', + 'status', + 'created', + 'updated', + 'creator', + 'reporter', + 'assignee', + ], + ...(cursor ? { nextPageToken: cursor } : {}), + }, + signal: input.signal, + }) + ) + return { rows: array(data.issues), next: string(data.nextPageToken) || undefined } + }, + sortKey, + input.end ) - const rows = array(data.issues) return { events: rows.flatMap((row): NativeActivityEvent[] => { const fields = object(row.fields) @@ -467,8 +499,8 @@ async function jiraActivityStream( }, ] }), - more: Boolean(string(data.nextPageToken)), - scannedTo: oldestInstant(rows.map((row) => string(object(row.fields)[field]))), + more, + scannedTo: oldestInstant(rows.map(sortKey)), } } @@ -479,27 +511,37 @@ async function confluenceActivitySearch( input: NativeActivityInput, clauses: string[], field: string, - expand: string + expand: string, + sortKey: (row: Record) => string ) { - const data = object( - await client.json(`/ex/confluence/${segment(string(site.id))}/wiki/rest/api/search`, { - query: { - cql: activityQuery( - [ - clauses[0], - policyClause('confluence', input.policy), - ...clauses.slice(1), - ...atlassianDateClauses(field, input.start, input.end), - ], - field - ), - limit: String(input.limit), - expand, - }, - signal: input.signal, - }) + const cql = activityQuery( + [ + clauses[0], + policyClause('confluence', input.policy), + ...clauses.slice(1), + ...atlassianDateClauses(field, input.start, input.end), + ], + field + ) + return readPastEnd( + async (cursor) => { + const data = object( + await client.json(`/ex/confluence/${segment(string(site.id))}/wiki/rest/api/search`, { + query: { cql, limit: String(input.limit), expand, ...(cursor ? { cursor } : {}) }, + signal: input.signal, + }) + ) + const next = string(object(data._links).next) + return { + rows: array(data.results), + next: next + ? (new URL(next, 'https://api.atlassian.com').searchParams.get('cursor') ?? undefined) + : undefined, + } + }, + sortKey, + input.end ) - return { rows: array(data.results), more: Boolean(string(object(data._links).next)) } } /** @@ -513,13 +555,16 @@ async function confluencePageStream( input: NativeActivityInput, accountId: string ): Promise { + const modifiedAt = (row: Record) => + string(object(object(row.content).version).when) || string(row.lastModified) const { rows, more } = await confluenceActivitySearch( client, site, input, ['type IN (page, blogpost)', 'contributor = currentUser()'], 'lastmodified', - 'content.version,content.space,content.history' + 'content.version,content.space,content.history', + modifiedAt ) return { events: rows.flatMap((row): NativeActivityEvent[] => { @@ -542,11 +587,7 @@ async function confluencePageStream( ] }), more, - scannedTo: oldestInstant( - rows.map( - (row) => string(object(object(row.content).version).when) || string(row.lastModified) - ) - ), + scannedTo: oldestInstant(rows.map(modifiedAt)), } } @@ -560,16 +601,17 @@ async function confluenceCommentStream( input: NativeActivityInput ): Promise { const cloudId = string(site.id) + const createdAt = (row: Record) => + string(object(object(row.content).history).createdDate) const { rows, more } = await confluenceActivitySearch( client, site, input, ['type = comment', 'creator = currentUser()'], 'created', - 'content.container,content.history,content.space' + 'content.container,content.history,content.space', + createdAt ) - const createdAt = (row: Record) => - string(object(object(row.content).history).createdDate) return { events: rows.flatMap((row): NativeActivityEvent[] => { const content = object(row.content) @@ -583,6 +625,8 @@ async function confluenceCommentStream( { document: { id: string(container.id), + /** Each comment is its own entry, though several read the same page. */ + dedupeKey: `comment:${string(content.id)}`, kind, ...(spaceKey ? { accessMetadata: { spaceKey } } : {}), container: cloudId, diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index 0be33090245..393c0a4c3d5 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -16,6 +16,7 @@ import { interleaveByRank } from '@/lib/sim-search/live/pages' import { permitsResources } from '@/lib/sim-search/live/policy' import { providerText } from '@/lib/sim-search/live/text' import type { + NativeActivityEvent, NativeActivityInput, NativeActivityPage, NativeClient, @@ -785,20 +786,26 @@ export async function searchCalendar( } } -/** Calendar event pages one activity call reads; the API lists a window oldest first. */ -const CALENDAR_ACTIVITY_PAGES = 4 +/** + * Calendar lists a range oldest first, so activity reads the window newest first in slices of + * this length, each read whole before the next older one. + */ +const CALENDAR_ACTIVITY_SLICE_MS = 7 * 86_400_000 +/** Calendar requests one activity call makes across its slices. */ +const CALENDAR_ACTIVITY_REQUESTS = 6 /** Personal blocks Calendar records as events, which nobody attends. */ const NON_MEETING_EVENT_TYPES = new Set(['focusTime', 'outOfOffice', 'workingLocation', 'birthday']) /** * Whether the connected member took part in a meeting: they organize it or accepted it, and - * someone else was invited. Declined and unanswered invitations are not attendance. + * another person (not a room) was invited. Declined and unanswered invitations are not attendance. */ function attendedMeeting(event: Record): boolean { if (event.status === 'cancelled' || NON_MEETING_EVENT_TYPES.has(string(event.eventType))) return false const attendees = array(event.attendees) - if (!attendees.some((attendee) => attendee.self !== true)) return false + if (!attendees.some((attendee) => attendee.self !== true && attendee.resource !== true)) + return false const self = attendees.find((attendee) => attendee.self === true) return ( object(event.organizer).self === true || @@ -807,71 +814,88 @@ function attendedMeeting(event: Record): boolean { } /** - * Meetings on the member's primary calendar that started in the window. Calendar - * lists a window oldest first, so the whole window is read (up to a bounded number of pages) - * and ordered newest first here; a window with more meetings than that reports partial coverage. + * Meetings on the member's primary calendar that started in the window, newest first. Slices + * of the window are read from its end backwards, each in full, until enough meetings are found; + * the start of the last slice read bounds what remains. A slice too full to read in the request + * budget yields nothing and reports partial coverage, since its newest meetings are the unread ones. */ export async function calendarActivity( client: NativeClient, input: NativeActivityInput ): Promise { - const events: Record[] = [] - let timeZone = '' - let pageToken: string | undefined - for (let page = 0; page < CALENDAR_ACTIVITY_PAGES; page++) { - const data = object( - await client.json('/calendar/v3/calendars/primary/events', { - query: { - timeMin: input.start, - timeMax: new Date(Date.parse(input.end) + 1).toISOString(), - singleEvents: 'true', - orderBy: 'startTime', - maxResults: '250', - showDeleted: 'false', - ...(pageToken ? { pageToken } : {}), - }, + const start = Date.parse(input.start) + /** Calendar ignores milliseconds, so the inclusive end rounds up to the next whole second. */ + let sliceEnd = (Math.floor(Date.parse(input.end) / 1000) + 1) * 1000 + const includeAttendees = input.policy?.includeAttendees !== false + const events: NativeActivityEvent[] = [] + let requests = 0 + let overfull = false + while (sliceEnd > start && requests < CALENDAR_ACTIVITY_REQUESTS && events.length < input.limit) { + const sliceStart = Math.max(start, sliceEnd - CALENDAR_ACTIVITY_SLICE_MS) + const slice: Record[] = [] + let timeZone = '' + let pageToken: string | undefined + do { + const data = object( + await client.json('/calendar/v3/calendars/primary/events', { + query: { + timeMin: new Date(sliceStart).toISOString(), + timeMax: new Date(sliceEnd).toISOString(), + singleEvents: 'true', + orderBy: 'startTime', + maxResults: '250', + showDeleted: 'false', + ...(pageToken ? { pageToken } : {}), + }, + signal: input.signal, + }) + ) + requests++ + timeZone ||= string(data.timeZone) + slice.push(...array(data.items)) + pageToken = string(data.nextPageToken) || undefined + } while (pageToken && requests < CALENDAR_ACTIVITY_REQUESTS) + if (pageToken) { + overfull = true + break + } + for (const event of slice.filter(attendedMeeting)) { + const document = { + ...eventDocument(event, 'primary', includeAttendees, timeZone || undefined), + dedupeKey: calendarOccurrenceKey(event), + } + const startedAt = Date.parse(document.eventStartAt ?? '') + /** timeMin bounds an event's end, so a meeting already under way is left to its own slice. */ + if (!document.eventStartAt || startedAt < sliceStart || startedAt >= sliceEnd) continue + events.push({ + document, + at: new Date(startedAt).toISOString(), + action: 'attended', + collaborators: includeAttendees + ? collaboratorNames( + array(event.attendees) + .filter((attendee) => attendee.self !== true && attendee.resource !== true) + .map((attendee) => string(attendee.displayName) || string(attendee.email)) + ) + : [], }) - ) - timeZone ||= string(data.timeZone) - events.push(...array(data.items)) - pageToken = string(data.nextPageToken) || undefined - if (!pageToken) break + } + sliceEnd = sliceStart } - const includeAttendees = input.policy?.includeAttendees !== false + const more = sliceEnd > start return { streams: [ { - events: events - .filter(attendedMeeting) - .flatMap((event) => { - const document = { - ...eventDocument(event, 'primary', includeAttendees, timeZone || undefined), - dedupeKey: calendarOccurrenceKey(event), - } - if (!document.eventStartAt) return [] - return [ - { - document, - at: document.eventStartAt, - action: 'attended' as const, - collaborators: includeAttendees - ? collaboratorNames( - array(event.attendees) - .filter((attendee) => attendee.self !== true && attendee.resource !== true) - .map((attendee) => string(attendee.displayName) || string(attendee.email)) - ) - : [], - }, - ] - }) - .sort((left, right) => Date.parse(right.at) - Date.parse(left.at)), - more: false, + events: events.sort((left, right) => Date.parse(right.at) - Date.parse(left.at)), + more, + ...(more ? { scannedTo: new Date(sliceEnd).toISOString() } : {}), }, ], - ...(pageToken + ...(overfull ? { partial: true, - message: 'This window holds more meetings than one call reads. Narrow the dates.', + message: + 'A week in this window holds more meetings than one call reads. Narrow the dates.', } : {}), } diff --git a/apps/sim/lib/sim-search/live/slack.ts b/apps/sim/lib/sim-search/live/slack.ts index 4ecd7142649..e86adb3c4e1 100644 --- a/apps/sim/lib/sim-search/live/slack.ts +++ b/apps/sim/lib/sim-search/live/slack.ts @@ -280,7 +280,8 @@ export async function slackActivity( }, undefined, Math.min(input.limit, SLACK_PAGE_SIZE), - 'from:me' + 'from:me', + false ) const messages = page.documents.filter((document) => document.kind !== 'file') return { @@ -313,7 +314,9 @@ async function searchSlackPage( input: NativeSearchInput, cursor: string | undefined, limit: number, - person: string | undefined + person: string | undefined, + /** Surrounding messages in each result's text; activity wants only the member's own words. */ + context = true ): Promise { const channels = [ ['public_channel', 'search:read.public'], @@ -353,7 +356,7 @@ async function searchSlackPage( ...(input.scopes.includes('search:read.files') ? ['files'] : []), ...(listChannels ? ['channels'] : []), ], - include_context_messages: true, + include_context_messages: context, limit: Math.min(limit, SLACK_PAGE_SIZE), ...(dates.start ? { after: Math.floor(Date.parse(dates.start) / 1000) - 1 } : {}), ...(dates.end ? { before: Math.ceil(Date.parse(dates.end) / 1000) } : {}), diff --git a/apps/sim/lib/sim-search/live/types.ts b/apps/sim/lib/sim-search/live/types.ts index 8584ad20560..eb8b4408f9f 100644 --- a/apps/sim/lib/sim-search/live/types.ts +++ b/apps/sim/lib/sim-search/live/types.ts @@ -147,7 +147,7 @@ export interface NativeActivityInput { /** One thing the connected person did, at the time of the provider order the stream reads in. */ export interface NativeActivityEvent { document: NativeDocument - /** The instant this entry sorts by: never later than its stream's `scannedTo` when more remain. */ + /** The instant this entry sorts by: never earlier than its stream's `scannedTo` when more remain. */ at: string action: ActivityAction collaborators: string[] From 33d6406b6c155fa5cf0f8a422b814702d7f072de Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:32:07 -0800 Subject: [PATCH 05/13] fix(search): keep paging after a recovered source, name disconnected and unsupported sources A page that returned entries continues even when the remaining bounds stay put, continuations skip the span check against now, cursors name each account's source so a disconnected account is reported, an unsupported source filter is reported, Jira created means creator, and Slack activity requests no file hits. --- .../contracts/mothership-assistant-tools.ts | 7 ++-- .../sim-assistant-tools.generated.ts | 7 ++-- .../lib/sim-search/live/activity-page.test.ts | 29 ++++++++++++++ apps/sim/lib/sim-search/live/activity-page.ts | 12 +++++- .../live/activity-providers.test.ts | 4 +- apps/sim/lib/sim-search/live/activity.ts | 38 ++++++++++++++++++- apps/sim/lib/sim-search/live/atlassian.ts | 4 +- apps/sim/lib/sim-search/live/slack.ts | 3 +- 8 files changed, 90 insertions(+), 14 deletions(-) diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index 3c9e07b6090..2adea17f06a 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -372,7 +372,7 @@ export const listMyActivityInputFieldsSchema = z cursor: z .string() .min(1) - .max(8000) + .max(40_000) .optional() .describe( 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.' @@ -382,10 +382,11 @@ export const listMyActivityInputFieldsSchema = z /** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */ export function refineActivityWindow( - input: { startDate?: string; endDate?: string }, + input: { startDate?: string; endDate?: string; cursor?: string }, context: z.RefinementCtx ) { - if (!input.startDate || !input.endDate) return + /** A continuation reads the window its signed cursor fixed, however long ago that was. */ + if (!input.startDate || !input.endDate || input.cursor) return const start = Date.parse(input.startDate) const end = Date.parse(input.endDate) if (start >= end) diff --git a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts index 8b760a222f7..882c532a2d9 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -392,7 +392,7 @@ export const listMyActivityInputFieldsSchema = z cursor: z .string() .min(1) - .max(8000) + .max(40_000) .optional() .describe( 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.' @@ -402,10 +402,11 @@ export const listMyActivityInputFieldsSchema = z /** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */ export function refineActivityWindow( - input: { startDate?: string; endDate?: string }, + input: { startDate?: string; endDate?: string; cursor?: string }, context: z.RefinementCtx ) { - if (!input.startDate || !input.endDate) return + /** A continuation reads the window its signed cursor fixed, however long ago that was. */ + if (!input.startDate || !input.endDate || input.cursor) return const start = Date.parse(input.startDate) const end = Date.parse(input.endDate) if (start >= end) diff --git a/apps/sim/lib/sim-search/live/activity-page.test.ts b/apps/sim/lib/sim-search/live/activity-page.test.ts index acd973e2302..e5ae9d0de72 100644 --- a/apps/sim/lib/sim-search/live/activity-page.test.ts +++ b/apps/sim/lib/sim-search/live/activity-page.test.ts @@ -183,6 +183,35 @@ describe('mergeActivityPage', () => { expect(new Set(pages.flat()).size).toBe(6) }) + it('keeps paging the others after a recovered account catches up and finishes', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [ + { at: at(80), key: 'c1' }, + { at: at(70), key: 'c2' }, + { at: at(60), key: 'c3' }, + ], + }, + { + id: 'mail', + limit: 2, + items: [ + { at: at(95), key: 'm1' }, + { at: at(90), key: 'm2' }, + ], + }, + ] + const { pages, stalled } = pageThrough( + accounts, + 1, + (accountId, page) => accountId === 'mail' && page === 0 + ) + expect(new Set(pages.flat())).toEqual(new Set(newestFirst(accounts))) + expect(stalled).toEqual([]) + }) + it('ends without a continuation when only failed accounts would continue', () => { const result = mergeActivityPage( [{ accountId: 'mail', bound: { end: END, seen: [] }, read: false }], diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts index 39b2ac6ac3b..89ab1d01109 100644 --- a/apps/sim/lib/sim-search/live/activity-page.ts +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -37,6 +37,8 @@ export function oldestInstant(values: readonly (string | undefined)[]): string | export interface ActivityBound { end: string seen: string[] + /** The account's source, so a page can still name an account that is no longer connected. */ + source?: string } /** One activity entry ready to merge: when it happened and the key naming it within its account. */ @@ -165,8 +167,13 @@ export function mergeActivityPage( continuing.push(account.accountId) } const entries = returned.map(({ entry }) => entry) - /** A page that moves no account's bound would be read again unchanged, so it ends here. */ - if (continuing.length && !progressed) return { entries, stalled: [...stalled, ...continuing] } + /** + * A page that returned nothing and moved no bound would be read again unchanged, so it ends + * here. Returning entries is progress even when the remaining bounds stay put, as when a + * recovered account catches up above the others. + */ + if (continuing.length && !progressed && !entries.length) + return { entries, stalled: [...stalled, ...continuing] } /** * An account that failed is retried on the next page while this one made progress; a page * where only failed accounts were left, and failed again, ends the listing. @@ -182,6 +189,7 @@ export function mergeActivityPage( const boundSchema = z.object({ end: z.string().datetime({ offset: true }), seen: z.array(z.string().max(32)).max(MAX_SEEN_AT_BOUND), + source: z.string().max(64).optional(), }) const cursorSchema = z .object({ diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts index 3fe30e372ac..fd8ae7c98cd 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -219,14 +219,14 @@ describe('Atlassian activity', () => { it('reads past a page of issues newer than the bound instead of stopping on it', async () => { const issue = (key: string, created: string) => ({ key, - fields: { summary: key, created, reporter: { accountId: 'me' } }, + fields: { summary: key, created, creator: { accountId: 'me' } }, }) const api = client((path, options) => { if (path === '/oauth/token/accessible-resources') return [site] if (path !== '/ex/jira/cloud/rest/api/3/search/jql') return undefined const body = (options as { body?: { jql?: string; nextPageToken?: string } } | undefined) ?.body - if (!body?.jql?.includes('reporter = currentUser()')) return { issues: [] } + if (!body?.jql?.includes('creator = currentUser()')) return { issues: [] } return body.nextPageToken ? { issues: [issue('ENG-1', '2026-11-07T10:00:00.000Z')] } : { issues: [issue('ENG-3', '2026-11-08T10:00:00.000Z')], nextPageToken: 'p2' } diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index ed7ceb6687f..ef40a3dd4c3 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -265,6 +265,31 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ ), ] : [] + if ( + approvals && + parsed.source && + !supportsActivity(parsed.source) && + !accounts.some((account) => account.provider === parsed.source) + ) + statuses.push({ + source: parsed.source, + status: 'unsupported', + message: 'This source does not report activity yet.', + itemCount: 0, + }) + /** An account a cursor continues that is no longer connected leaves its activity unread. */ + for (const [accountId, bound] of Object.entries(cursor?.accounts ?? {})) { + const source = LIVE_SEARCH_PROVIDER_IDS.find((provider) => provider === bound.source) + if (source && !eligible.some((account) => account.id === accountId)) + statuses.push({ + source, + accountId, + status: 'failed', + reason: 'unavailable', + message: 'This account is no longer connected; its remaining activity was not read.', + itemCount: 0, + }) + } /** Every page reports the accounts no page reads, so its coverage never reads complete. */ for (const account of eligible.slice(MAX_ACTIVITY_ACCOUNTS)) statuses.push( @@ -431,7 +456,18 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ } const nextCursor = merged.next ? writeActivityCursor( - { v: 1, scope, start: window.start, end: window.end, accounts: merged.next }, + { + v: 1, + scope, + start: window.start, + end: window.end, + accounts: Object.fromEntries( + Object.entries(merged.next).map(([accountId, bound]) => [ + accountId, + { ...bound, source: byId.get(accountId)?.provider ?? bound.source }, + ]) + ), + }, env.BETTER_AUTH_SECRET ) : undefined diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 6cad0c2dc11..1f0b7a2fd69 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -432,12 +432,12 @@ function siteOrigin(site: Record): string { } /** - * The two Jira listings: issues the member reported, by creation, and issues assigned to them, by + * The two Jira listings: issues the member created, by creation, and issues assigned to them, by * last update. Jira's `updatedBy()` cannot be bounded reliably by date, so an assigned issue's * time is its last update, by anyone. */ const JIRA_ACTIVITY = { - created: { field: 'created', self: 'reporter', other: 'assignee' }, + created: { field: 'created', self: 'creator', other: 'assignee' }, assigned: { field: 'updated', self: 'assignee', other: 'reporter' }, } as const diff --git a/apps/sim/lib/sim-search/live/slack.ts b/apps/sim/lib/sim-search/live/slack.ts index e86adb3c4e1..d339c4bc08f 100644 --- a/apps/sim/lib/sim-search/live/slack.ts +++ b/apps/sim/lib/sim-search/live/slack.ts @@ -275,7 +275,8 @@ export async function slackActivity( }, policy: input.policy, limit: SLACK_PAGE_SIZE, - scopes: input.scopes, + /** File hits come from a separately ordered collection, so none are requested. */ + scopes: input.scopes.filter((scope) => scope !== 'search:read.files'), signal: input.signal, }, undefined, From 23c7559376c83cba71a014937bd88c0e1b78079a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:44:21 -0800 Subject: [PATCH 06/13] fix(search): start each activity account's deadline when it gets a slot --- apps/sim/lib/sim-search/live/activity.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index ef40a3dd4c3..41c04073032 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -314,14 +314,17 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ const streamItems = Math.max(MIN_STREAM_ITEMS, topK) const readAccount = async (account: LiveAccount): Promise => { const settled = new AbortController() - const signal = AbortSignal.any([ - callSignal, - settled.signal, - AbortSignal.timeout(ACCOUNT_DEADLINE_MS), - ]) + /** Aborts at the account's own deadline, which starts once it gets a slot to open. */ + const deadline = new AbortController() + const signal = AbortSignal.any([callSignal, settled.signal, deadline.signal]) let session: Awaited> | undefined try { session = await opening(async () => { + const expiry = AbortSignal.timeout(ACCOUNT_DEADLINE_MS) + expiry.addEventListener('abort', () => deadline.abort(expiry.reason), { + once: true, + signal: settled.signal, + }) const resolved = await waitWithAbort( resolveListedLiveAccount(owner, userId, account, signal), signal From a66c75e418b5fcae2bd0776d0858c39e8242cc12 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:54:07 -0800 Subject: [PATCH 07/13] docs(search): document the activity input and flag check --- apps/sim/lib/sim-search/live/activity.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index 41c04073032..702ebc5a48f 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -68,6 +68,7 @@ const SNIPPET_CHARACTERS = 300 /** Raw items each provider listing reads per page; at least a page's worth of entries. */ const MIN_STREAM_ITEMS = 20 +/** One activity page request: the caller's organization, the window and the page to read. */ export interface ListMyActivityInput { organizationId: string startDate?: string @@ -79,6 +80,7 @@ export interface ListMyActivityInput { resultSecretRegistry?: ResolvedSecretTraceRegistry } +/** Whether `list_my_activity` is rolled out to this organization (the `my-activity` flag). */ export function isMyActivityEnabled(organizationId: string): Promise { return isFeatureEnabled('my-activity', { orgId: organizationId }) } From 84a705df4c38d2b50721490bdfcbf57eb8b624b0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:17:03 -0800 Subject: [PATCH 08/13] feat(search): admit workflow runs on the activity listing's organization form --- apps/sim/lib/knowledge/application/operations.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/sim/lib/knowledge/application/operations.ts b/apps/sim/lib/knowledge/application/operations.ts index 79c7c11db1a..7c9a10f660a 100644 --- a/apps/sim/lib/knowledge/application/operations.ts +++ b/apps/sim/lib/knowledge/application/operations.ts @@ -435,7 +435,7 @@ export const knowledgeOperations = { contentDelivery: 'sourced', ...HUMAN_AND_COPILOT_PRINCIPAL_POLICY, }), - { organizationDelegation: 'allow' } + { organizationDelegation: 'allow', organizationDelegatedServices: ['copilot', 'executor'] } ), listFolders: defineKnowledgeOperation( defineWorkspaceOperation({ From e32c843ee92e3d6d2c721539b9827ddedf763665 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:28:38 -0800 Subject: [PATCH 09/13] fix(search): key activity entries by site and bound Gmail and Slack to the end's own second --- apps/sim/lib/sim-search/live/activity.ts | 6 +++++- apps/sim/lib/sim-search/live/google.ts | 10 +++++++++- apps/sim/lib/sim-search/live/slack.ts | 3 ++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index 702ebc5a48f..0350235259e 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -127,7 +127,11 @@ interface Entry extends ActivityEntry { /** The seen-key of an entry: short and opaque, since a cursor carries it. */ function entryKey(event: NativeActivityEvent): string { return fingerprint( - JSON.stringify([event.action, event.document.dedupeKey ?? event.document.id]) + JSON.stringify([ + event.action, + event.document.container, + event.document.dedupeKey ?? event.document.id, + ]) ).slice(0, 16) } diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index 393c0a4c3d5..a2342bac91b 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -352,7 +352,15 @@ export async function gmailActivity( const data = object( await client.json('/gmail/v1/users/me/messages', { query: { - q: ['in:sent', ...gmailDateClauses(input.start, input.end)].join(' '), + /** + * The inclusive end widens only to its own whole second, so a continuation rereads at most + * that second's messages rather than a page of newer ones. + */ + q: [ + 'in:sent', + ...gmailDateClauses(input.start), + `before:${Math.floor(Date.parse(input.end) / 1000) + 1}`, + ].join(' '), maxResults: String(Math.min(input.limit, GMAIL_ACTIVITY_PAGE_SIZE)), }, }) diff --git a/apps/sim/lib/sim-search/live/slack.ts b/apps/sim/lib/sim-search/live/slack.ts index d339c4bc08f..961ef4503ed 100644 --- a/apps/sim/lib/sim-search/live/slack.ts +++ b/apps/sim/lib/sim-search/live/slack.ts @@ -270,7 +270,8 @@ export async function slackActivity( query: '', filters: { startDate: input.start, - endDate: new Date(Date.parse(input.end) + 1000).toISOString(), + /** Inclusive end: Real-time Search's exclusive whole-second bound covers only its second. */ + endDate: new Date(Date.parse(input.end) + 1).toISOString(), sortBy: 'newest', }, policy: input.policy, From 137e058d020fae1b233e01524fbb574da26f533b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:40:10 -0800 Subject: [PATCH 10/13] fix(search): trim Calendar activity to the page and document the shared live helpers --- .../live/activity-providers.test.ts | 21 +++++++++++++++++++ apps/sim/lib/sim-search/live/candidates.ts | 1 + apps/sim/lib/sim-search/live/google.ts | 17 ++++++++++++--- apps/sim/lib/sim-search/live/providers.ts | 1 + 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts index fd8ae7c98cd..6060e05bc89 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -145,6 +145,27 @@ describe('Calendar activity', () => { }) }) +describe('Calendar activity paging', () => { + it('returns only the newest meetings a page needs and resumes below them', async () => { + const meeting = (id: string, day: number) => ({ + id, + summary: id, + start: { dateTime: `2026-11-0${day}T15:00:00Z` }, + end: { dateTime: `2026-11-0${day}T16:00:00Z` }, + organizer: { self: true }, + attendees: [{ email: 'ann@x.com' }], + }) + const api = client((path) => + path === '/calendar/v3/calendars/primary/events' + ? { items: [meeting('first', 2), meeting('second', 4), meeting('third', 6)] } + : undefined + ) + const [stream] = (await calendarActivity(api, { ...WINDOW, limit: 2 })).streams + expect(stream?.events.map((event) => event.document.id)).toEqual(['third', 'second']) + expect(stream).toMatchObject({ more: true, scannedTo: '2026-11-04T15:00:00.000Z' }) + }) +}) + describe('Atlassian activity', () => { const site = { id: 'cloud', url: 'https://acme.atlassian.net' } diff --git a/apps/sim/lib/sim-search/live/candidates.ts b/apps/sim/lib/sim-search/live/candidates.ts index 03c662a28c5..ef0971a3156 100644 --- a/apps/sim/lib/sim-search/live/candidates.ts +++ b/apps/sim/lib/sim-search/live/candidates.ts @@ -26,6 +26,7 @@ export interface LiveCandidate { documentId: string } +/** A provider result with its document ID: a reference bound to this account and `owner`. */ export function candidateFor( document: NativeDocument, account: LiveAccount, diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index a2342bac91b..c0543f06983 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -890,13 +890,24 @@ export async function calendarActivity( } sliceEnd = sliceStart } - const more = sliceEnd > start + events.sort((left, right) => Date.parse(right.at) - Date.parse(left.at)) + /** + * Whole slices can hold more meetings than a page needs: keep the newest `limit`, plus any + * sharing the last kept start, and resume below them. + */ + const lastKept = events[input.limit - 1] + const kept = lastKept + ? events.filter((event) => Date.parse(event.at) >= Date.parse(lastKept.at)) + : events + const trimmed = kept.length < events.length + const scannedTo = trimmed && lastKept ? lastKept.at : new Date(sliceEnd).toISOString() + const more = trimmed || sliceEnd > start return { streams: [ { - events: events.sort((left, right) => Date.parse(right.at) - Date.parse(left.at)), + events: kept, more, - ...(more ? { scannedTo: new Date(sliceEnd).toISOString() } : {}), + ...(more ? { scannedTo } : {}), }, ], ...(overfull diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 7804603e4a8..efb52e33af5 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -400,6 +400,7 @@ export function supportsActivity(provider: LiveSearchProviderId): boolean { return 'activity' in LIVE_SEARCH_PROVIDERS[provider] } +/** Lists the connected person's own activity from a native provider that supports it. */ export function activityNativeProvider( provider: LiveSearchProviderId, client: NativeClient, From a521cffa854e7636b9832435b79576b71f54be3c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:51:30 -0800 Subject: [PATCH 11/13] fix(search): never count Calendar meetings at the resume bound toward the page --- .../live/activity-providers.test.ts | 22 +++++++++++++++++++ apps/sim/lib/sim-search/live/google.ts | 7 ++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts index 6060e05bc89..5a49e8740af 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -164,6 +164,28 @@ describe('Calendar activity paging', () => { expect(stream?.events.map((event) => event.document.id)).toEqual(['third', 'second']) expect(stream).toMatchObject({ more: true, scannedTo: '2026-11-04T15:00:00.000Z' }) }) + + it('reads past meetings at the bound an earlier page may have returned', async () => { + const meeting = (id: string, day: number) => ({ + id, + summary: id, + start: { dateTime: `2026-11-0${day}T15:00:00Z` }, + end: { dateTime: `2026-11-0${day}T16:00:00Z` }, + organizer: { self: true }, + attendees: [{ email: 'ann@x.com' }], + }) + const api = client((path) => + path === '/calendar/v3/calendars/primary/events' + ? { items: [meeting('older', 2), meeting('tied-a', 6), meeting('tied-b', 6)] } + : undefined + ) + const [stream] = ( + await calendarActivity(api, { ...WINDOW, end: '2026-11-06T15:00:00.000Z', limit: 2 }) + ).streams + expect(stream?.events.map((event) => event.document.id)).toEqual( + expect.arrayContaining(['tied-a', 'tied-b', 'older']) + ) + }) }) describe('Atlassian activity', () => { diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index c0543f06983..bce030e3cdb 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -893,9 +893,12 @@ export async function calendarActivity( events.sort((left, right) => Date.parse(right.at) - Date.parse(left.at)) /** * Whole slices can hold more meetings than a page needs: keep the newest `limit`, plus any - * sharing the last kept start, and resume below them. + * sharing the last kept start, and resume below them. Meetings at the inclusive end may be ones + * an earlier page returned, so they never count toward the limit. */ - const lastKept = events[input.limit - 1] + const lastKept = events.filter((event) => Date.parse(event.at) < Date.parse(input.end))[ + input.limit - 1 + ] const kept = lastKept ? events.filter((event) => Date.parse(event.at) >= Date.parse(lastKept.at)) : events From 1be33b652aeb31c7807d12093ef5a87d1d6b7211 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:53:40 -0800 Subject: [PATCH 12/13] chore(search): regenerate Mothership tool contracts after rebasing on chat history --- .../sim-assistant-tools.generated.ts | 52 +++++++++++++ .../mothership/generated/tool-catalog-v1.ts | 73 +++++++++++++++++++ .../mothership/generated/tool-schemas-v1.ts | 66 +++++++++++++++++ 3 files changed, 191 insertions(+) diff --git a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts index 882c532a2d9..5849d7b3233 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -49,6 +49,9 @@ const PROVIDER_KIND_SCHEMAS = { zoom: z.enum(['meeting']), } as const +/** A collection one GitLab search selects. */ +export type GitLabSearchKind = z.output + function hasSearchKinds( provider: LiveSearchProvider ): provider is keyof typeof PROVIDER_KIND_SCHEMAS { @@ -522,6 +525,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 @@ -592,6 +637,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: 'list_my_activity', route: 'sim', diff --git a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts index 3b6fea88b16..10fdd858c49 100644 --- a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts @@ -12,6 +12,7 @@ export interface ToolCatalogEntry { | '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.' + | 'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.' | '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.' @@ -90,6 +91,7 @@ export interface ToolCatalogEntry { | 'knowledge' | 'list_deployment_versions' | 'list_integration_tools' + | 'list_my_activity' | 'list_my_chat_history' | 'list_user_projects' | 'list_workspace_mcp_servers' @@ -7842,6 +7844,76 @@ export const ListMyChatHistory: ToolCatalogEntry = { }, } +export const ListMyActivity: ToolCatalogEntry = { + id: 'list_my_activity', + description: + 'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', + route: 'sim', + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + startDate: { + description: + 'Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most 92 days.', + 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)))$', + }, + endDate: { + description: + 'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up 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)))$', + }, + source: { + description: + 'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.', + type: 'string', + enum: [ + 'google_drive', + 'gmail', + 'google_meet', + 'zoom', + 'google_calendar', + 'slack', + 'jira', + 'confluence', + 'github', + 'jama', + 'flow', + 'gitlab', + 'linear', + 'lucid', + 'hex', + 'hubspot', + 'fireflies', + 'granola', + 'notion', + 'coda', + ], + }, + topK: { + description: 'Maximum entries on this page: 25 by default.', + type: 'integer', + minimum: 1, + maximum: 50, + }, + cursor: { + description: + 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.', + type: 'string', + minLength: 1, + maxLength: 40000, + }, + }, + additionalProperties: false, + }, +} + export const Dashboards: ToolCatalogEntry = { id: 'dashboards', description: @@ -8853,6 +8925,7 @@ export const TOOL_CATALOG: Record = { [ListWorkspaces.id]: ListWorkspaces, [SearchPeople.id]: SearchPeople, [ListMyChatHistory.id]: ListMyChatHistory, + [ListMyActivity.id]: ListMyActivity, [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 ac9f13088cf..f8aca3b7092 100644 --- a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts @@ -7916,6 +7916,72 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, + list_my_activity: { + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + startDate: { + description: + 'Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most 92 days.', + 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)))$', + }, + endDate: { + description: + 'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up 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)))$', + }, + source: { + description: + 'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.', + type: 'string', + enum: [ + 'google_drive', + 'gmail', + 'google_meet', + 'zoom', + 'google_calendar', + 'slack', + 'jira', + 'confluence', + 'github', + 'jama', + 'flow', + 'gitlab', + 'linear', + 'lucid', + 'hex', + 'hubspot', + 'fireflies', + 'granola', + 'notion', + 'coda', + ], + }, + topK: { + description: 'Maximum entries on this page: 25 by default.', + type: 'integer', + minimum: 1, + maximum: 50, + }, + cursor: { + description: + 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.', + type: 'string', + minLength: 1, + maxLength: 40000, + }, + }, + additionalProperties: false, + }, + resultSchema: undefined, + }, dashboards: { parameters: { $schema: 'http://json-schema.org/draft-07/schema#', From 97e292ab53dff2b0836ed73784b5b7e3a1303c06 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:06:32 -0800 Subject: [PATCH 13/13] fix(search): give each activity entry its own citation and list the tool only to people --- apps/sim/lib/knowledge/mcp/server.ts | 3 ++- apps/sim/lib/knowledge/search/citation.ts | 10 ++++++++++ .../mothership/tools/server/knowledge/my-activity.ts | 4 ++-- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 99224542db3..db2c30eed39 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -209,7 +209,8 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe // Only a person has a chat history; a workspace API key acts for no one. if (resolvePrincipalSubjectUserId(principal)) registerListMyChatHistoryTool(server, { execute, principal, organizationId }) - if (context.listMyActivity) + // Activity is always the caller's own; a workspace API key has no person to list. + if (context.listMyActivity && resolvePrincipalSubjectUserId(principal)) registerListMyActivityTool(server, { execute, principal, organizationId, request }) return server diff --git a/apps/sim/lib/knowledge/search/citation.ts b/apps/sim/lib/knowledge/search/citation.ts index e17bb6f8cf4..f8d04895388 100644 --- a/apps/sim/lib/knowledge/search/citation.ts +++ b/apps/sim/lib/knowledge/search/citation.ts @@ -10,3 +10,13 @@ import { liveDocumentKey } from '@/lib/sim-search/live/reference' export function liveCitationId(documentId: string): string { return `live:${sha256Hex(liveDocumentKey(documentId)).slice(0, 32)}` } + +/** + * The citation ID of one activity entry. Entries that read the same document can link to + * different places in it, such as two comments on one page, so the link is part of the identity. + */ +export function activityCitationId(documentId: string, url: string | null): string { + return url + ? `live:${sha256Hex(`${liveDocumentKey(documentId)}\n${url}`).slice(0, 32)}` + : liveCitationId(documentId) +} diff --git a/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts b/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts index a92f9722561..d6431c20fd8 100644 --- a/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts +++ b/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger' import { z } from 'zod' import { listMyActivityInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' import { getValidationErrorMessage } from '@/lib/api/server/validation' -import { liveCitationId } from '@/lib/knowledge/search/citation' +import { activityCitationId } from '@/lib/knowledge/search/citation' import { executeCopilotOrganizationKnowledgeUseCase, messageForCopilotKnowledgeError, @@ -54,7 +54,7 @@ export const listMyActivityServerTool: BaseServerTool = { ...data, items: data.items.map((item) => ({ ...item, - citationId: liveCitationId(item.documentId), + citationId: activityCitationId(item.documentId, item.url), citationUrl: item.url, })), },