From 99c6765076ffb0d24133506412a08b8b04ceb65e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:33:11 -0800 Subject: [PATCH 1/7] fix(search): keep activity paging and labels truthful under busy sources and failures - Jira reads its created listing with relative-minute bounds and assigned issues by the moment of assignment (assignee CHANGED TO currentUser() DURING, from each issue's history) - Confluence places pages at the member's own latest edit from version history, dropping pages they did not edit in the window, and reads listings whose order is not the member's action whole; CQL bounds widen by the widest time zone offsets instead of a day - A listing that cannot reach its bound stops only its own account, with an accurate status - A failed account is retried once, then reported - Search MCP charges one rate-limit operation per account read - Continuations may change topK; Assistant items drop the duplicate citationUrl and items drop accountId - Calendar reports an overfull week only when a slice exhausts the whole budget - Removes the never-emitted mentioned action and approximateTime --- .../contracts/mothership-assistant-tools.ts | 8 +- apps/sim/lib/knowledge/mcp/my-activity.ts | 39 +- .../lib/mothership/chat/citation-evidence.ts | 2 +- .../sim-assistant-tools.generated.ts | 8 +- .../mothership/generated/tool-schemas-v1.ts | 2 +- .../tools/server/knowledge/my-activity.ts | 3 +- .../lib/sim-search/live/activity-page.test.ts | 54 +- apps/sim/lib/sim-search/live/activity-page.ts | 63 +- .../live/activity-paging.integration.ts | 149 +++++ .../live/activity-providers.test.ts | 163 ++--- apps/sim/lib/sim-search/live/activity.ts | 48 +- apps/sim/lib/sim-search/live/atlassian.ts | 577 +++++++++++------- apps/sim/lib/sim-search/live/google.ts | 4 +- apps/sim/lib/sim-search/live/types.ts | 2 - 14 files changed, 784 insertions(+), 338 deletions(-) create mode 100644 apps/sim/lib/sim-search/live/activity-paging.integration.ts diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index be3fd6d442c..751ebb995e0 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -375,7 +375,7 @@ export const listMyActivityInputFieldsSchema = z .max(40_000) .optional() .describe( - 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.' + 'nextCursor from the previous page, with the same startDate, endDate and source; topK may change. Pages continue newest first without gaps.' ), }) .strict() @@ -434,7 +434,6 @@ const activityActionSchema = z.enum([ 'replied', 'attended', 'assigned', - 'mentioned', ]) export type ActivityAction = z.output @@ -443,15 +442,12 @@ const activityItemSchema = z.object({ documentId: z.string(), timestamp: z.string(), source: liveSearchProviderSchema, - accountId: z.string(), action: activityActionSchema, 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({ @@ -650,7 +646,7 @@ export const assistantToolContracts = [ 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.', + 'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted, Jira issues you created or that were assigned to you, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more; a source that failed and recovers on a later page can return entries older than that page. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', inputSchema: listMyActivityInputSchema, }, { diff --git a/apps/sim/lib/knowledge/mcp/my-activity.ts b/apps/sim/lib/knowledge/mcp/my-activity.ts index 3853a1e3b90..16673c7fa9f 100644 --- a/apps/sim/lib/knowledge/mcp/my-activity.ts +++ b/apps/sim/lib/knowledge/mcp/my-activity.ts @@ -9,6 +9,8 @@ import { projectResult, } from '@/lib/knowledge/mcp/tool-runner' import { listMyActivity } from '@/lib/sim-search/live/activity' +import { listLiveSearchAccounts } from '@/lib/sim-search/live/application' +import { supportsActivity } from '@/lib/sim-search/live/providers' interface ListMyActivityToolContext { execute: KnowledgeMcpToolRunner @@ -17,11 +19,31 @@ interface ListMyActivityToolContext { request: NextRequest } +/** Accounts one call reads at most, as the use case caps them. */ +const MAX_ACTIVITY_ACCOUNTS = 20 + /** - * Provider reads one call makes, for the rate limit: about one listing per connected source, - * which is more than a single search's share. + * What one call costs against the rate limit: one operation per account it reads, since each is + * a separate provider listing. A lookup that fails charges one, as a call reading nothing would. */ -const LIST_MY_ACTIVITY_COST = 2 +async function activityCost( + principal: Principal, + organizationId: string, + source: string | undefined +): Promise { + try { + const { accounts } = await listLiveSearchAccounts.execute({ + principal, + input: { organizationId }, + }) + const read = accounts.filter( + (account) => supportsActivity(account.provider) && (!source || account.provider === source) + ).length + return Math.min(MAX_ACTIVITY_ACCOUNTS, Math.max(1, read)) + } catch { + return 1 + } +} /** * Registers `list_my_activity`: what the caller did across their connected sources in a window, @@ -36,12 +58,14 @@ export function registerListMyActivityTool( { 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.', + 'List what you did across your connected sources in a date window, newest first, each at the time of your own action: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted (attended), Jira issues you created or that were assigned to you, 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. When truncated is true, call again with nextCursor and the same startDate, endDate and source (topK may change): pages continue without gaps, though a source that failed and recovers on a later page can return entries older than that page. sources reports every source: not_connected and reconnect carry connect.url, where you connect that account.', inputSchema: listMyActivityMcpSchema, annotations: KNOWLEDGE_MCP_READ_ONLY, }, - async (input: unknown, extra: { signal: AbortSignal }) => - execute( + async (input: unknown, extra: { signal: AbortSignal }) => { + const requested = listMyActivityMcpSchema.safeParse(input) + const cost = await activityCost(principal, organizationId, requested.data?.source) + return execute( 'list_my_activity', knowledgeOperations.listActivity, extra.signal, @@ -54,7 +78,8 @@ export function registerListMyActivityTool( }) return projectResult(result, registry) }, - LIST_MY_ACTIVITY_COST + cost ) + } ) } diff --git a/apps/sim/lib/mothership/chat/citation-evidence.ts b/apps/sim/lib/mothership/chat/citation-evidence.ts index 8a54f8abc40..e9df44c34ee 100644 --- a/apps/sim/lib/mothership/chat/citation-evidence.ts +++ b/apps/sim/lib/mothership/chat/citation-evidence.ts @@ -45,7 +45,7 @@ export function toCitationResult( if (toolName === 'list_my_activity' && typeof result.documentName !== 'string') return { citationId: result.citationId, - citationUrl: result.citationUrl, + citationUrl: result.url, documentName: result.title, connectorType: result.source, sourceDate: result.timestamp, 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 5849d7b3233..50b56169b21 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -398,7 +398,7 @@ export const listMyActivityInputFieldsSchema = z .max(40_000) .optional() .describe( - 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.' + 'nextCursor from the previous page, with the same startDate, endDate and source; topK may change. Pages continue newest first without gaps.' ), }) .strict() @@ -457,7 +457,6 @@ const activityActionSchema = z.enum([ 'replied', 'attended', 'assigned', - 'mentioned', ]) export type ActivityAction = z.output @@ -466,15 +465,12 @@ const activityItemSchema = z.object({ documentId: z.string(), timestamp: z.string(), source: liveSearchProviderSchema, - accountId: z.string(), action: activityActionSchema, 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({ @@ -648,7 +644,7 @@ export const assistantToolContracts = [ 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.', + 'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted, Jira issues you created or that were assigned to you, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more; a source that failed and recovers on a later page can return entries older than that page. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', inputSchema: listMyActivityInputSchema, }, { diff --git a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts index 94f888d4627..eec49ac5e5a 100644 --- a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts @@ -8008,7 +8008,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, cursor: { description: - 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.', + 'nextCursor from the previous page, with the same startDate, endDate and source; topK may change. Pages continue newest first without gaps.', type: 'string', minLength: 1, maxLength: 40000, 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 d6431c20fd8..0caa63d522b 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 with a non-null citationUrl as {"id":""}.', + 'Cite entries with a non-null url as {"id":""}.', ] .filter(Boolean) .join(' '), @@ -55,7 +55,6 @@ export const listMyActivityServerTool: BaseServerTool = { items: data.items.map((item) => ({ ...item, citationId: activityCitationId(item.documentId, item.url), - citationUrl: item.url, })), }, } 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 e5ae9d0de72..d26a06cff59 100644 --- a/apps/sim/lib/sim-search/live/activity-page.test.ts +++ b/apps/sim/lib/sim-search/live/activity-page.test.ts @@ -22,12 +22,15 @@ interface FakeAccount { /** Items the provider holds, newest first, read `limit` at a time like a provider listing. */ items: ActivityEntry[] limit: number + /** Reads newest first without honoring the bound, as a listing whose bound is too coarse. */ + ignoresBound?: true } /** 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 + (item) => + (account.ignoresBound || Date.parse(item.at) <= Date.parse(bound.end)) && item.at >= START ) const page = inWindow.slice(0, account.limit) return { @@ -63,7 +66,7 @@ function pageThrough( topK ) pages.push(result.entries.map((entry) => `${entry.accountId}:${entry.key}`)) - stalled.push(...result.stalled) + stalled.push(...result.stopped.map((stop) => `${stop.accountId}:${stop.reason}`)) if (!result.next) return { pages, stalled } bounds = result.next } @@ -212,6 +215,51 @@ describe('mergeActivityPage', () => { expect(stalled).toEqual([]) }) + it('stops only the account whose listing cannot reach its bound, paging the others', () => { + const accounts: FakeAccount[] = [ + { + id: 'busy', + limit: 2, + ignoresBound: true, + items: [ + { at: at(170), key: 'b1' }, + { at: at(169), key: 'b2' }, + { at: at(10), key: 'b3' }, + ], + }, + { + id: 'mail', + limit: 50, + items: [ + { at: at(120), key: 'm1' }, + { at: at(100), key: 'm2' }, + { at: at(80), key: 'm3' }, + ], + }, + ] + const { pages, stalled } = pageThrough(accounts, 1) + expect(pages.flat().filter((key) => key.startsWith('mail:'))).toEqual([ + 'mail:m1', + 'mail:m2', + 'mail:m3', + ]) + expect(stalled).toEqual(['busy:unreachable']) + }) + + it('retries a failed account once, then reports it instead of retrying again', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [4, 3, 2, 1].map((hour) => ({ at: at(hour * 10), key: `c${hour}` })), + }, + { id: 'mail', limit: 50, items: [{ at: at(5), key: 'm1' }] }, + ] + const { pages, stalled } = pageThrough(accounts, 1, (accountId) => accountId === 'mail') + expect(pages.flat()).toEqual(['chat:c4', 'chat:c3', 'chat:c2', 'chat:c1']) + expect(stalled).toEqual(['mail:failed_again']) + }) + it('ends without a continuation when only failed accounts would continue', () => { const result = mergeActivityPage( [{ accountId: 'mail', bound: { end: END, seen: [] }, read: false }], @@ -231,7 +279,7 @@ describe('mergeActivityPage', () => { ] const { pages, stalled } = pageThrough(accounts, 10) expect(new Set(pages.flat()).size).toBe(pages.flat().length) - expect(stalled).toEqual(['chat']) + expect(stalled).toEqual(['chat:no_progress']) }) it('leaves out entries outside the window and those an earlier page returned at its bound', () => { diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts index 89ab1d01109..e345ba8b342 100644 --- a/apps/sim/lib/sim-search/live/activity-page.ts +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -39,6 +39,8 @@ export interface ActivityBound { seen: string[] /** The account's source, so a page can still name an account that is no longer connected. */ source?: string + /** Pages that already retried this bound after the account failed; one retry is allowed. */ + retries?: number } /** One activity entry ready to merge: when it happened and the key naming it within its account. */ @@ -59,13 +61,20 @@ export type AccountActivity = { bound: ActivityBound } & ({ read: true; streams: ActivityStreamRead[] } | { read: false }) +/** + * Why an account stopped before reading all its activity: a listing could not page past items + * newer than its bound, more entries than a cursor can name sat at one instant, a page made no + * progress at all, or the account failed again on its one retry. + */ +export type ActivityStopReason = 'unreachable' | 'crowded' | 'no_progress' | 'failed_again' + 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[] + /** Accounts that stopped without reading all their activity, and why. */ + stopped: { accountId: string; reason: ActivityStopReason }[] } function sameBound(left: ActivityBound, right: ActivityBound): boolean { @@ -82,8 +91,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; its entries, newer than the others' - * bounds, then arrive out of order on that page rather than being lost. + * keeps its bound, so the next page retries it once 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[], @@ -94,15 +103,33 @@ export function mergeActivityPage( let horizon: number | undefined const pending: { entry: E & { accountId: string }; time: number }[] = [] const unfinished = new Set() + const stopped: ActivityPageResult['stopped'] = [] + /** + * A listing with more to read that scanned nothing at or before its bound cannot advance: the + * next page would read the same newer items. Only its account stops; holding every account at + * that bound would end the whole listing. + */ + const unreachable = new Set( + accounts.flatMap((account) => + account.read && + account.streams.some((stream) => { + if (!stream.more) return false + const scanned = Date.parse(stream.scannedTo ?? '') + return !Number.isFinite(scanned) || scanned > Date.parse(account.bound.end) + }) + ? [account.accountId] + : [] + ) + ) + for (const accountId of unreachable) stopped.push({ accountId, reason: 'unreachable' }) for (const account of accounts) { if (!account.read) continue 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 ? Date.parse(stream.scannedTo) : end - const floor = Number.isFinite(scanned) ? Math.min(scanned, end) : end + if (stream.more && !unreachable.has(account.accountId)) { + const floor = Date.parse(stream.scannedTo ?? '') horizon = horizon === undefined ? floor : Math.max(horizon, floor) unfinished.add(account.accountId) } @@ -132,15 +159,18 @@ export function mergeActivityPage( pending.filter((item) => !returnedItems.has(item)).map(({ entry }) => entry.accountId) ) 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 + /** A failed account is retried once from its bound, then reported as not read. */ + if ((account.bound.retries ?? 0) >= 1) + stopped.push({ accountId: account.accountId, reason: 'failed_again' }) + else next[account.accountId] = { ...account.bound, retries: (account.bound.retries ?? 0) + 1 } continue } if ( + unreachable.has(account.accountId) || resume === undefined || (!unfinished.has(account.accountId) && !remaining.has(account.accountId)) ) @@ -159,7 +189,7 @@ export function mergeActivityPage( seen: [...new Set([...(ownEnd === end ? account.bound.seen : []), ...returnedAtEnd])], } if (bound.seen.length > MAX_SEEN_AT_BOUND) { - stalled.push(account.accountId) + stopped.push({ accountId: account.accountId, reason: 'crowded' }) continue } if (!sameBound(bound, account.bound)) progressed = true @@ -173,16 +203,22 @@ export function mergeActivityPage( * recovered account catches up above the others. */ if (continuing.length && !progressed && !entries.length) - return { entries, stalled: [...stalled, ...continuing] } + return { + entries, + stopped: [ + ...stopped, + ...continuing.map((accountId) => ({ accountId, reason: 'no_progress' as const })), + ], + } /** * 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) + const retrying = Object.keys(next).some((accountId) => !continuing.includes(accountId)) return { entries, ...(continuing.length || (retrying && entries.length) ? { next } : {}), - stalled, + stopped, } } @@ -190,6 +226,7 @@ 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(), + retries: z.number().int().min(0).max(1).optional(), }) const cursorSchema = z .object({ diff --git a/apps/sim/lib/sim-search/live/activity-paging.integration.ts b/apps/sim/lib/sim-search/live/activity-paging.integration.ts new file mode 100644 index 00000000000..b60cf45e443 --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity-paging.integration.ts @@ -0,0 +1,149 @@ +/** + * Paging `list_my_activity` end to end against real Postgres: the caller's real membership and + * the signed cursor carry the listing across pages, while each connected account is a fake + * provider that reads a few items at a time, newest first, up to the bound it is given. Following + * nextCursor must return every item exactly once, newest first. + */ +import type { OAuthAccessTokenPrincipal } from '@sim/auth/principal' +import { db } from '@sim/db' +import { member, organization, user } from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq } from 'drizzle-orm' +import { afterAll, beforeAll, expect, it, vi } from 'vitest' +import type { LiveAccount, NativeActivityInput, NativeDocument } from '@/lib/sim-search/live/types' + +vi.hoisted(() => vi.stubEnv('MY_ACTIVITY', 'true')) + +interface FakeItem { + id: string + at: string +} + +const { fakes } = vi.hoisted(() => ({ + fakes: { + accounts: [] as { account: LiveAccount; items: FakeItem[]; readSize: number }[], + }, +})) + +vi.mock('@/lib/sim-search/live/accounts', async (importOriginal) => ({ + ...(await importOriginal()), + listLiveAccounts: async () => fakes.accounts.map(({ account }) => account), + resolveListedLiveAccount: async (_owner: unknown, _userId: string, account: LiveAccount) => ({ + account, + accessToken: 'fake', + }), +})) + +vi.mock('@/lib/sim-search/live/account-session', () => ({ + openLiveAccountSession: async ({ resolved }: { resolved: { account: LiveAccount } }) => { + const fake = fakes.accounts.find(({ account }) => account.id === resolved.account.id) + if (!fake) throw new Error('Unknown fake account') + return { + policy: {}, + servicePartial: false, + verifySharesPreviewBudget: false, + close: async () => undefined, + verify: async () => true, + async activity(input: NativeActivityInput) { + const window = fake.items.filter( + (item) => + Date.parse(item.at) <= Date.parse(input.end) && + Date.parse(item.at) >= Date.parse(input.start) + ) + const read = window.slice(0, fake.readSize) + return { + streams: [ + { + events: read.map((item) => ({ + document: { + id: item.id, + title: item.id, + url: `https://example.com/${item.id}`, + content: item.id, + } satisfies NativeDocument, + at: item.at, + action: 'sent' as const, + collaborators: [], + })), + more: window.length > read.length, + scannedTo: read.at(-1)?.at, + }, + ], + } + }, + } + }, +})) + +const { listMyActivity } = await import('@/lib/sim-search/live/activity') + +const organizationId = generateId() +const userId = generateId() + +const principal: OAuthAccessTokenPrincipal = { + kind: 'oauth_access_token', + userId, + clientId: 'mcp-client', + tokenId: generateId(), + scopes: ['search:read'], + expiresAt: new Date(Date.now() + 3_600_000), +} + +function account(id: string, provider: LiveAccount['provider']): LiveAccount { + return { id, provider, providerId: provider, displayName: id, type: 'oauth', scopes: [] } +} + +/** Items newest first, one every `stepHours`, starting `firstHoursAgo` before now. */ +function items(prefix: string, count: number, firstHoursAgo: number, stepHours: number) { + return Array.from({ length: count }, (_, index) => ({ + id: `${prefix}-${index}`, + at: new Date(Date.now() - (firstHoursAgo + index * stepHours) * 3_600_000).toISOString(), + })) +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Paging person', + email: `${userId}@example.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db + .insert(organization) + .values({ id: organizationId, slug: organizationId, name: 'Paging fixture', createdAt: now }) + await db.insert(member).values({ id: generateId(), organizationId, userId, role: 'member' }) +}) + +afterAll(async () => { + await db.delete(organization).where(eq(organization.id, organizationId)) + await db.delete(user).where(eq(user.id, userId)) + vi.unstubAllEnvs() +}) + +it('returns every item of every account exactly once, newest first, across pages', async () => { + fakes.accounts = [ + { account: account('chat-account', 'slack'), items: items('chat', 9, 2, 7), readSize: 3 }, + { account: account('mail-account', 'gmail'), items: items('mail', 6, 5, 11), readSize: 4 }, + ] + const expected = fakes.accounts + .flatMap(({ items: list }) => list) + .sort((left, right) => Date.parse(right.at) - Date.parse(left.at)) + .map((item) => item.id) + for (const topK of [2, 10]) { + const seen: string[] = [] + let cursor: string | undefined + for (let page = 0; page < 30 && (page === 0 || cursor); page++) { + const result = await listMyActivity.execute({ + principal, + input: { organizationId, topK, ...(cursor ? { cursor } : {}) }, + }) + seen.push(...result.items.map(({ title }) => title)) + cursor = result.nextCursor + } + expect(cursor).toBeUndefined() + expect(seen).toEqual(expected) + } +}) 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 5a49e8740af..721b352c6a5 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -188,16 +188,59 @@ describe('Calendar activity paging', () => { }) }) +describe('Calendar activity budget', () => { + it('resumes a busy older week on the next page instead of calling it too full', async () => { + const window = { ...WINDOW, start: '2026-10-25T00:00:00.000Z' } + const api = client((path, options) => { + if (path !== '/calendar/v3/calendars/primary/events') return undefined + const timeMin = String(options?.query?.timeMin) + /** The newest week holds one meeting; the older week pages on past the budget. */ + if (timeMin === '2026-11-01T00:00:01.000Z') + return { + items: [ + { + id: 'recent', + summary: 'recent', + start: { dateTime: '2026-11-05T15:00:00Z' }, + organizer: { self: true }, + attendees: [{ email: 'ann@x.com' }], + }, + ], + } + return { items: [], nextPageToken: 'more' } + }) + const page = await calendarActivity(api, window) + expect(page.partial).toBeUndefined() + expect(page.streams[0]).toMatchObject({ more: true, scannedTo: '2026-11-01T00:00:01.000Z' }) + }) +}) + 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 () => { + it('places a page at the member’s own edit, leaving out pages they did not edit in the window', async () => { + const page = (id: string, when: string, by: string, number: number) => ({ + content: { id, type: 'page', title: id, version: { when, number, by: { accountId: by } } }, + }) 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/api/v2/pages/shared/versions') + return { + results: [ + { number: 4, authorId: 'ann', createdAt: '2026-11-07T10:00:00.000Z' }, + { number: 3, authorId: 'me', createdAt: '2026-11-05T09:00:00.000Z' }, + ], + } + if (path === '/ex/confluence/cloud/wiki/api/v2/pages/old/versions') + return { + results: [ + { number: 2, authorId: 'ann', createdAt: '2026-11-06T10:00:00.000Z' }, + { number: 1, authorId: 'me', createdAt: '2026-10-01T09:00:00.000Z' }, + ], + } if (path !== '/ex/confluence/cloud/wiki/rest/api/search') return undefined - const cql = String(options?.query?.cql) - return cql.startsWith('type = comment') + return String(options?.query?.cql).startsWith('type = comment') ? { results: [ { @@ -205,7 +248,7 @@ describe('Atlassian activity', () => { id: 'c1', type: 'comment', container: { id: '42', type: 'page', title: 'Runbook' }, - history: { createdDate: '2026-11-05T10:00:00.000Z' }, + history: { createdDate: '2026-11-04T10:00:00.000Z' }, _links: { webui: '/spaces/ENG/pages/42?focusedCommentId=c1' }, }, excerpt: 'Agreed', @@ -215,102 +258,64 @@ describe('Atlassian activity', () => { } : { 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' }, - }, - }, - }, + page('shared', '2026-11-07T10:00:00.000Z', 'ann', 4), + page('old', '2026-11-06T10:00:00.000Z', 'ann', 2), + page('mine', '2026-11-03T10:00:00.000Z', 'me', 1), ], - _links: { next: '/wiki/rest/api/search?cursor=abc' }, + _links: {}, } }) 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?.events.map((event) => [event.document.id, event.action, event.at])).toEqual([ + ['shared', 'edited', '2026-11-05T09:00:00.000Z'], + ['mine', 'created', '2026-11-03T10:00:00.000Z'], ]) - 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' }), + document: expect.objectContaining({ id: '42', dedupeKey: 'comment:c1' }), }), ]) }) - 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, 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('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' } - }) - 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 () => { + it('reports a Jira issue at the moment it was assigned to the member, from its history', async () => { const api = client((path, options) => { if (path === '/oauth/token/accessible-resources') return [site] + if (path === '/ex/jira/cloud/rest/api/3/myself') return { accountId: 'me' } 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' }, + if (!jql.includes('assignee CHANGED TO currentUser()')) return { issues: [] } + return { + issues: [ + { + key: 'ENG-2', + fields: { summary: 'Fix login', updated: '2026-11-07T09:00:00.000Z' }, + changelog: { + histories: [ + { + created: '2026-11-03T08:00:00.000Z', + items: [{ field: 'assignee', to: 'me' }], }, - }, - ], - } - : { issues: [] } + { created: '2026-11-07T09:00:00.000Z', items: [{ field: 'status', to: '3' }] }, + ], + }, + }, + { + key: 'ENG-3', + fields: { summary: 'No history', updated: '2026-11-06T09:00:00.000Z' }, + changelog: { histories: [] }, + }, + ], + } }) - const streams = (await atlassianActivity(api, 'jira', WINDOW)).streams - expect(streams.flatMap((stream) => stream.events)).toEqual([ + const page = await atlassianActivity(api, 'jira', WINDOW) + expect(page.streams.flatMap((stream) => stream.events)).toEqual([ expect.objectContaining({ action: 'assigned', - at: '2026-11-06T09:00:00.000Z', - approximateTime: true, - collaborators: ['Ann'], + at: '2026-11-03T08:00:00.000Z', + document: expect.objectContaining({ id: 'ENG-2' }), }), ]) + expect(page).toMatchObject({ partial: true }) }) }) diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index 0350235259e..1713945044f 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -30,6 +30,7 @@ import { type AccountActivity, type ActivityBound, type ActivityEntry, + type ActivityStopReason, mergeActivityPage, readActivityCursor, writeActivityCursor, @@ -65,6 +66,8 @@ 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 +/** Search budgets one account's session gets: up to four sites, each with several listings. */ +const ACTIVITY_SESSION_SEARCHES = 3 /** Raw items each provider listing reads per page; at least a page's worth of entries. */ const MIN_STREAM_ITEMS = 20 @@ -85,6 +88,17 @@ export function isMyActivityEnabled(organizationId: string): Promise { return isFeatureEnabled('my-activity', { orgId: organizationId }) } +/** What a source's status says when its listing stopped before reading all its activity. */ +const STOP_MESSAGES: Record = { + unreachable: + 'This source returned more recent items than one page can move past, so its older activity in the window was not read. Narrow the dates to read it.', + crowded: + 'This source has more activity at one instant than a page can return, so its older activity in the window was not read.', + no_progress: + 'Paging made no progress, so older activity in the window was not read. Narrow the dates to read it.', + failed_again: 'It failed again on retry, so its remaining activity was not read.', +} + const INVALID_CURSOR_MESSAGE = 'Invalid cursor. Continue with the same startDate, endDate, source and topK, or start again without a cursor.' @@ -216,7 +230,6 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ startDate: instantScopePart(parsed.startDate), endDate: instantScopePart(parsed.endDate), source: parsed.source, - topK, }) ) const cursor = parsed.cursor @@ -336,7 +349,16 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ signal ) return waitWithAbort( - openLiveAccountSession({ owner, userId, resolved, policies, signal, pool }), + openLiveAccountSession({ + owner, + userId, + resolved, + policies, + signal, + pool, + /** A page reads several listings per site, and version histories for Confluence. */ + searches: ACTIVITY_SESSION_SEARCHES, + }), signal ) }) @@ -423,7 +445,6 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ 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, @@ -435,27 +456,28 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ safeContent(document.content, registry).trim(), SNIPPET_CHARACTERS ), - ...(event.approximateTime ? { approximateTime: true as const } : {}), }, ] }) - const stalled = new Set(merged.stalled) + const stopped = new Map(merged.stopped.map(({ accountId, reason }) => [accountId, reason])) for (const read of reads) { const account = byId.get(read.accountId) if (!account) continue if (!read.read) { - statuses.push(failureStatus(account, read.error, organizationId)) + const failure = failureStatus(account, read.error, organizationId) + statuses.push( + stopped.has(account.id) + ? { ...failure, message: `${read.error.message} ${STOP_MESSAGES.failed_again}` } + : failure + ) continue } - const stopped = stalled.has(account.id) + const reason = stopped.get(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.', - } + status: read.partial || reason ? 'partial' : 'ok', + ...(reason + ? { message: STOP_MESSAGES[reason] } : read.partial && read.message ? { message: read.message } : {}), diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 1f0b7a2fd69..34fb8e0e6b1 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -402,192 +402,350 @@ 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 +/** The base URL of a site's pages, without a trailing slash. */ +function siteOrigin(site: Record): string { + return string(site.url).replace(/\/$/, '') +} + +const MINUTE_MS = 60_000 + +/** + * A JQL date as minutes before now, which Jira resolves without the member's time zone. Each + * bound widens by a minute for clock drift; every returned instant is checked exactly. + */ +function jiraMinutesAgo(instant: string, widen: 1 | -1): string { + const minutes = Math.floor((Date.now() - Date.parse(instant)) / MINUTE_MS) + widen + return `"-${Math.max(0, minutes)}m"` +} + +/** + * Confluence reads a CQL date in the member's configured time zone, which its API does not + * return. A wall-clock bound shifted by the widest offsets (UTC-12 to UTC+14) plus a minute holds + * the instant in any zone; every returned instant is checked exactly. + */ +function confluenceWallClock(instant: string, offsetHours: number): string { + const shifted = new Date( + Date.parse(instant) + offsetHours * 3_600_000 + Math.sign(offsetHours) * MINUTE_MS + ) + return `"${shifted.toISOString().slice(0, 16).replace('T', ' ').replaceAll('-', '/')}"` +} + +/** Provider pages one bounded listing reads; more is reported as partial coverage. */ +const MAX_LISTING_PAGES = 2 /** - * 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. + * Reads a whole listing, up to {@link MAX_LISTING_PAGES} provider pages. Listings whose order + * is not the person's own action time are read whole and ordered here, so paging by the action + * never skips an item a later edit moved. */ -async function readPastEnd( - readPage: (cursor?: string) => Promise<{ rows: Record[]; next?: string }>, - sortKey: (row: Record) => string, - end: string +async function readListing( + readPage: (cursor?: string) => Promise<{ rows: Record[]; next?: string }> ) { const rows: Record[] = [] let next: string | undefined - for (let page = 0; page < MAX_ACTIVITY_PAGES; page++) { + for (let page = 0; page < MAX_LISTING_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 + if (!next) break } - return { rows, more: Boolean(next) } + return { rows, capped: Boolean(next) } } -/** The base URL of a site's pages, without a trailing slash. */ -function siteOrigin(site: Record): string { - return string(site.url).replace(/\/$/, '') +/** Newest first, with the events at or before the bound. */ +function newestWithin(events: NativeActivityEvent[], input: NativeActivityInput) { + const end = Date.parse(input.end) + return events + .filter((event) => Date.parse(event.at) <= end) + .sort((left, right) => Date.parse(right.at) - Date.parse(left.at)) } -/** - * 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: 'creator', other: 'assignee' }, - assigned: { field: 'updated', self: 'assignee', other: 'reporter' }, -} as const +/** One activity listing and, when it could not be read whole, why its coverage is short. */ +interface ActivityListing { + stream: NativeActivityStream + note?: string +} -async function jiraActivityStream( +const JIRA_FIELDS = [ + 'summary', + 'description', + 'status', + 'created', + 'updated', + 'creator', + 'assignee', +] + +async function jiraSearch( client: NativeClient, - site: Record, + cloudId: string, input: NativeActivityInput, - kind: keyof typeof JIRA_ACTIVITY -): Promise { + jql: string, + extra: Record = {}, + cursor?: string +) { + return object( + await client.json(`/ex/jira/${segment(cloudId)}/rest/api/3/search/jql`, { + body: { + jql, + maxResults: input.limit, + fields: JIRA_FIELDS, + ...extra, + ...(cursor ? { nextPageToken: cursor } : {}), + }, + signal: input.signal, + }) + ) +} + +/** Issues the member created, newest first by creation, read up to the bound. */ +async function jiraCreatedStream( + client: NativeClient, + site: Record, + input: NativeActivityInput +): Promise { const cloudId = string(site.id) - const { field, self, other } = JIRA_ACTIVITY[kind] - 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 + const data = await jiraSearch( + client, + cloudId, + input, + activityQuery( + [ + policyClause('jira', input.policy), + 'creator = currentUser()', + `created >= ${jiraMinutesAgo(input.start, 1)}`, + `created <= ${jiraMinutesAgo(input.end, -1)}`, + ], + 'created' + ) + ) + const rows = array(data.issues) + const createdAt = (row: Record) => string(object(row.fields).created) + return { + stream: { + events: rows.flatMap((row): NativeActivityEvent[] => { + const fields = object(row.fields) + const at = Date.parse(createdAt(row)) + if (!Number.isFinite(at)) return [] + return [ + { + document: issue(row, cloudId, siteOrigin(site)), + at: new Date(at).toISOString(), + action: 'created', + collaborators: displayNames( + [fields.assignee], + string(object(fields.creator).accountId) ), - 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 } + ] + }), + more: Boolean(string(data.nextPageToken)), + scannedTo: oldestInstant(rows.map(createdAt)), }, - sortKey, - input.end - ) - return { - events: rows.flatMap((row): NativeActivityEvent[] => { - const fields = object(row.fields) - const at = string(fields[field]) - if (!Number.isFinite(Date.parse(at))) return [] - return [ - { - document: issue(row, cloudId, siteOrigin(site)), - at: new Date(at).toISOString(), - action: kind, - collaborators: displayNames([fields[other]], string(object(fields[self]).accountId)), - ...(kind === 'assigned' ? { approximateTime: true as const } : {}), - }, - ] - }), - more, - scannedTo: oldestInstant(rows.map(sortKey)), } } -/** One Confluence CQL listing for activity: its rows and whether more follow. */ -async function confluenceActivitySearch( +/** + * Issues assigned to the member in the window, at the moment of that assignment from each + * issue's history. Jira orders them by last update, which a later edit moves, so the listing is + * read whole and ordered by the assignment here. + */ +async function jiraAssignedStream( client: NativeClient, site: Record, - input: NativeActivityInput, - clauses: string[], - field: string, - expand: string, - sortKey: (row: Record) => string -) { - const cql = activityQuery( + input: NativeActivityInput +): Promise { + const cloudId = string(site.id) + const me = string( + object( + await client.json(`/ex/jira/${segment(cloudId)}/rest/api/3/myself`, { + memo: true, + signal: input.signal, + }) + ).accountId + ) + const jql = activityQuery( [ - clauses[0], - policyClause('confluence', input.policy), - ...clauses.slice(1), - ...atlassianDateClauses(field, input.start, input.end), + policyClause('jira', input.policy), + `assignee CHANGED TO currentUser() DURING (${jiraMinutesAgo(input.start, 1)}, ${jiraMinutesAgo(input.end, -1)})`, ], - field + 'updated' ) - 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 { rows, capped } = await readListing(async (cursor) => { + const data = await jiraSearch(client, cloudId, input, jql, { expand: 'changelog' }, cursor) + return { rows: array(data.issues), next: string(data.nextPageToken) || undefined } + }) + const start = Date.parse(input.start) + const end = Date.parse(input.end) + let unmatched = false + const events = rows.flatMap((row): NativeActivityEvent[] => { + const assignedAt = array(object(row.changelog).histories) + .filter((history) => + array(history.items).some( + (item) => string(item.field) === 'assignee' && Boolean(me) && string(item.to) === me + ) ) - 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 + .map((history) => Date.parse(string(history.created))) + .filter((time) => Number.isFinite(time) && time >= start && time <= end) + .sort((left, right) => right - left)[0] + if (assignedAt === undefined) { + unmatched = true + return [] + } + const fields = object(row.fields) + return [ + { + document: issue(row, cloudId, siteOrigin(site)), + at: new Date(assignedAt).toISOString(), + action: 'assigned', + collaborators: displayNames([fields.creator], me || undefined), + }, + ] + }) + return { + stream: { events: newestWithin(events, input), more: false }, + ...(capped || unmatched + ? { + note: capped + ? 'More Jira issues were assigned in this window than one call reads. Narrow the dates.' + : 'Some assigned Jira issues have a history too long to show when they were assigned, and were left out.', + } + : {}), + } +} + +async function confluenceSearch( + client: NativeClient, + site: Record, + input: NativeActivityInput, + cql: string, + expand: string +) { + return readListing(async (cursor) => { + const data = object( + await client.json(`/ex/confluence/${segment(string(site.id))}/wiki/rest/api/search`, { + query: { cql, limit: '50', 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, + } + }) +} + +/** Version histories one activity call reads to find the member's own edit of a page. */ +const MAX_VERSION_CHECKS = 10 + +/** + * The member's latest version of a page within the window, from its version history, or + * undefined when they made none there. + */ +async function ownVersion( + client: NativeClient, + site: Record, + page: NativeDocument, + accountId: string, + input: NativeActivityInput +): Promise<{ at: number; number: number } | undefined> { + const collection = page.kind === 'blogpost' ? 'blogposts' : 'pages' + const data = object( + await client.json( + `/ex/confluence/${segment(string(site.id))}/wiki/api/v2/${collection}/${segment(page.id)}/versions`, + { query: { sort: '-modified-date', limit: '50' }, signal: input.signal } + ) ) + const start = Date.parse(input.start) + const end = Date.parse(input.end) + return array(data.results) + .filter((version) => string(version.authorId) === accountId) + .map((version) => ({ + at: Date.parse(string(version.createdAt)), + number: Number(version.number), + })) + .filter(({ at }) => Number.isFinite(at) && at >= start && at <= end) + .sort((left, right) => right.at - left.at)[0] } /** - * 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. + * Pages and blog posts the member created or edited in the window, at their own latest edit. + * Confluence orders contributed pages by anyone's last edit, so the listing is read whole: a page + * whose last edit is the member's needs nothing more, and up to {@link MAX_VERSION_CHECKS} others + * have their history read. A page the member did not edit in the window is left out. */ async function confluencePageStream( client: NativeClient, site: Record, input: NativeActivityInput, accountId: string -): Promise { - const modifiedAt = (row: Record) => - string(object(object(row.content).version).when) || string(row.lastModified) - const { rows, more } = await confluenceActivitySearch( +): Promise { + const cloudId = string(site.id) + const { rows, capped } = await confluenceSearch( client, site, input, - ['type IN (page, blogpost)', 'contributor = currentUser()'], - 'lastmodified', - 'content.version,content.space,content.history', - modifiedAt + activityQuery( + [ + 'type IN (page, blogpost)', + policyClause('confluence', input.policy), + 'contributor = currentUser()', + `lastmodified >= ${confluenceWallClock(input.start, -12)}`, + ], + 'lastmodified' + ), + 'content.version,content.space,content.history' ) + const start = Date.parse(input.start) + const end = Date.parse(input.end) + let checks = 0 + let unchecked = false + const events: NativeActivityEvent[] = [] + for (const row of rows) { + const document = page(row, cloudId, siteOrigin(site)) + if (!document) continue + const content = object(row.content) + const version = object(content.version) + const last = Date.parse(string(version.when)) + let own: { at: number; number: number } | undefined + if (accountId && string(object(version.by).accountId) === accountId) { + if (Number.isFinite(last) && last >= start && last <= end) + own = { at: last, number: Number(version.number) } + else if (last > end) { + if (checks >= MAX_VERSION_CHECKS) unchecked = true + else { + checks++ + own = await ownVersion(client, site, document, accountId, input) + } + } + } else if (accountId) { + if (checks >= MAX_VERSION_CHECKS) unchecked = true + else { + checks++ + own = await ownVersion(client, site, document, accountId, input) + } + } + if (!own) continue + events.push({ + document, + at: new Date(own.at).toISOString(), + action: own.number === 1 ? 'created' : 'edited', + collaborators: displayNames( + [object(content.history).createdBy, version.by], + accountId || undefined + ), + }) + } return { - events: rows.flatMap((row): NativeActivityEvent[] => { - 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 [] - 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, - scannedTo: oldestInstant(rows.map(modifiedAt)), + stream: { events: newestWithin(events, input), more: false }, + ...(capped || unchecked + ? { + note: 'Confluence holds more pages you contributed to than one call checks. Narrow the dates.', + } + : {}), } } @@ -599,50 +757,59 @@ async function confluenceCommentStream( client: NativeClient, site: Record, input: NativeActivityInput -): Promise { +): Promise { const cloudId = string(site.id) - const createdAt = (row: Record) => - string(object(object(row.content).history).createdDate) - const { rows, more } = await confluenceActivitySearch( + const { rows, capped } = await confluenceSearch( client, site, input, - ['type = comment', 'creator = currentUser()'], - 'created', - 'content.container,content.history,content.space', - createdAt + activityQuery( + [ + 'type = comment', + policyClause('confluence', input.policy), + 'creator = currentUser()', + `created >= ${confluenceWallClock(input.start, -12)}`, + `created <= ${confluenceWallClock(input.end, 14)}`, + ], + 'created' + ), + 'content.container,content.history,content.space' ) - 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), - /** Each comment is its own entry, though several read the same page. */ - dedupeKey: `comment:${string(content.id)}`, - kind, - ...(spaceKey ? { accessMetadata: { spaceKey } } : {}), - container: cloudId, - title: string(container.title) || string(row.title), - url: `${siteOrigin(site)}/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: [], + const events = rows.flatMap((row): NativeActivityEvent[] => { + const content = object(row.content) + const container = object(content.container) + const kind = string(container.type) + const at = Date.parse(string(object(content.history).createdDate)) + if ((kind !== 'page' && kind !== 'blogpost') || !string(container.id)) return [] + if (!Number.isFinite(at)) return [] + const spaceKey = string(object(content.space).key) + return [ + { + 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, + title: string(container.title) || string(row.title), + url: `${siteOrigin(site)}/wiki${string(object(content._links).webui) || string(row.url)}`, + content: providerText(string(row.excerpt).replace(/@@@(?:end)?hl@@@/g, ''), 'html'), + modifiedAt: new Date(at).toISOString(), }, - ] - }), - more, - scannedTo: oldestInstant(rows.map(createdAt)), + at: new Date(at).toISOString(), + action: 'commented', + collaborators: [], + }, + ] + }) + return { + stream: { events: newestWithin(events, input), more: false }, + ...(capped + ? { + note: 'You wrote more Confluence comments in this window than one call reads. Narrow the dates.', + } + : {}), } } @@ -659,34 +826,36 @@ export async function atlassianActivity( 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') + const listings = ( + await Promise.all( + selected.map(async (site) => { + if (provider === 'jira') + return Promise.all([ + jiraCreatedStream(client, site, input), + jiraAssignedStream(client, site, input), + ]) + 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([ - jiraActivityStream(client, site, input, 'created'), - jiraActivityStream(client, site, input, 'assigned'), + confluencePageStream(client, site, input, string(current.accountId)), + confluenceCommentStream(client, site, input), ]) - 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 + }) + ) + ).flat() + const notes = [ + ...new Set(listings.flatMap((listing) => (listing.note ? [listing.note] : []))), + ...(allSites.length > selected.length + ? [`Activity covers the first ${MAX_ACTIVITY_SITES} accessible Atlassian sites.`] + : []), + ] return { - streams: streams.flat(), - ...(skipped - ? { - partial: true, - message: `Activity covers the first ${MAX_ACTIVITY_SITES} accessible Atlassian sites.`, - } - : {}), + streams: listings.map((listing) => listing.stream), + ...(notes.length ? { partial: true, message: notes.join(' ') } : {}), } } diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index bce030e3cdb..e1e101ae000 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -840,6 +840,8 @@ export async function calendarActivity( let overfull = false while (sliceEnd > start && requests < CALENDAR_ACTIVITY_REQUESTS && events.length < input.limit) { const sliceStart = Math.max(start, sliceEnd - CALENDAR_ACTIVITY_SLICE_MS) + /** A slice begun with the whole budget that still cannot be read is too full to page. */ + const firstSlice = requests === 0 const slice: Record[] = [] let timeZone = '' let pageToken: string | undefined @@ -864,7 +866,7 @@ export async function calendarActivity( pageToken = string(data.nextPageToken) || undefined } while (pageToken && requests < CALENDAR_ACTIVITY_REQUESTS) if (pageToken) { - overfull = true + overfull = firstSlice break } for (const event of slice.filter(attendedMeeting)) { diff --git a/apps/sim/lib/sim-search/live/types.ts b/apps/sim/lib/sim-search/live/types.ts index eb8b4408f9f..bc685714372 100644 --- a/apps/sim/lib/sim-search/live/types.ts +++ b/apps/sim/lib/sim-search/live/types.ts @@ -151,8 +151,6 @@ export interface NativeActivityEvent { 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 } /** From 716ff7ff18f8a97309c94adf3443003b3efa77a0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:38:03 -0800 Subject: [PATCH 2/7] refactor(search): read Confluence version histories together and tidy activity constants --- apps/sim/lib/knowledge/mcp/my-activity.ts | 5 +- .../lib/sim-search/live/activity-page.test.ts | 26 ++--- apps/sim/lib/sim-search/live/activity-page.ts | 6 +- apps/sim/lib/sim-search/live/activity.ts | 11 ++- apps/sim/lib/sim-search/live/atlassian.ts | 94 +++++++++++-------- apps/sim/lib/sim-search/live/google.ts | 4 +- 6 files changed, 82 insertions(+), 64 deletions(-) diff --git a/apps/sim/lib/knowledge/mcp/my-activity.ts b/apps/sim/lib/knowledge/mcp/my-activity.ts index 16673c7fa9f..1c403c34644 100644 --- a/apps/sim/lib/knowledge/mcp/my-activity.ts +++ b/apps/sim/lib/knowledge/mcp/my-activity.ts @@ -8,7 +8,7 @@ import { type KnowledgeMcpToolRunner, projectResult, } from '@/lib/knowledge/mcp/tool-runner' -import { listMyActivity } from '@/lib/sim-search/live/activity' +import { listMyActivity, MAX_ACTIVITY_ACCOUNTS } from '@/lib/sim-search/live/activity' import { listLiveSearchAccounts } from '@/lib/sim-search/live/application' import { supportsActivity } from '@/lib/sim-search/live/providers' @@ -19,9 +19,6 @@ interface ListMyActivityToolContext { request: NextRequest } -/** Accounts one call reads at most, as the use case caps them. */ -const MAX_ACTIVITY_ACCOUNTS = 20 - /** * What one call costs against the rate limit: one operation per account it reads, since each is * a separate provider listing. A lookup that fails charges one, as a call reading nothing would. 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 d26a06cff59..7e575720332 100644 --- a/apps/sim/lib/sim-search/live/activity-page.test.ts +++ b/apps/sim/lib/sim-search/live/activity-page.test.ts @@ -51,7 +51,7 @@ function pageThrough( accounts.map((account) => [account.id, { end: END, seen: [] }]) ) const pages: string[][] = [] - const stalled: string[] = [] + const stopped: string[] = [] for (let page = 0; page < 50; page++) { const result = mergeActivityPage( accounts @@ -66,8 +66,8 @@ function pageThrough( topK ) pages.push(result.entries.map((entry) => `${entry.accountId}:${entry.key}`)) - stalled.push(...result.stopped.map((stop) => `${stop.accountId}:${stop.reason}`)) - if (!result.next) return { pages, stalled } + stopped.push(...result.stopped.map((stop) => `${stop.accountId}:${stop.reason}`)) + if (!result.next) return { pages, stopped } bounds = result.next } throw new Error('Paging did not end') @@ -114,10 +114,10 @@ describe('mergeActivityPage', () => { }, ] for (const topK of [2, 10]) { - const { pages, stalled } = pageThrough(accounts, topK) + const { pages, stopped } = pageThrough(accounts, topK) expect(pages.flat()).toEqual(newestFirst(accounts)) expect(pages.every((page) => page.length <= topK)).toBe(true) - expect(stalled).toEqual([]) + expect(stopped).toEqual([]) } }) @@ -206,13 +206,13 @@ describe('mergeActivityPage', () => { ], }, ] - const { pages, stalled } = pageThrough( + const { pages, stopped } = pageThrough( accounts, 1, (accountId, page) => accountId === 'mail' && page === 0 ) expect(new Set(pages.flat())).toEqual(new Set(newestFirst(accounts))) - expect(stalled).toEqual([]) + expect(stopped).toEqual([]) }) it('stops only the account whose listing cannot reach its bound, paging the others', () => { @@ -237,13 +237,13 @@ describe('mergeActivityPage', () => { ], }, ] - const { pages, stalled } = pageThrough(accounts, 1) + const { pages, stopped } = pageThrough(accounts, 1) expect(pages.flat().filter((key) => key.startsWith('mail:'))).toEqual([ 'mail:m1', 'mail:m2', 'mail:m3', ]) - expect(stalled).toEqual(['busy:unreachable']) + expect(stopped).toEqual(['busy:unreachable']) }) it('retries a failed account once, then reports it instead of retrying again', () => { @@ -255,9 +255,9 @@ describe('mergeActivityPage', () => { }, { id: 'mail', limit: 50, items: [{ at: at(5), key: 'm1' }] }, ] - const { pages, stalled } = pageThrough(accounts, 1, (accountId) => accountId === 'mail') + const { pages, stopped } = pageThrough(accounts, 1, (accountId) => accountId === 'mail') expect(pages.flat()).toEqual(['chat:c4', 'chat:c3', 'chat:c2', 'chat:c1']) - expect(stalled).toEqual(['mail:failed_again']) + expect(stopped).toEqual(['mail:failed_again']) }) it('ends without a continuation when only failed accounts would continue', () => { @@ -277,9 +277,9 @@ describe('mergeActivityPage', () => { items: [1, 2, 3, 4, 5].map((index) => ({ at: at(100), key: `c${index}` })), }, ] - const { pages, stalled } = pageThrough(accounts, 10) + const { pages, stopped } = pageThrough(accounts, 10) expect(new Set(pages.flat()).size).toBe(pages.flat().length) - expect(stalled).toEqual(['chat:no_progress']) + expect(stopped).toEqual(['chat:no_progress']) }) it('leaves out entries outside the window and those an earlier page returned at its bound', () => { diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts index e345ba8b342..2f5174ae922 100644 --- a/apps/sim/lib/sim-search/live/activity-page.ts +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -11,6 +11,8 @@ const MAX_ACTIVITY_COLLABORATORS = 10 * them; an account with more than this many entries at one instant stops there. */ const MAX_SEEN_AT_BOUND = 50 +/** Pages that retry a failed account before it is reported as not read. */ +const MAX_ACTIVITY_RETRIES = 1 /** The distinct, nonempty names on one activity entry, at most {@link MAX_ACTIVITY_COLLABORATORS}. */ export function collaboratorNames(names: readonly string[]): string[] { @@ -164,7 +166,7 @@ export function mergeActivityPage( for (const account of accounts) { if (!account.read) { /** A failed account is retried once from its bound, then reported as not read. */ - if ((account.bound.retries ?? 0) >= 1) + if ((account.bound.retries ?? 0) >= MAX_ACTIVITY_RETRIES) stopped.push({ accountId: account.accountId, reason: 'failed_again' }) else next[account.accountId] = { ...account.bound, retries: (account.bound.retries ?? 0) + 1 } continue @@ -226,7 +228,7 @@ 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(), - retries: z.number().int().min(0).max(1).optional(), + retries: z.number().int().min(0).max(MAX_ACTIVITY_RETRIES).optional(), }) const cursorSchema = z .object({ diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index 1713945044f..26a80aaac9f 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -58,7 +58,7 @@ 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 +export 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. */ @@ -66,7 +66,11 @@ 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 -/** Search budgets one account's session gets: up to four sites, each with several listings. */ +/** + * Search request budgets one account's session gets. A Confluence account reads up to four + * sites, each with two listings, a profile and up to ten version histories, so the budget of a + * single search would cut it short. + */ const ACTIVITY_SESSION_SEARCHES = 3 /** Raw items each provider listing reads per page; at least a page's worth of entries. */ const MIN_STREAM_ITEMS = 20 @@ -100,7 +104,7 @@ const STOP_MESSAGES: Record = { } const INVALID_CURSOR_MESSAGE = - 'Invalid cursor. Continue with the same startDate, endDate, source and topK, or start again without a cursor.' + 'Invalid cursor. Continue with the same startDate, endDate and source, or start again without a cursor.' /** The window a first page reads: the requested bounds, defaulted and clamped to now. */ function resolveWindow(input: { startDate?: string; endDate?: string }, now: number) { @@ -356,7 +360,6 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ policies, signal, pool, - /** A page reads several listings per site, and version histories for Confluence. */ searches: ACTIVITY_SESSION_SEARCHES, }), signal diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 34fb8e0e6b1..778cc75f9ea 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -1,3 +1,4 @@ +import { mapWithConcurrency } from '@sim/utils/concurrency' import { collaboratorNames, oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates' import { @@ -376,8 +377,8 @@ export async function searchAtlassian( const MAX_ACTIVITY_SITES = 4 /** - * 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. + * Search's JQL and CQL date bounds: dates compare in the member's profile time zone at day + * precision, so each bound is widened by a day; returned instants are checked exactly. */ function atlassianDateClauses(field: string, start?: string, end?: string): string[] { const day = (instant: string, offsetDays: number) => @@ -564,6 +565,11 @@ async function jiraAssignedStream( }) ).accountId ) + if (!me) + return { + stream: { events: [], more: false }, + note: 'Jira did not return your account, so issues assigned to you were not read.', + } const jql = activityQuery( [ policyClause('jira', input.policy), @@ -582,7 +588,7 @@ async function jiraAssignedStream( const assignedAt = array(object(row.changelog).histories) .filter((history) => array(history.items).some( - (item) => string(item.field) === 'assignee' && Boolean(me) && string(item.to) === me + (item) => string(item.field) === 'assignee' && string(item.to) === me ) ) .map((history) => Date.parse(string(history.created))) @@ -598,7 +604,7 @@ async function jiraAssignedStream( document: issue(row, cloudId, siteOrigin(site)), at: new Date(assignedAt).toISOString(), action: 'assigned', - collaborators: displayNames([fields.creator], me || undefined), + collaborators: displayNames([fields.creator], me), }, ] }) @@ -624,7 +630,7 @@ async function confluenceSearch( return readListing(async (cursor) => { const data = object( await client.json(`/ex/confluence/${segment(string(site.id))}/wiki/rest/api/search`, { - query: { cql, limit: '50', expand, ...(cursor ? { cursor } : {}) }, + query: { cql, limit: CONFLUENCE_PAGE_SIZE, expand, ...(cursor ? { cursor } : {}) }, signal: input.signal, }) ) @@ -640,6 +646,10 @@ async function confluenceSearch( /** Version histories one activity call reads to find the member's own edit of a page. */ const MAX_VERSION_CHECKS = 10 +/** Version histories read at once. */ +const VERSION_CHECK_CONCURRENCY = 5 +/** Results per Confluence search request. */ +const CONFLUENCE_PAGE_SIZE = '50' /** * The member's latest version of a page within the window, from its version history, or @@ -656,7 +666,7 @@ async function ownVersion( const data = object( await client.json( `/ex/confluence/${segment(string(site.id))}/wiki/api/v2/${collection}/${segment(page.id)}/versions`, - { query: { sort: '-modified-date', limit: '50' }, signal: input.signal } + { query: { sort: '-modified-date', limit: CONFLUENCE_PAGE_SIZE }, signal: input.signal } ) ) const start = Date.parse(input.start) @@ -701,44 +711,50 @@ async function confluencePageStream( ) const start = Date.parse(input.start) const end = Date.parse(input.end) - let checks = 0 - let unchecked = false - const events: NativeActivityEvent[] = [] - for (const row of rows) { + /** Pages whose last edit is the member's own, in the window, need no history read. */ + const candidates = rows.flatMap((row) => { const document = page(row, cloudId, siteOrigin(site)) - if (!document) continue + if (!document || !accountId) return [] const content = object(row.content) const version = object(content.version) const last = Date.parse(string(version.when)) - let own: { at: number; number: number } | undefined - if (accountId && string(object(version.by).accountId) === accountId) { - if (Number.isFinite(last) && last >= start && last <= end) - own = { at: last, number: Number(version.number) } - else if (last > end) { - if (checks >= MAX_VERSION_CHECKS) unchecked = true - else { - checks++ - own = await ownVersion(client, site, document, accountId, input) - } - } - } else if (accountId) { - if (checks >= MAX_VERSION_CHECKS) unchecked = true - else { - checks++ - own = await ownVersion(client, site, document, accountId, input) - } + const mine = string(object(version.by).accountId) === accountId + const own = + mine && last >= start && last <= end + ? { at: last, number: Number(version.number) } + : undefined + if (!own && mine && !(last > end)) return [] + return [{ document, content, version, own }] + }) + const toCheck = candidates.filter(({ own }) => !own) + const checked = new Set(toCheck.slice(0, MAX_VERSION_CHECKS)) + const unchecked = toCheck.length > checked.size + const owned = await mapWithConcurrency( + candidates, + VERSION_CHECK_CONCURRENCY, + async (candidate) => + candidate.own ?? + (checked.has(candidate) + ? await ownVersion(client, site, candidate.document, accountId, input) + : undefined) + ) + const events = candidates.flatMap( + ({ document, content, version }, index): NativeActivityEvent[] => { + const own = owned[index] + if (!own) return [] + return [ + { + document, + at: new Date(own.at).toISOString(), + action: own.number === 1 ? 'created' : 'edited', + collaborators: displayNames( + [object(content.history).createdBy, version.by], + accountId || undefined + ), + }, + ] } - if (!own) continue - events.push({ - document, - at: new Date(own.at).toISOString(), - action: own.number === 1 ? 'created' : 'edited', - collaborators: displayNames( - [object(content.history).createdBy, version.by], - accountId || undefined - ), - }) - } + ) return { stream: { events: newestWithin(events, input), more: false }, ...(capped || unchecked diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index e1e101ae000..6bcb6b6bb67 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -824,8 +824,8 @@ function attendedMeeting(event: Record): boolean { /** * 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. + * the start of the last slice read bounds what remains. A slice too full to read on the whole + * budget reports partial coverage; one cut short by an earlier slice resumes on the next page. */ export async function calendarActivity( client: NativeClient, From a934f1e2813f99b7b254beff207199ad7d35d32e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:51:00 -0800 Subject: [PATCH 3/7] fix(search): stop only the activity source that cannot advance and pick each item once per window - A page with no progress stops the accounts pinning the horizon; the others page on - A failed account the listing ends before retrying is reported - Confluence pages and Jira assignments are placed at their latest moment in the whole window, so a later page never repeats them; an unread version history reports partial coverage - Confluence comments before the window are left out - Search MCP charges a continuation by the accounts its cursor still names --- apps/sim/lib/knowledge/mcp/my-activity.ts | 14 ++- .../lib/sim-search/live/activity-page.test.ts | 33 +++++++ apps/sim/lib/sim-search/live/activity-page.ts | 67 ++++++++++---- .../live/activity-providers.test.ts | 87 +++++++++++++++++++ apps/sim/lib/sim-search/live/activity.ts | 10 ++- apps/sim/lib/sim-search/live/atlassian.ts | 55 +++++++----- apps/sim/lib/sim-search/live/types.ts | 6 ++ 7 files changed, 225 insertions(+), 47 deletions(-) diff --git a/apps/sim/lib/knowledge/mcp/my-activity.ts b/apps/sim/lib/knowledge/mcp/my-activity.ts index 1c403c34644..4884645f777 100644 --- a/apps/sim/lib/knowledge/mcp/my-activity.ts +++ b/apps/sim/lib/knowledge/mcp/my-activity.ts @@ -9,6 +9,7 @@ import { projectResult, } from '@/lib/knowledge/mcp/tool-runner' import { listMyActivity, MAX_ACTIVITY_ACCOUNTS } from '@/lib/sim-search/live/activity' +import { activityCursorAccountCount } from '@/lib/sim-search/live/activity-page' import { listLiveSearchAccounts } from '@/lib/sim-search/live/application' import { supportsActivity } from '@/lib/sim-search/live/providers' @@ -26,8 +27,12 @@ interface ListMyActivityToolContext { async function activityCost( principal: Principal, organizationId: string, - source: string | undefined + source: string | undefined, + cursor: string | undefined ): Promise { + /** A continuation reads only the accounts its cursor still names. */ + const continued = cursor ? activityCursorAccountCount(cursor) : undefined + if (continued !== undefined) return Math.min(MAX_ACTIVITY_ACCOUNTS, Math.max(1, continued)) try { const { accounts } = await listLiveSearchAccounts.execute({ principal, @@ -61,7 +66,12 @@ export function registerListMyActivityTool( }, async (input: unknown, extra: { signal: AbortSignal }) => { const requested = listMyActivityMcpSchema.safeParse(input) - const cost = await activityCost(principal, organizationId, requested.data?.source) + const cost = await activityCost( + principal, + organizationId, + requested.data?.source, + requested.data?.cursor + ) return execute( 'list_my_activity', knowledgeOperations.listActivity, 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 7e575720332..e3f4561d508 100644 --- a/apps/sim/lib/sim-search/live/activity-page.test.ts +++ b/apps/sim/lib/sim-search/live/activity-page.test.ts @@ -260,6 +260,39 @@ describe('mergeActivityPage', () => { expect(stopped).toEqual(['mail:failed_again']) }) + it('stops only the account that cannot move past its bound, letting the others page on', () => { + const accounts: FakeAccount[] = [ + { + id: 'stuck', + limit: 2, + items: [1, 2, 3].map((index) => ({ at: at(100), key: `s${index}` })), + }, + { + id: 'mail', + limit: 50, + items: [ + { at: at(90), key: 'm1' }, + { at: at(80), key: 'm2' }, + ], + }, + ] + const { pages, stopped } = pageThrough(accounts, 10) + expect(pages.flat().filter((key) => key.startsWith('mail:'))).toEqual(['mail:m1', 'mail:m2']) + expect(stopped).toEqual(['stuck:no_progress']) + }) + + it('reports a failed account the listing ended before retrying', () => { + const { stopped } = pageThrough( + [ + { id: 'chat', limit: 50, items: [] }, + { id: 'mail', limit: 50, items: [{ at: at(5), key: 'm1' }] }, + ], + 10, + (accountId) => accountId === 'mail' + ) + expect(stopped).toEqual(['mail:not_retried']) + }) + 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 2f5174ae922..8c14d2b59af 100644 --- a/apps/sim/lib/sim-search/live/activity-page.ts +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -65,10 +65,16 @@ export type AccountActivity = { /** * Why an account stopped before reading all its activity: a listing could not page past items - * newer than its bound, more entries than a cursor can name sat at one instant, a page made no - * progress at all, or the account failed again on its one retry. + * newer than its bound, more entries than a cursor can name sat at one instant, it held the + * others at a bound it could not move past, it failed again on its one retry, or it failed and + * the listing ended before it could be retried. */ -export type ActivityStopReason = 'unreachable' | 'crowded' | 'no_progress' | 'failed_again' +export type ActivityStopReason = + | 'unreachable' + | 'crowded' + | 'no_progress' + | 'failed_again' + | 'not_retried' interface ActivityPageResult { /** Newest first. */ @@ -200,28 +206,36 @@ export function mergeActivityPage( } const entries = returned.map(({ entry }) => entry) /** - * 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. + * A page that returned nothing and moved no bound would be read again unchanged. The accounts + * whose listings pin the horizon are the ones that cannot advance, so only they stop; the + * others continue below it on the next page. 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, - stopped: [ - ...stopped, - ...continuing.map((accountId) => ({ accountId, reason: 'no_progress' as const })), - ], + if (continuing.length && !progressed && !entries.length) { + const pinning = continuing.filter((accountId) => { + const account = accounts.find((candidate) => candidate.accountId === accountId) + return ( + account?.read && + account.streams.some( + (stream) => stream.more && Date.parse(stream.scannedTo ?? '') === horizon + ) + ) + }) + for (const accountId of pinning.length ? pinning : [...continuing]) { + stopped.push({ accountId, reason: 'no_progress' }) + delete next[accountId] + continuing.splice(continuing.indexOf(accountId), 1) } + } /** * 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 = Object.keys(next).some((accountId) => !continuing.includes(accountId)) - return { - entries, - ...(continuing.length || (retrying && entries.length) ? { next } : {}), - stopped, - } + const retrying = Object.keys(next).filter((accountId) => !continuing.includes(accountId)) + if (continuing.length || (retrying.length && entries.length)) return { entries, next, stopped } + /** A listing that ends here leaves the failed accounts it would have retried unread. */ + for (const accountId of retrying) stopped.push({ accountId, reason: 'not_retried' }) + return { entries, stopped } } const boundSchema = z.object({ @@ -273,3 +287,18 @@ export function readActivityCursor( return undefined } } + +/** + * How many accounts a cursor continues, for charging a page before it is read. The cursor is not + * verified here; a forged one is refused when the page reads it. + */ +export function activityCursorAccountCount(value: string): number | undefined { + try { + const parsed = cursorSchema + .pick({ accounts: true }) + .safeParse(JSON.parse(Buffer.from(value, 'base64url').toString('utf8'))) + return parsed.success ? Object.keys(parsed.data.accounts).length : 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 index 721b352c6a5..3d28792580f 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -10,6 +10,7 @@ import type { NativeActivityInput, NativeClient } from '@/lib/sim-search/live/ty const WINDOW: NativeActivityInput = { start: '2026-11-01T00:00:00.000Z', end: '2026-11-08T00:00:00.000Z', + windowEnd: '2026-11-08T00:00:00.000Z', limit: 20, scopes: ['search:read.public'], } @@ -278,6 +279,92 @@ describe('Atlassian activity', () => { ]) }) + it('places a page at its latest edit in the whole window, so a later page never repeats it', 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/api/v2/pages/twice/versions') + return { + results: [ + { number: 3, authorId: 'ann', createdAt: '2026-11-07T10:00:00.000Z' }, + { number: 2, authorId: 'me', createdAt: '2026-11-06T10:00:00.000Z' }, + { number: 1, authorId: 'me', createdAt: '2026-11-04T10:00:00.000Z' }, + ], + } + if (path !== '/ex/confluence/cloud/wiki/rest/api/search') return undefined + return String(options?.query?.cql).startsWith('type = comment') + ? { + results: [ + { + content: { + id: 'early', + type: 'comment', + container: { id: '42', type: 'page', title: 'Runbook' }, + history: { createdDate: '2026-10-31T20:00:00.000Z' }, + }, + }, + ], + _links: {}, + } + : { + results: [ + { + content: { + id: 'twice', + type: 'page', + title: 'twice', + version: { + when: '2026-11-07T10:00:00.000Z', + number: 3, + by: { accountId: 'ann' }, + }, + }, + }, + ], + _links: {}, + } + }) + const [pages, comments] = ( + await atlassianActivity(api, 'confluence', { ...WINDOW, end: '2026-11-05T00:00:00.000Z' }) + ).streams + expect(pages?.events).toEqual([]) + expect(comments?.events).toEqual([]) + }) + + it('reports partial coverage when a page history is longer than one read', 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/api/v2/pages/long/versions') + return { + results: [{ number: 90, authorId: 'ann', createdAt: '2026-11-07T10:00:00.000Z' }], + _links: { next: '/wiki/api/v2/pages/long/versions?cursor=x' }, + } + if (path !== '/ex/confluence/cloud/wiki/rest/api/search') return undefined + return String(options?.query?.cql).startsWith('type = comment') + ? { results: [], _links: {} } + : { + results: [ + { + content: { + id: 'long', + type: 'page', + title: 'long', + version: { + when: '2026-11-07T10:00:00.000Z', + number: 90, + by: { accountId: 'ann' }, + }, + }, + }, + ], + _links: {}, + } + }) + const page = await atlassianActivity(api, 'confluence', WINDOW) + expect(page).toMatchObject({ partial: true }) + }) + it('reports a Jira issue at the moment it was assigned to the member, from its history', 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 26a80aaac9f..0ced090017e 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -99,8 +99,10 @@ const STOP_MESSAGES: Record = { crowded: 'This source has more activity at one instant than a page can return, so its older activity in the window was not read.', no_progress: - 'Paging made no progress, so older activity in the window was not read. Narrow the dates to read it.', + 'This source could not move past items it already returned, so its older activity in the window was not read. Narrow the dates to read it.', failed_again: 'It failed again on retry, so its remaining activity was not read.', + not_retried: + 'The listing ended before it could be retried, so its remaining activity was not read.', } const INVALID_CURSOR_MESSAGE = @@ -369,6 +371,7 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ const page = await session.activity({ start: window.start, end: bound.end, + windowEnd: window.end, limit: streamItems, scopes: account.scopes, signal, @@ -468,9 +471,10 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ if (!account) continue if (!read.read) { const failure = failureStatus(account, read.error, organizationId) + const reason = stopped.get(account.id) statuses.push( - stopped.has(account.id) - ? { ...failure, message: `${read.error.message} ${STOP_MESSAGES.failed_again}` } + reason + ? { ...failure, message: `${read.error.message} ${STOP_MESSAGES[reason]}` } : failure ) continue diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 778cc75f9ea..92cfdd1d51b 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -455,9 +455,10 @@ async function readListing( /** Newest first, with the events at or before the bound. */ function newestWithin(events: NativeActivityEvent[], input: NativeActivityInput) { + const start = Date.parse(input.start) const end = Date.parse(input.end) return events - .filter((event) => Date.parse(event.at) <= end) + .filter((event) => Date.parse(event.at) >= start && Date.parse(event.at) <= end) .sort((left, right) => Date.parse(right.at) - Date.parse(left.at)) } @@ -573,7 +574,7 @@ async function jiraAssignedStream( const jql = activityQuery( [ policyClause('jira', input.policy), - `assignee CHANGED TO currentUser() DURING (${jiraMinutesAgo(input.start, 1)}, ${jiraMinutesAgo(input.end, -1)})`, + `assignee CHANGED TO currentUser() DURING (${jiraMinutesAgo(input.start, 1)}, ${jiraMinutesAgo(input.windowEnd, -1)})`, ], 'updated' ) @@ -582,7 +583,8 @@ async function jiraAssignedStream( return { rows: array(data.issues), next: string(data.nextPageToken) || undefined } }) const start = Date.parse(input.start) - const end = Date.parse(input.end) + /** The latest assignment in the whole window, so every page picks the same moment. */ + const windowEnd = Date.parse(input.windowEnd) let unmatched = false const events = rows.flatMap((row): NativeActivityEvent[] => { const assignedAt = array(object(row.changelog).histories) @@ -592,7 +594,7 @@ async function jiraAssignedStream( ) ) .map((history) => Date.parse(string(history.created))) - .filter((time) => Number.isFinite(time) && time >= start && time <= end) + .filter((time) => Number.isFinite(time) && time >= start && time < windowEnd) .sort((left, right) => right - left)[0] if (assignedAt === undefined) { unmatched = true @@ -661,7 +663,7 @@ async function ownVersion( page: NativeDocument, accountId: string, input: NativeActivityInput -): Promise<{ at: number; number: number } | undefined> { +): Promise<{ own?: { at: number; number: number }; incomplete: boolean }> { const collection = page.kind === 'blogpost' ? 'blogposts' : 'pages' const data = object( await client.json( @@ -670,15 +672,19 @@ async function ownVersion( ) ) const start = Date.parse(input.start) - const end = Date.parse(input.end) - return array(data.results) - .filter((version) => string(version.authorId) === accountId) - .map((version) => ({ - at: Date.parse(string(version.createdAt)), - number: Number(version.number), - })) - .filter(({ at }) => Number.isFinite(at) && at >= start && at <= end) + const windowEnd = Date.parse(input.windowEnd) + const versions = array(data.results).map((version) => ({ + at: Date.parse(string(version.createdAt)), + number: Number(version.number), + mine: string(version.authorId) === accountId, + })) + const own = versions + .filter(({ at, mine }) => mine && Number.isFinite(at) && at >= start && at < windowEnd) .sort((left, right) => right.at - left.at)[0] + /** Older history the window still reaches is unread, so a missing edit proves nothing. */ + const oldestRead = Math.min(...versions.map(({ at }) => at).filter(Number.isFinite)) + const incomplete = !own && Boolean(string(object(data._links).next)) && !(oldestRead < start) + return { ...(own ? { own } : {}), incomplete } } /** @@ -710,7 +716,8 @@ async function confluencePageStream( 'content.version,content.space,content.history' ) const start = Date.parse(input.start) - const end = Date.parse(input.end) + /** Each page is placed at its latest edit in the whole window, so every page picks the same moment. */ + const windowEnd = Date.parse(input.windowEnd) /** Pages whose last edit is the member's own, in the window, need no history read. */ const candidates = rows.flatMap((row) => { const document = page(row, cloudId, siteOrigin(site)) @@ -720,10 +727,10 @@ async function confluencePageStream( const last = Date.parse(string(version.when)) const mine = string(object(version.by).accountId) === accountId const own = - mine && last >= start && last <= end + mine && last >= start && last < windowEnd ? { at: last, number: Number(version.number) } : undefined - if (!own && mine && !(last > end)) return [] + if (!own && mine && !(last >= windowEnd)) return [] return [{ document, content, version, own }] }) const toCheck = candidates.filter(({ own }) => !own) @@ -733,14 +740,16 @@ async function confluencePageStream( candidates, VERSION_CHECK_CONCURRENCY, async (candidate) => - candidate.own ?? - (checked.has(candidate) - ? await ownVersion(client, site, candidate.document, accountId, input) - : undefined) + candidate.own + ? { own: candidate.own, incomplete: false } + : checked.has(candidate) + ? await ownVersion(client, site, candidate.document, accountId, input) + : { incomplete: false } ) + const historyCut = owned.some(({ incomplete }) => incomplete) const events = candidates.flatMap( ({ document, content, version }, index): NativeActivityEvent[] => { - const own = owned[index] + const own = owned[index]?.own if (!own) return [] return [ { @@ -757,9 +766,9 @@ async function confluencePageStream( ) return { stream: { events: newestWithin(events, input), more: false }, - ...(capped || unchecked + ...(capped || unchecked || historyCut ? { - note: 'Confluence holds more pages you contributed to than one call checks. Narrow the dates.', + note: 'Confluence holds more pages or page history you contributed to than one call checks. Narrow the dates.', } : {}), } diff --git a/apps/sim/lib/sim-search/live/types.ts b/apps/sim/lib/sim-search/live/types.ts index bc685714372..14debe77f74 100644 --- a/apps/sim/lib/sim-search/live/types.ts +++ b/apps/sim/lib/sim-search/live/types.ts @@ -137,6 +137,12 @@ export interface NativeSearchInput { export interface NativeActivityInput { start: string end: string + /** + * The requested window's exclusive end, fixed across pages. An item counted once per window, + * such as a page at the member's latest edit, is chosen within it so a later page whose `end` + * is earlier never picks an older moment of the same item. + */ + windowEnd: string /** Raw provider items one stream reads per call. */ limit: number scopes: readonly string[] From a836e22badf1066a5822aeb249ee1ad26f230099 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 01:04:44 -0800 Subject: [PATCH 4/7] fix(search): charge Search MCP activity by the accounts a page read, after admission --- apps/sim/lib/knowledge/mcp/my-activity.ts | 60 +++++-------------- apps/sim/lib/knowledge/mcp/server.ts | 4 +- apps/sim/lib/knowledge/mcp/tool-runner.ts | 10 +++- apps/sim/lib/sim-search/live/activity-page.ts | 15 ----- apps/sim/lib/sim-search/live/activity.ts | 2 +- 5 files changed, 29 insertions(+), 62 deletions(-) diff --git a/apps/sim/lib/knowledge/mcp/my-activity.ts b/apps/sim/lib/knowledge/mcp/my-activity.ts index 4884645f777..d1131739861 100644 --- a/apps/sim/lib/knowledge/mcp/my-activity.ts +++ b/apps/sim/lib/knowledge/mcp/my-activity.ts @@ -8,10 +8,7 @@ import { type KnowledgeMcpToolRunner, projectResult, } from '@/lib/knowledge/mcp/tool-runner' -import { listMyActivity, MAX_ACTIVITY_ACCOUNTS } from '@/lib/sim-search/live/activity' -import { activityCursorAccountCount } from '@/lib/sim-search/live/activity-page' -import { listLiveSearchAccounts } from '@/lib/sim-search/live/application' -import { supportsActivity } from '@/lib/sim-search/live/providers' +import { listMyActivity } from '@/lib/sim-search/live/activity' interface ListMyActivityToolContext { execute: KnowledgeMcpToolRunner @@ -20,33 +17,6 @@ interface ListMyActivityToolContext { request: NextRequest } -/** - * What one call costs against the rate limit: one operation per account it reads, since each is - * a separate provider listing. A lookup that fails charges one, as a call reading nothing would. - */ -async function activityCost( - principal: Principal, - organizationId: string, - source: string | undefined, - cursor: string | undefined -): Promise { - /** A continuation reads only the accounts its cursor still names. */ - const continued = cursor ? activityCursorAccountCount(cursor) : undefined - if (continued !== undefined) return Math.min(MAX_ACTIVITY_ACCOUNTS, Math.max(1, continued)) - try { - const { accounts } = await listLiveSearchAccounts.execute({ - principal, - input: { organizationId }, - }) - const read = accounts.filter( - (account) => supportsActivity(account.provider) && (!source || account.provider === source) - ).length - return Math.min(MAX_ACTIVITY_ACCOUNTS, Math.max(1, read)) - } catch { - return 1 - } -} - /** * 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. @@ -64,29 +34,31 @@ export function registerListMyActivityTool( inputSchema: listMyActivityMcpSchema, annotations: KNOWLEDGE_MCP_READ_ONLY, }, - async (input: unknown, extra: { signal: AbortSignal }) => { - const requested = listMyActivityMcpSchema.safeParse(input) - const cost = await activityCost( - principal, - organizationId, - requested.data?.source, - requested.data?.cursor - ) - return execute( + async (input: unknown, extra: { signal: AbortSignal }) => + execute( 'list_my_activity', knowledgeOperations.listActivity, extra.signal, - async (registry, signal) => { + async (registry, signal, charge) => { const parsed = listMyActivityMcpSchema.parse(input) const result = await listMyActivity.execute({ principal, input: { ...parsed, organizationId, resultSecretRegistry: registry, signal }, request, }) + /** + * Each account read is a separate provider listing, so beyond the one operation the call + * was admitted with, it is charged one per further account this page read. + */ + const accountsRead = result.sources.filter( + ({ accountId, status, reason }) => + accountId && + status !== 'unsupported' && + !(status === 'failed' && reason === 'unavailable') + ).length + await charge(accountsRead - 1) return projectResult(result, registry) - }, - cost + } ) - } ) } diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index db2c30eed39..08161777eb6 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -81,7 +81,9 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe : `API rate limit exceeded. Retry in ${Math.ceil(retryAfter / 1000)} seconds.` ) } - const result = await run(new ResolvedSecretTraceRegistry(), signal) + const result = await run(new ResolvedSecretTraceRegistry(), signal, async (more) => { + if (more > 0) await v2RateLimits.publicApi.enforce(request, auth, operation, more) + }) outcome = signal.aborted ? 'cancelled' : result.isError ? 'error' : 'success' resultChars = resultCharacters(result) return result diff --git a/apps/sim/lib/knowledge/mcp/tool-runner.ts b/apps/sim/lib/knowledge/mcp/tool-runner.ts index a3828accab6..e0a42433af4 100644 --- a/apps/sim/lib/knowledge/mcp/tool-runner.ts +++ b/apps/sim/lib/knowledge/mcp/tool-runner.ts @@ -22,7 +22,15 @@ export type KnowledgeMcpToolRunner = ( toolName: SearchMcpActivityInput['toolName'], operation: ApplicationOperation, toolSignal: AbortSignal, - run: (registry: ResolvedSecretTraceRegistry, signal: AbortSignal) => Promise, + run: ( + registry: ResolvedSecretTraceRegistry, + signal: AbortSignal, + /** + * Charges further operations once the call knows what it read, for a call whose size is not + * known before it runs. The call was already admitted, so this only spends the budget. + */ + charge: (cost: number) => Promise + ) => Promise, /** Operations the call performs for the rate limit, such as each document a batched read reads. */ cost?: number ) => Promise diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts index 8c14d2b59af..6c5f23d82aa 100644 --- a/apps/sim/lib/sim-search/live/activity-page.ts +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -287,18 +287,3 @@ export function readActivityCursor( return undefined } } - -/** - * How many accounts a cursor continues, for charging a page before it is read. The cursor is not - * verified here; a forged one is refused when the page reads it. - */ -export function activityCursorAccountCount(value: string): number | undefined { - try { - const parsed = cursorSchema - .pick({ accounts: true }) - .safeParse(JSON.parse(Buffer.from(value, 'base64url').toString('utf8'))) - return parsed.success ? Object.keys(parsed.data.accounts).length : undefined - } catch { - return undefined - } -} diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index 0ced090017e..2e5a8cfa4e7 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -58,7 +58,7 @@ const logger = createLogger('LiveActivity') const DAY_MS = 86_400_000 const DEFAULT_WINDOW_DAYS = 7 /** Accounts one call reads, as one search does. */ -export const MAX_ACTIVITY_ACCOUNTS = 20 +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. */ From b15ece60837080d4b8fcba40ff9e2806b1803804 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 01:14:19 -0800 Subject: [PATCH 5/7] fix(search): admit every activity account read before reading, through the MCP rate limit --- apps/sim/lib/knowledge/mcp/my-activity.ts | 27 ++++++++++--------- apps/sim/lib/knowledge/mcp/server.ts | 24 ++++++++++------- apps/sim/lib/knowledge/mcp/tool-runner.ts | 6 ++--- .../live/activity-paging.integration.ts | 25 +++++++++++++++++ apps/sim/lib/sim-search/live/activity.ts | 6 +++++ 5 files changed, 63 insertions(+), 25 deletions(-) diff --git a/apps/sim/lib/knowledge/mcp/my-activity.ts b/apps/sim/lib/knowledge/mcp/my-activity.ts index d1131739861..4649deddf6f 100644 --- a/apps/sim/lib/knowledge/mcp/my-activity.ts +++ b/apps/sim/lib/knowledge/mcp/my-activity.ts @@ -2,6 +2,7 @@ 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 { OrchestrationError } from '@/lib/core/orchestration/types' import { knowledgeOperations } from '@/lib/knowledge/application/operations' import { KNOWLEDGE_MCP_READ_ONLY, @@ -43,20 +44,22 @@ export function registerListMyActivityTool( const parsed = listMyActivityMcpSchema.parse(input) const result = await listMyActivity.execute({ principal, - input: { ...parsed, organizationId, resultSecretRegistry: registry, signal }, + input: { + ...parsed, + organizationId, + resultSecretRegistry: registry, + signal, + /** + * Each account is a separate provider listing: beyond the one operation the call + * was admitted with, one more per further account, admitted before any is read. + */ + admitReads: async (accounts) => { + const rejected = await charge(accounts - 1) + if (rejected) throw new OrchestrationError('unavailable', rejected) + }, + }, request, }) - /** - * Each account read is a separate provider listing, so beyond the one operation the call - * was admitted with, it is charged one per further account this page read. - */ - const accountsRead = result.sources.filter( - ({ accountId, status, reason }) => - accountId && - status !== 'unsupported' && - !(status === 'failed' && reason === 'unavailable') - ).length - await charge(accountsRead - 1) return projectResult(result, registry) } ) diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 08161777eb6..2d17a73f9ff 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -54,6 +54,14 @@ interface KnowledgeMcpContext { listMyActivity?: boolean } +/** What a caller is told when the rate limit refuses a call, with when to retry if known. */ +function rateLimitMessage(limited: Response): string { + const retryAfter = parseRetryAfter(limited.headers.get('Retry-After'), Number.MAX_SAFE_INTEGER) + return retryAfter === null + ? 'API rate limit exceeded. Please try again later.' + : `API rate limit exceeded. Retry in ${Math.ceil(retryAfter / 1000)} seconds.` +} + /** A request owns its server; no credential or principal survives into another HTTP request. */ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServer { const { request, auth, organizationId } = context @@ -71,18 +79,14 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe signal.throwIfAborted() if (limited) { outcome = 'rate_limited' - const retryAfter = parseRetryAfter( - limited.headers.get('Retry-After'), - Number.MAX_SAFE_INTEGER - ) - return toolError( - retryAfter === null - ? 'API rate limit exceeded. Please try again later.' - : `API rate limit exceeded. Retry in ${Math.ceil(retryAfter / 1000)} seconds.` - ) + return toolError(rateLimitMessage(limited)) } const result = await run(new ResolvedSecretTraceRegistry(), signal, async (more) => { - if (more > 0) await v2RateLimits.publicApi.enforce(request, auth, operation, more) + if (more <= 0) return undefined + const rejected = await v2RateLimits.publicApi.enforce(request, auth, operation, more) + if (!rejected) return undefined + outcome = 'rate_limited' + return rateLimitMessage(rejected) }) outcome = signal.aborted ? 'cancelled' : result.isError ? 'error' : 'success' resultChars = resultCharacters(result) diff --git a/apps/sim/lib/knowledge/mcp/tool-runner.ts b/apps/sim/lib/knowledge/mcp/tool-runner.ts index e0a42433af4..646fef44bd0 100644 --- a/apps/sim/lib/knowledge/mcp/tool-runner.ts +++ b/apps/sim/lib/knowledge/mcp/tool-runner.ts @@ -26,10 +26,10 @@ export type KnowledgeMcpToolRunner = ( registry: ResolvedSecretTraceRegistry, signal: AbortSignal, /** - * Charges further operations once the call knows what it read, for a call whose size is not - * known before it runs. The call was already admitted, so this only spends the budget. + * Admits further operations for a call whose size is known only once it runs, before it does + * that work. Resolves to the rate-limit message when the budget cannot cover them. */ - charge: (cost: number) => Promise + charge: (cost: number) => Promise ) => Promise, /** Operations the call performs for the rate limit, such as each document a batched read reads. */ cost?: number diff --git a/apps/sim/lib/sim-search/live/activity-paging.integration.ts b/apps/sim/lib/sim-search/live/activity-paging.integration.ts index b60cf45e443..eb4063fad02 100644 --- a/apps/sim/lib/sim-search/live/activity-paging.integration.ts +++ b/apps/sim/lib/sim-search/live/activity-paging.integration.ts @@ -22,6 +22,7 @@ interface FakeItem { const { fakes } = vi.hoisted(() => ({ fakes: { accounts: [] as { account: LiveAccount; items: FakeItem[]; readSize: number }[], + reads: 0, }, })) @@ -45,6 +46,7 @@ vi.mock('@/lib/sim-search/live/account-session', () => ({ close: async () => undefined, verify: async () => true, async activity(input: NativeActivityInput) { + fakes.reads++ const window = fake.items.filter( (item) => Date.parse(item.at) <= Date.parse(input.end) && @@ -147,3 +149,26 @@ it('returns every item of every account exactly once, newest first, across pages expect(seen).toEqual(expected) } }) + +it('admits every account a page reads before reading any, and reads none when refused', async () => { + fakes.accounts = [ + { account: account('chat-account', 'slack'), items: items('chat', 2, 2, 7), readSize: 3 }, + { account: account('mail-account', 'gmail'), items: items('mail', 2, 5, 11), readSize: 4 }, + ] + fakes.reads = 0 + const admitted: number[] = [] + await expect( + listMyActivity.execute({ + principal, + input: { + organizationId, + admitReads: async (accounts) => { + admitted.push(accounts) + throw new Error('rate limited') + }, + }, + }) + ).rejects.toThrow('rate limited') + expect(admitted).toEqual([2]) + expect(fakes.reads).toBe(0) +}) diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index 2e5a8cfa4e7..f7689f103d6 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -85,6 +85,11 @@ export interface ListMyActivityInput { cursor?: string signal?: AbortSignal resultSecretRegistry?: ResolvedSecretTraceRegistry + /** + * Admits the provider reads a page is about to make, one per account, before it makes them; a + * surface with a per-call budget rejects by throwing. + */ + admitReads?: (accounts: number) => Promise } /** Whether `list_my_activity` is rolled out to this organization (the `my-activity` flag). */ @@ -326,6 +331,7 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ }) ) /** The window's end is exclusive; a continuation's bound is the inclusive instant it resumes at. */ + await input.admitReads?.(selected.length) const boundOf = (account: LiveAccount): ActivityBound => cursor?.accounts[account.id] ?? { end: new Date(Date.parse(window.end) - 1).toISOString(), From 5f9ea0d22343192a59d5210b80ba92d3f49b4e79 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 01:15:06 -0800 Subject: [PATCH 6/7] chore(search): regenerate Mothership tool contracts after rebasing --- .../sim-assistant-tools.generated.ts | 37 ++++++++++++++++--- .../mothership/generated/tool-catalog-v1.ts | 6 +-- 2 files changed, 34 insertions(+), 9 deletions(-) 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 50b56169b21..b85d1223e8a 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -489,6 +489,10 @@ 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. */ +function peopleFieldFilter(description: string) { + return z.string().trim().min(1).max(200).optional().describe(description) +} + export const searchPeopleInputSchema = z .object({ query: z @@ -508,18 +512,39 @@ export const searchPeopleInputSchema = z .describe( 'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.' ), + name: peopleFieldFilter('Only people whose name contains this text.'), + email: z + .string() + .trim() + .min(3) + .max(320) + .optional() + .describe('Only the person with this exact email address.'), + title: peopleFieldFilter('Only people whose title contains this text.'), + department: peopleFieldFilter('Only people whose department contains this text.'), + location: peopleFieldFilter('Only people whose location contains this text.'), + managerPersonId: z + .string() + .min(1) + .max(255) + .optional() + .describe('Only the direct reports of this personId.'), cursor: z .string() .min(1) .max(1024) .optional() - .describe('nextCursor from the previous page of the same query.'), + .describe('nextCursor from the previous page of the same query and filters.'), }) .strict() - .refine((input) => !input.personId || (input.query === undefined && !input.cursor), { - path: ['personId'], - message: 'Pass either personId or a query with its cursor, not both.', - }) + .refine( + ({ personId, ...listing }) => + !personId || Object.values(listing).every((value) => value === undefined), + { + path: ['personId'], + message: 'Pass either personId or a query with its filters and cursor, not both.', + } + ) /** * The caller's own questions to Sim over a window, oldest first. The 92-day window and the page @@ -630,7 +655,7 @@ export const assistantToolContracts = [ id: 'search_people', route: 'sim', description: - '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.', + 'Look up people in this organization’s directory by name, email, title, department, or location, with query across all of them or a filter per field; managerPersonId lists someone’s direct reports. Returns each person’s title, department, location, email, start date, time zone, Slack user ID, manager, and direct report count. 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, }, { diff --git a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts index 8fe2bba5570..834b6ffb594 100644 --- a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts @@ -12,7 +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.' + | 'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted, Jira issues you created or that were assigned to you, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more; a source that failed and recovers on a later page can return entries older than that page. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.' | 'Look up people in this organization’s directory by name, email, title, department, or location, with query across all of them or a filter per field; managerPersonId lists someone’s direct reports. Returns each person’s title, department, location, email, start date, time zone, Slack user ID, manager, and direct report count. 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.' @@ -7883,7 +7883,7 @@ 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.', + 'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent (replied when the message answers another), Google Calendar meetings you organized or accepted, Jira issues you created or that were assigned to you, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more; a source that failed and recovers on a later page can return entries older than that page. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', route: 'sim', parameters: { $schema: 'http://json-schema.org/draft-07/schema#', @@ -7940,7 +7940,7 @@ export const ListMyActivity: ToolCatalogEntry = { }, cursor: { description: - 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.', + 'nextCursor from the previous page, with the same startDate, endDate and source; topK may change. Pages continue newest first without gaps.', type: 'string', minLength: 1, maxLength: 40000, From f5988521f3954b97fc033beb181335a5a2b5eaa4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 01:28:44 -0800 Subject: [PATCH 7/7] fix(search): read Jira assignments at a fixed page size and check cancellation around admission --- apps/sim/lib/knowledge/mcp/server.ts | 2 ++ .../live/activity-paging.integration.ts | 14 ++++++++-- .../live/activity-providers.test.ts | 27 +++++++++++++++++++ apps/sim/lib/sim-search/live/atlassian.ts | 14 ++++++++-- 4 files changed, 53 insertions(+), 4 deletions(-) diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 2d17a73f9ff..8afaeb1fc63 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -83,7 +83,9 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe } const result = await run(new ResolvedSecretTraceRegistry(), signal, async (more) => { if (more <= 0) return undefined + signal.throwIfAborted() const rejected = await v2RateLimits.publicApi.enforce(request, auth, operation, more) + signal.throwIfAborted() if (!rejected) return undefined outcome = 'rate_limited' return rateLimitMessage(rejected) diff --git a/apps/sim/lib/sim-search/live/activity-paging.integration.ts b/apps/sim/lib/sim-search/live/activity-paging.integration.ts index eb4063fad02..41b8be4ebcd 100644 --- a/apps/sim/lib/sim-search/live/activity-paging.integration.ts +++ b/apps/sim/lib/sim-search/live/activity-paging.integration.ts @@ -134,13 +134,23 @@ it('returns every item of every account exactly once, newest first, across pages .flatMap(({ items: list }) => list) .sort((left, right) => Date.parse(right.at) - Date.parse(left.at)) .map((item) => item.id) - for (const topK of [2, 10]) { + /** Each listing changes its page size after the first page, as a continuation may. */ + for (const [firstTopK, laterTopK] of [ + [2, 2], + [10, 10], + [2, 7], + [10, 3], + ]) { const seen: string[] = [] let cursor: string | undefined for (let page = 0; page < 30 && (page === 0 || cursor); page++) { const result = await listMyActivity.execute({ principal, - input: { organizationId, topK, ...(cursor ? { cursor } : {}) }, + input: { + organizationId, + topK: page ? laterTopK : firstTopK, + ...(cursor ? { cursor } : {}), + }, }) seen.push(...result.items.map(({ title }) => title)) cursor = result.nextCursor 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 3d28792580f..a5df1782b90 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -365,6 +365,33 @@ describe('Atlassian activity', () => { expect(page).toMatchObject({ partial: true }) }) + it('reads every assignment in the window whatever page size the caller asks for', async () => { + const assigned = ['ENG-1', 'ENG-2', 'ENG-3'].map((key, index) => ({ + key, + fields: { summary: key, updated: '2026-11-07T09:00:00.000Z' }, + changelog: { + histories: [ + { + created: `2026-11-0${index + 2}T08:00:00.000Z`, + items: [{ field: 'assignee', to: 'me' }], + }, + ], + }, + })) + const api = client((path, options) => { + if (path === '/oauth/token/accessible-resources') return [site] + if (path === '/ex/jira/cloud/rest/api/3/myself') return { accountId: 'me' } + if (path !== '/ex/jira/cloud/rest/api/3/search/jql') return undefined + const body = (options as { body?: { jql?: string; maxResults?: number } } | undefined)?.body + if (!body?.jql?.includes('assignee CHANGED TO currentUser()')) return { issues: [] } + return { issues: assigned.slice(0, body.maxResults) } + }) + const page = await atlassianActivity(api, 'jira', { ...WINDOW, limit: 2 }) + expect( + page.streams.flatMap((stream) => stream.events.map((event) => event.document.id)) + ).toEqual(['ENG-3', 'ENG-2', 'ENG-1']) + }) + it('reports a Jira issue at the moment it was assigned to the member, from its history', async () => { const api = client((path, options) => { if (path === '/oauth/token/accessible-resources') return [site] diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 92cfdd1d51b..cd80f7df0e2 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -431,6 +431,8 @@ function confluenceWallClock(instant: string, offsetHours: number): string { return `"${shifted.toISOString().slice(0, 16).replace('T', ' ').replaceAll('-', '/')}"` } +/** Results per provider request of a listing read whole, the same on every page of a listing. */ +const LISTING_PAGE_SIZE = 50 /** Provider pages one bounded listing reads; more is reported as partial coverage. */ const MAX_LISTING_PAGES = 2 @@ -579,7 +581,15 @@ async function jiraAssignedStream( 'updated' ) const { rows, capped } = await readListing(async (cursor) => { - const data = await jiraSearch(client, cloudId, input, jql, { expand: 'changelog' }, cursor) + /** A fixed page size, so a continuation that asks for fewer entries reads the same issues. */ + const data = await jiraSearch( + client, + cloudId, + input, + jql, + { expand: 'changelog', maxResults: LISTING_PAGE_SIZE }, + cursor + ) return { rows: array(data.issues), next: string(data.nextPageToken) || undefined } }) const start = Date.parse(input.start) @@ -651,7 +661,7 @@ const MAX_VERSION_CHECKS = 10 /** Version histories read at once. */ const VERSION_CHECK_CONCURRENCY = 5 /** Results per Confluence search request. */ -const CONFLUENCE_PAGE_SIZE = '50' +const CONFLUENCE_PAGE_SIZE = String(LISTING_PAGE_SIZE) /** * The member's latest version of a page within the window, from its version history, or