Skip to content

Commit 2b4de28

Browse files
feat(search): count Search use per integration (#10681)
* feat(search): count Search use per integration Adds organization_search_integration_daily, a content-free daily count per organization, surface, integration and member of how each search reached an integration (ok, partial, reconnect, rate limited, unavailable, timeout) and of results opened from it. Searches count on the same surfaces member activity counts, set by the adapter that knows the surface. Opens are recorded through a member-only organization endpoint from the Search page and organization chats. Rows cascade with the member or organization and are swept with adoption history after 400 days. * fix(search): drop non-null assertions and unused exports in Search opens - Pass organizationId in the open mutation's variables, so the caller's organization check types it instead of a non-null assertion - Keep the open contract's body and surface schemas file-local - Tighten comments that overstated what the counts and migration promise - Assert the outsider refusal by its error class; drop a test that only exercised input validation and a client test that asserted on mocks * fix(search): count opens from recently viewed sources on the Search page * fix(search): keep integration counts on listings, tool results and recovered chats - Key a Search page listing's repeat rule by the filters the caller sent, not the end date the listing implies, so a refetch within the minute counts nothing. - Open chat tool-activity results through the shared source navigation, so they count like other opened sources. - Give a recovered interactive chat turn the surface its chat post set, so its searches still count; unattended turns still count nothing. * fix(search): give the search activity result link a props interface * refactor(search): reuse the account status and open surface types for integration counts --------- Co-authored-by: Waleed Latif <walif6@gmail.com>
1 parent d1bb321 commit 2b4de28

37 files changed

Lines changed: 35699 additions & 160 deletions

File tree

‎apps/docs/content/docs/platform/self-hosting/background-jobs.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ Create a workflow with a Schedule trigger set to every minute, deploy it, and wa
182182
| Table row TTL cleanup | `/api/cron/cleanup-table-row-ttl` | `*/15 * * * *` | Deletes table rows whose TTL column has expired |
183183
| Stale execution cleanup | `/api/cron/cleanup-stale-executions` | `*/30 * * * *` | Fails runs whose worker died without finishing — workflow executions, background jobs, table jobs and table runs — so they stop showing as running |
184184
| OAuth token cleanup | `/api/cron/cleanup-oauth-tokens` | `0 * * * *` | Deletes access and refresh tokens after the retention tail |
185-
| Activity history cleanup | `/api/cron/cleanup-activity-history` | `45 4 * * *` | Deletes organization adoption history past its retention: daily member activity and Search MCP call metadata after 400 days |
185+
| Activity history cleanup | `/api/cron/cleanup-activity-history` | `45 4 * * *` | Deletes organization adoption history past its retention: daily member activity, daily Search integration counts and Search MCP call metadata after 400 days |
186186
| Workspace source staging cleanup | `/api/cron/cleanup-source-staging` | `30 * * * *` | Deletes binary files staged for a workspace source apply a day after they were last staged |
187187
| SCIM reconciliation | `/api/cron/scim-reconcile` | `17 * * * *` | Re-applies directory group mappings |
188188
| Data drains | `/api/cron/run-data-drains` | `*/15 * * * *` | Enterprise data drains; each drain runs only when its own cadence is due |

‎apps/sim/app/api/knowledge/search/route.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export const POST = defineInternalJsonRoute({
2121
...body,
2222
signal: request.signal,
2323
surface: 'dashboard' as const,
24+
activitySurface: 'search' as const,
2425
}),
2526
useCase: searchLiveKnowledge,
2627
present: (data) => ({ success: true as const, data }),
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { recordSearchOpenContract } from '@/lib/api/contracts/knowledge/search-activity'
2+
import {
3+
defineInternalJsonRoute,
4+
internalOrchestrationErrorPolicy,
5+
internalRateLimits,
6+
internalSessionAuth,
7+
} from '@/lib/api/server/routes'
8+
import {
9+
recordSearchOpen,
10+
searchActivityOperations,
11+
} from '@/lib/knowledge/application/search-activity'
12+
13+
export const POST = defineInternalJsonRoute({
14+
contract: recordSearchOpenContract,
15+
auth: internalSessionAuth,
16+
operation: searchActivityOperations.recordOpen,
17+
rateLimit: internalRateLimits.user({ bucketName: 'search-opens-write' }),
18+
errorPolicy: internalOrchestrationErrorPolicy,
19+
mapInput: ({ params, body }) => ({ organizationId: params.id, ...body }),
20+
useCase: recordSearchOpen,
21+
staticResponseHeaders: { 'Cache-Control': 'private, no-store' },
22+
})

‎apps/sim/app/o/[organizationId]/components/organization-conversation.tsx‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ import {
3636
} from '@/app/o/[organizationId]/search/search-params'
3737
import { ChatResourcePanel } from '@/app/workspace/[workspaceId]/home/components/chat-resource-panel'
3838
import { ComposerScrollArea } from '@/app/workspace/[workspaceId]/home/components/composer-scroll-area'
39-
import { useSearchHistoryActions } from '@/app/workspace/[workspaceId]/home/components/message-content/components/source-history-context'
39+
import {
40+
SourceOpenSurfaceProvider,
41+
useSearchHistoryActions,
42+
} from '@/app/workspace/[workspaceId]/home/components/message-content/components/source-history-context'
4043
import { SearchIntegrationConnection } from '@/app/workspace/[workspaceId]/home/components/message-content/components/special-tags/search-integration-connection'
4144
import { MothershipChat } from '@/app/workspace/[workspaceId]/home/components/mothership-chat'
4245
import { SourcesResourceContent } from '@/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/sources-resource-content'
@@ -120,10 +123,12 @@ export function OrganizationConversation(props: OrganizationConversationProps) {
120123
if (isRestoredChatEntry || !isClient || !session?.user?.id)
121124
return <HomeFallback header={props.header} />
122125
return (
123-
<OrganizationConversationContent
124-
key={`${session.user.id}:${organization.id}:${props.chatId ?? 'new'}:${props.panelOptions ? 'panel' : props.requestMode}`}
125-
{...props}
126-
/>
126+
<SourceOpenSurfaceProvider surface={props.requestMode === 'assistant' ? 'assistant' : 'agent'}>
127+
<OrganizationConversationContent
128+
key={`${session.user.id}:${organization.id}:${props.chatId ?? 'new'}:${props.panelOptions ? 'panel' : props.requestMode}`}
129+
{...props}
130+
/>
131+
</SourceOpenSurfaceProvider>
127132
)
128133
}
129134

‎apps/sim/app/o/[organizationId]/search/search-results-view.tsx‎

Lines changed: 42 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { OrganizationLanding } from '@/app/o/[organizationId]/components/organiz
1212
import { PAGE_COLUMN_CLASS } from '@/app/o/[organizationId]/components/organization-page'
1313
import { useOrganizationContext } from '@/app/o/[organizationId]/providers/organization-provider'
1414
import { KnowledgeSearchResults } from '@/app/workspace/[workspaceId]/home/components/knowledge-search-results'
15+
import { SourceOpenSurfaceProvider } from '@/app/workspace/[workspaceId]/home/components/message-content/components/source-history-context'
1516
import {
1617
SIDEBAR_DIVIDER_PAD_ABOVE_CLASS,
1718
SIDEBAR_DIVIDER_PAD_BELOW_CLASS,
@@ -24,7 +25,10 @@ interface SearchResultsViewProps {
2425
onSearchChange?: (search: SearchResource) => void
2526
}
2627

27-
/** Standalone Search uses the original centered field and docked results layout. */
28+
/**
29+
* Standalone Search uses the original centered field and docked results layout. Its results and
30+
* the recently viewed sources under the field both count opens toward the `search` surface.
31+
*/
2832
export function SearchResultsView({
2933
composer,
3034
query,
@@ -41,40 +45,44 @@ export function SearchResultsView({
4145
enabled: searching,
4246
})
4347
return (
44-
<div className='flex h-full min-h-0 flex-col bg-[var(--bg)]'>
45-
{searching ? (
46-
<>
47-
<div className={cn(PAGE_COLUMN_CLASS, SIDEBAR_DIVIDER_PAD_ABOVE_CLASS, 'shrink-0 pt-8')}>
48-
{composer}
49-
</div>
50-
<div
51-
ref={scrollContainerRef}
52-
className={cn(
53-
SIDEBAR_DIVIDER_PAD_BELOW_CLASS,
54-
SIDEBAR_DIVIDER_PAD_ABOVE_CLASS,
55-
scrollFadeClass,
56-
overflowFadeSizeClass,
57-
'min-h-0 flex-1 overflow-y-auto [scrollbar-gutter:stable_both-edges]'
58-
)}
59-
{...scrollFadeAttributes(scrollEdges)}
60-
>
61-
{/* The rows carry their own `px-2`; this gutter brings each row's mark under the
48+
<SourceOpenSurfaceProvider surface='search'>
49+
<div className='flex h-full min-h-0 flex-col bg-[var(--bg)]'>
50+
{searching ? (
51+
<>
52+
<div
53+
className={cn(PAGE_COLUMN_CLASS, SIDEBAR_DIVIDER_PAD_ABOVE_CLASS, 'shrink-0 pt-8')}
54+
>
55+
{composer}
56+
</div>
57+
<div
58+
ref={scrollContainerRef}
59+
className={cn(
60+
SIDEBAR_DIVIDER_PAD_BELOW_CLASS,
61+
SIDEBAR_DIVIDER_PAD_ABOVE_CLASS,
62+
scrollFadeClass,
63+
overflowFadeSizeClass,
64+
'min-h-0 flex-1 overflow-y-auto [scrollbar-gutter:stable_both-edges]'
65+
)}
66+
{...scrollFadeAttributes(scrollEdges)}
67+
>
68+
{/* The rows carry their own `px-2`; this gutter brings each row's mark under the
6269
field's own search glyph, so results read as a column hanging from the field. */}
63-
<div ref={scrollContentRef} className={cn(PAGE_COLUMN_CLASS, 'px-8')}>
64-
<KnowledgeSearchResults
65-
scope={scope}
66-
query={query}
67-
onSummarize={onSummarize}
68-
onSearchChange={onSearchChange}
69-
/>
70+
<div ref={scrollContentRef} className={cn(PAGE_COLUMN_CLASS, 'px-8')}>
71+
<KnowledgeSearchResults
72+
scope={scope}
73+
query={query}
74+
onSummarize={onSummarize}
75+
onSearchChange={onSearchChange}
76+
/>
77+
</div>
7078
</div>
71-
</div>
72-
</>
73-
) : (
74-
<OrganizationLanding heading={`Search ${organization.name}`}>
75-
{composer}
76-
</OrganizationLanding>
77-
)}
78-
</div>
79+
</>
80+
) : (
81+
<OrganizationLanding heading={`Search ${organization.name}`}>
82+
{composer}
83+
</OrganizationLanding>
84+
)}
85+
</div>
86+
</SourceOpenSurfaceProvider>
7987
)
8088
}

‎apps/sim/app/workspace/[workspaceId]/home/components/message-content/components/agent-group/search-activity-results.tsx‎

Lines changed: 44 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,8 @@ import {
1515
sourceLabel,
1616
sourceSiteName,
1717
} from '@/app/workspace/[workspaceId]/home/components/message-content/components/source-chip'
18-
import {
19-
externalLinkHostname,
20-
handleExternalLinkClick,
21-
} from '@/app/workspace/[workspaceId]/home/components/message-content/components/source-link'
18+
import { useSourceNavigation } from '@/app/workspace/[workspaceId]/home/components/message-content/components/source-history-context'
19+
import { externalLinkHostname } from '@/app/workspace/[workspaceId]/home/components/message-content/components/source-link'
2220
import type { SourceTagData } from '@/app/workspace/[workspaceId]/home/components/message-content/components/special-tags'
2321

2422
interface SearchActivityResultsProps {
@@ -49,39 +47,50 @@ export function SearchActivityResults({ sources, label }: SearchActivityResultsP
4947
{...scrollFadeAttributes(edges)}
5048
>
5149
<ul className='m-0 list-none p-0'>
52-
{sources.map((source) => {
53-
const hostname = externalLinkHostname(source.url)
54-
return (
55-
<li key={source.url}>
56-
<a
57-
href={source.url}
58-
target='_blank'
59-
rel='noopener noreferrer'
60-
onClick={(event) => handleExternalLinkClick(event, source.url)}
61-
className={cn(
62-
'not-prose flex h-8 min-w-0 items-center gap-2 px-2 text-[var(--text-body)] text-small no-underline transition-colors focus-visible:bg-[var(--surface-hover)] focus-visible:outline-none',
63-
chipHoverSurfaceClass,
64-
chipRadiusClass
65-
)}
66-
>
67-
<span className={chipIconSlotClass}>
68-
<SourceIcon source={source} />
69-
</span>
70-
<OverflowText
71-
label={sourceLabel(source)}
72-
focusTarget='nearest-interactive'
73-
className='flex-1'
74-
/>
75-
<OverflowText
76-
label={hostname?.replace(/^www\./, '') ?? sourceSiteName(source)}
77-
className='max-w-[35%] text-[var(--text-muted)] text-caption'
78-
/>
79-
</a>
80-
</li>
81-
)
82-
})}
50+
{sources.map((source) => (
51+
<li key={source.url}>
52+
<SearchActivityResultLink source={source} />
53+
</li>
54+
))}
8355
</ul>
8456
</div>
8557
</div>
8658
)
8759
}
60+
61+
interface SearchActivityResultLinkProps {
62+
source: SourceTagData
63+
}
64+
65+
/** Opens through the shared source-open boundary, so a result opened here is counted like any other. */
66+
function SearchActivityResultLink({ source }: SearchActivityResultLinkProps) {
67+
const navigate = useSourceNavigation(source)
68+
const hostname = externalLinkHostname(source.url)
69+
return (
70+
<a
71+
href={source.url}
72+
target='_blank'
73+
rel='noopener noreferrer'
74+
onClick={navigate}
75+
onAuxClick={navigate}
76+
className={cn(
77+
'not-prose flex h-8 min-w-0 items-center gap-2 px-2 text-[var(--text-body)] text-small no-underline transition-colors focus-visible:bg-[var(--surface-hover)] focus-visible:outline-none',
78+
chipHoverSurfaceClass,
79+
chipRadiusClass
80+
)}
81+
>
82+
<span className={chipIconSlotClass}>
83+
<SourceIcon source={source} />
84+
</span>
85+
<OverflowText
86+
label={sourceLabel(source)}
87+
focusTarget='nearest-interactive'
88+
className='flex-1'
89+
/>
90+
<OverflowText
91+
label={hostname?.replace(/^www\./, '') ?? sourceSiteName(source)}
92+
className='max-w-[35%] text-[var(--text-muted)] text-caption'
93+
/>
94+
</a>
95+
)
96+
}

‎apps/sim/app/workspace/[workspaceId]/home/components/message-content/components/source-history-context.tsx‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,27 @@ import {
1010
} from 'react'
1111
import { noop } from '@sim/utils/helpers'
1212
import { truncateAtCodePoint } from '@sim/utils/string'
13+
import type { SearchOpenSurface } from '@/lib/api/contracts/knowledge/search-activity'
1314
import type { ViewedSearchSource } from '@/lib/api/contracts/knowledge/search-history'
1415
import { isKnowledgeSourceUrl } from '@/lib/knowledge/search/source-url'
16+
import { isLiveSearchProviderId } from '@/lib/sim-search/live/provider-catalog'
1517
import { handleExternalLinkClick } from '@/app/workspace/[workspaceId]/home/components/message-content/components/source-link'
1618
import type { SourceTagData } from '@/app/workspace/[workspaceId]/home/components/message-content/components/special-tags'
19+
import { useRecordSearchOpen } from '@/hooks/queries/search-activity'
1720
import { useRecordSearchHistory } from '@/hooks/queries/search-history'
1821

1922
interface SourceHistoryContextValue {
2023
recordSource: (source: ViewedSearchSource) => void
2124
recordQuery: (query: string) => void
25+
recordOpen: (connectorType: string | undefined, surface: SearchOpenSurface | undefined) => void
2226
}
2327
const SourceHistoryContext = createContext<SourceHistoryContextValue>({
2428
recordSource: noop,
2529
recordQuery: noop,
30+
recordOpen: noop,
2631
})
32+
/** Where the sources below it are opened from; none outside an organization's Search surfaces. */
33+
const SourceOpenSurfaceContext = createContext<SearchOpenSurface | undefined>(undefined)
2734

2835
interface SourceHistoryProviderProps {
2936
organizationId?: string
@@ -38,6 +45,7 @@ export function SourceHistoryProvider({
3845
children,
3946
}: SourceHistoryProviderProps) {
4047
const { mutate } = useRecordSearchHistory(organizationId, userId)
48+
const { mutate: countOpen } = useRecordSearchOpen()
4149
const recordSource = useCallback(
4250
(source: ViewedSearchSource) => {
4351
if (
@@ -58,20 +66,46 @@ export function SourceHistoryProvider({
5866
},
5967
[organizationId, userId, mutate]
6068
)
61-
const value = useMemo(() => ({ recordSource, recordQuery }), [recordSource, recordQuery])
69+
const recordOpen = useCallback(
70+
(connectorType: string | undefined, surface: SearchOpenSurface | undefined) => {
71+
if (organizationId && userId && surface && isLiveSearchProviderId(connectorType))
72+
countOpen({ organizationId, connectorType, surface })
73+
},
74+
[organizationId, userId, countOpen]
75+
)
76+
const value = useMemo(
77+
() => ({ recordSource, recordQuery, recordOpen }),
78+
[recordSource, recordQuery, recordOpen]
79+
)
6280
return <SourceHistoryContext.Provider value={value}>{children}</SourceHistoryContext.Provider>
6381
}
6482

83+
interface SourceOpenSurfaceProviderProps {
84+
surface: SearchOpenSurface
85+
children: ReactNode
86+
}
87+
88+
/** Names the Search surface the sources below it are opened from, so each open counts there. */
89+
export function SourceOpenSurfaceProvider({ surface, children }: SourceOpenSurfaceProviderProps) {
90+
return (
91+
<SourceOpenSurfaceContext.Provider value={surface}>
92+
{children}
93+
</SourceOpenSurfaceContext.Provider>
94+
)
95+
}
96+
6597
export function useSearchHistoryActions() {
6698
return useContext(SourceHistoryContext)
6799
}
68100

69101
/** Native, keyboard and middle-click navigation share the same source-open boundary. */
70102
export function useSourceNavigation(source: SourceTagData) {
71-
const { recordSource } = useSearchHistoryActions()
103+
const { recordSource, recordOpen } = useSearchHistoryActions()
104+
const surface = useContext(SourceOpenSurfaceContext)
72105
return useCallback(
73106
(event: MouseEvent<HTMLAnchorElement>) => {
74107
if (event.defaultPrevented || (event.button !== 0 && event.button !== 1)) return
108+
recordOpen(source.connectorType, surface)
75109
recordSource({
76110
url: source.url,
77111
title: source.title?.trim() ? truncateAtCodePoint(source.title.trim(), 512, '') : undefined,
@@ -84,6 +118,14 @@ export function useSourceNavigation(source: SourceTagData) {
84118
})
85119
handleExternalLinkClick(event, source.url)
86120
},
87-
[source.url, source.title, source.siteName, source.connectorType, recordSource]
121+
[
122+
source.url,
123+
source.title,
124+
source.siteName,
125+
source.connectorType,
126+
surface,
127+
recordSource,
128+
recordOpen,
129+
]
88130
)
89131
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { useMutation } from '@tanstack/react-query'
2+
import { requestJson } from '@/lib/api/client/request'
3+
import {
4+
type RecordSearchOpenBody,
5+
recordSearchOpenContract,
6+
} from '@/lib/api/contracts/knowledge/search-activity'
7+
8+
interface RecordSearchOpenVariables extends RecordSearchOpenBody {
9+
organizationId: string
10+
}
11+
12+
/**
13+
* Counts an opened Search result toward its integration. No client query reads these counts, so
14+
* there is nothing to invalidate.
15+
*/
16+
export function useRecordSearchOpen() {
17+
return useMutation({
18+
mutationFn: ({ organizationId, ...body }: RecordSearchOpenVariables) =>
19+
requestJson(recordSearchOpenContract, { params: { id: organizationId }, body }),
20+
})
21+
}

0 commit comments

Comments
 (0)