Skip to content

Commit c7c8a2f

Browse files
authored
improvement(search): smaller chat history pages with a first-page total (#10567)
* improvement(search): smaller chat history pages, a first-page total, and an ids-only workspace check * fix(search): an empty first page counts zero; total is optional in workflow outputs
1 parent a75dd84 commit c7c8a2f

6 files changed

Lines changed: 112 additions & 38 deletions

File tree

‎apps/sim/blocks/blocks/organization.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,10 @@ export const OrganizationBlock: BlockConfig = {
395395
type: 'array',
396396
description: 'List My Chat History: the person’s own questions, newest first by default',
397397
},
398+
total: {
399+
type: 'number',
400+
description: 'List My Chat History: questions in the window, on the first page only',
401+
},
398402
note: { type: 'string', description: 'Search People: guidance when no one matches' },
399403
window: { type: 'json', description: 'List My Activity: the window read' },
400404
items: { type: 'array', description: 'List My Activity: activity entries, newest first' },

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

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
workspace,
1818
} from '@sim/db/schema'
1919
import { generateId } from '@sim/utils/id'
20-
import { inArray } from 'drizzle-orm'
20+
import { and, eq, inArray } from 'drizzle-orm'
2121
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
2222

2323
/** What the caller may open now: chat reads decide it from Build and Plan mode, stood in here. */
@@ -285,6 +285,44 @@ describe('list_my_chat_history', () => {
285285
}
286286
})
287287

288+
it('opens every workspace of the organization to an admin, without a permission on each', async () => {
289+
await ask(
290+
await chat({ organizationId: null, workspaceId: closedWorkspaceId }),
291+
'closed workspace',
292+
'2026-11-02T11:00:00Z'
293+
)
294+
expect((await list()).questions).toEqual([])
295+
await db
296+
.update(member)
297+
.set({ role: 'admin' })
298+
.where(and(eq(member.userId, callerId), eq(member.organizationId, organizationId)))
299+
try {
300+
expect((await list()).questions.map((q) => q.question)).toEqual(['closed workspace'])
301+
} finally {
302+
await db
303+
.update(member)
304+
.set({ role: 'member' })
305+
.where(and(eq(member.userId, callerId), eq(member.organizationId, organizationId)))
306+
}
307+
})
308+
309+
it('counts zero on the first page of an empty history', async () => {
310+
expect(await list()).toEqual({ total: 0, questions: [] })
311+
})
312+
313+
it('caps each question, and counts the whole window on the first page only', async () => {
314+
const id = await chat()
315+
await ask(id, 'q'.repeat(2_000), '2026-11-02T10:00:00Z')
316+
await ask(id, 'short', '2026-11-03T10:00:00Z')
317+
318+
const first = await list({ topK: 1 })
319+
expect(first.total).toBe(2)
320+
expect(first.questions[0]?.question).toBe(`${'q'.repeat(400)}...`)
321+
const next = await list({ topK: 1, cursor: first.nextCursor })
322+
expect(next.total).toBeUndefined()
323+
expect(next.questions.map((q) => q.question)).toEqual(['short'])
324+
})
325+
288326
it('includes startDate and excludes endDate, and refuses a window over 92 days', async () => {
289327
const id = await chat()
290328
await ask(id, 'at start', WINDOW.startDate)
@@ -329,7 +367,7 @@ describe('list_my_chat_history', () => {
329367

330368
const withAnswers = (await list({ includeAnswers: true })).questions[0]
331369
expect(withAnswers?.answerExcerpt?.startsWith('Two releases shipped . x')).toBe(true)
332-
expect(withAnswers?.answerExcerpt?.length).toBeLessThan(700)
370+
expect(withAnswers?.answerExcerpt?.length).toBeLessThanOrEqual(303)
333371
expect((await list()).questions[0]?.answerExcerpt).toBeUndefined()
334372
})
335373

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

Lines changed: 61 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
import { requirePrincipalSubjectUserId } from '@sim/auth/principal'
22
import { db } from '@sim/db'
3-
import { copilotChats, copilotMessages, mothershipInboxTask } from '@sim/db/schema'
3+
import {
4+
copilotChats,
5+
copilotMessages,
6+
mothershipInboxTask,
7+
permissions,
8+
workspace,
9+
} from '@sim/db/schema'
10+
import { isOrgAdminRole } from '@sim/platform-authz/workspace'
411
import { truncateAtCodePoint } from '@sim/utils/string'
512
import { and, asc, desc, eq, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm'
613
import { z } from 'zod'
@@ -19,14 +26,14 @@ import { type ConversationMode, conversationModeSelection } from '@/lib/mothersh
1926
import { requireOrganizationBuildPermission } from '@/lib/mothership/chat/organization-chats'
2027
import { isPlanModeEnabled } from '@/lib/mothership/feature-flags'
2128
import { organizationRoutes } from '@/lib/navigation/paths'
22-
import { listAccessibleWorkspaceRowsForUser } from '@/lib/workspaces/utils'
2329

2430
const DAY_MS = 86_400_000
2531
const MAX_WINDOW_DAYS = 92
2632
const DEFAULT_WINDOW_DAYS = 7
2733
const DEFAULT_TOP_K = 50
28-
const QUESTION_MAX_CHARS = 2_000
29-
const ANSWER_EXCERPT_MAX_CHARS = 600
34+
/** Characters of each question and answer returned: a page stays small enough to read inline. */
35+
const QUESTION_MAX_CHARS = 400
36+
const ANSWER_EXCERPT_MAX_CHARS = 300
3037
/** Answer characters read for an excerpt: enough to strip cards and citation tags from. */
3138
const ANSWER_READ_CHARS = 4_000
3239
/** Orders a message without a transcript `seq` after every numbered one, as transcripts read. */
@@ -46,6 +53,8 @@ interface ChatHistoryQuestion {
4653
}
4754

4855
type ChatHistoryPage = {
56+
/** Every question in the window, returned on the first page only. */
57+
total?: number
4958
questions: ChatHistoryQuestion[]
5059
nextCursor?: string
5160
}
@@ -161,11 +170,16 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({
161170
const after = input.cursor ? decodeCursor(input.cursor, sort) : undefined
162171
const { from, to } = after ?? resolveWindow(input)
163172

164-
const workspaceIds = (
165-
await listAccessibleWorkspaceRowsForUser(userId, 'active', organizationId)
166-
)
167-
.filter(({ workspace }) => workspace.organizationId === organizationId)
168-
.map(({ workspace }) => workspace.id)
173+
/**
174+
* The organization's active workspaces the caller can open, as ids in the chat read itself:
175+
* every one for an organization admin or owner, otherwise those they hold a permission on.
176+
*/
177+
const accessibleWorkspaceIds = isOrgAdminRole(context.role)
178+
? sql`SELECT ${workspace.id} FROM ${workspace}
179+
WHERE ${workspace.organizationId} = ${organizationId} AND ${workspace.archivedAt} IS NULL`
180+
: sql`SELECT w.id FROM ${permissions} p JOIN ${workspace} w ON w.id = p.entity_id
181+
WHERE p.user_id = ${userId} AND p.entity_type = 'workspace'
182+
AND w.organization_id = ${organizationId} AND w.archived_at IS NULL`
169183
/**
170184
* Only conversations the caller may open now, as chat reads decide it: agent and plan chats
171185
* in the organization need Build, plan chats need Plan mode, and Assistant chats need neither.
@@ -207,18 +221,16 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({
207221
eq(copilotChats.organizationId, organizationId),
208222
inArray(conversationModeSelection, organizationModes)
209223
),
210-
workspaceIds.length
211-
? and(
212-
inArray(copilotChats.workspaceId, workspaceIds),
213-
inArray(conversationModeSelection, workspaceModes)
214-
)
215-
: undefined
224+
and(
225+
sql`${copilotChats.workspaceId} IN (${accessibleWorkspaceIds})`,
226+
inArray(conversationModeSelection, workspaceModes)
227+
)
216228
),
217229
isNull(copilotChats.deletedAt),
218230
sql`${copilotChats.config}->'benchmark' IS NULL`
219231
)
220232
)
221-
if (!chats.length) return { questions: [] }
233+
if (!chats.length) return after ? { questions: [] } : { total: 0, questions: [] }
222234
const chatById = new Map(chats.map((chat) => [chat.id, chat]))
223235

224236
/**
@@ -261,35 +273,47 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({
261273
: sql<null>`NULL`
262274
const newest = sort === 'newest'
263275

264-
const rows = await db
276+
/** The caller's own questions in the window: the page and, on the first page, its total. */
277+
const questionFilter = [
278+
inArray(copilotMessages.chatId, [...chatById.keys()]),
279+
eq(copilotMessages.role, 'user'),
280+
isNull(copilotMessages.deletedAt),
281+
sql`${copilotMessages.content}->>'origin' IS NULL`,
282+
/**
283+
* Inbox email turns run for their sender as the workspace owner; neither they nor their
284+
* forked copies (same message id and time) are the caller's own questions.
285+
*/
286+
sql`NOT EXISTS (
287+
SELECT 1 FROM ${copilotMessages} im
288+
JOIN ${mothershipInboxTask} t ON t.chat_id = im.chat_id
289+
WHERE im.role = 'user' AND im.deleted_at IS NULL
290+
AND im.created_at = copilot_messages.created_at
291+
AND im.message_id = copilot_messages.message_id)`,
292+
gte(copilotMessages.createdAt, from),
293+
lt(copilotMessages.createdAt, to),
294+
]
295+
/** Counted once, on the first page, from the same index range the page reads. */
296+
const totalQuery = after
297+
? undefined
298+
: db
299+
.select({ total: sql<number>`count(*)::int` })
300+
.from(copilotMessages)
301+
.where(and(...questionFilter))
302+
303+
const rowsQuery = db
265304
.select({
266305
id: copilotMessages.id,
267306
chatId: copilotMessages.chatId,
268307
createdAt: preciseTimestampText(copilotMessages.createdAt),
269308
question: sql<
270309
string | null
271-
>`left(${copilotMessages.content}->>'content', ${QUESTION_MAX_CHARS})`,
310+
>`left(${copilotMessages.content}->>'content', ${QUESTION_MAX_CHARS + 1})`,
272311
answer,
273312
})
274313
.from(copilotMessages)
275314
.where(
276315
and(
277-
inArray(copilotMessages.chatId, [...chatById.keys()]),
278-
eq(copilotMessages.role, 'user'),
279-
isNull(copilotMessages.deletedAt),
280-
sql`${copilotMessages.content}->>'origin' IS NULL`,
281-
/**
282-
* Inbox email turns run for their sender as the workspace owner; neither they nor their
283-
* forked copies (same message id and time) are the caller's own questions.
284-
*/
285-
sql`NOT EXISTS (
286-
SELECT 1 FROM ${copilotMessages} im
287-
JOIN ${mothershipInboxTask} t ON t.chat_id = im.chat_id
288-
WHERE im.role = 'user' AND im.deleted_at IS NULL
289-
AND im.created_at = copilot_messages.created_at
290-
AND im.message_id = copilot_messages.message_id)`,
291-
gte(copilotMessages.createdAt, from),
292-
lt(copilotMessages.createdAt, to),
316+
...questionFilter,
293317
after
294318
? newest
295319
? sql`(${copilotMessages.createdAt}, ${copilotMessages.id}) < (cast(${after.createdAt} as timestamp), ${after.id}::uuid)`
@@ -304,10 +328,13 @@ export const listMyChatHistory = defineAuthorizedOrganizationUseCase({
304328
)
305329
.limit(topK + 1)
306330

331+
const [rows, counted] = await Promise.all([rowsQuery, totalQuery])
332+
const total = counted?.[0]?.total
307333
const routes = organizationRoutes(organizationId)
308334
const page = rows.slice(0, topK)
309335
const last = page[page.length - 1]
310336
return {
337+
...(total === undefined ? {} : { total }),
311338
questions: page.flatMap((row) => {
312339
const chat = chatById.get(row.chatId)
313340
if (!chat) return []

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ export function registerListMyChatHistoryTool(
2424
{
2525
title: 'List my chat history',
2626
description:
27-
'List the questions you asked Sim between startDate (inclusive, 7 days before endDate by default) and endDate (exclusive, now by default; at most 92 days apart), newest first unless sortBy is oldest: the Assistant, agent chats, the Slack app and this server’s chat tool. Each carries its time, a link to the conversation and, with includeAnswers, the start of the answer. Only your own conversations that still exist are listed. Follow nextCursor for the next page.',
27+
'List the questions you asked Sim between startDate (inclusive, 7 days before endDate by default) and endDate (exclusive, now by default; at most 92 days apart), newest first unless sortBy is oldest: the Assistant, agent chats, the Slack app and this server’s chat tool. Each carries its time, a link to the conversation and, with includeAnswers, the start of the answer. Only your own conversations that still exist are listed. The first page carries total, the number of questions in the window; follow nextCursor for the next page.',
2828
inputSchema: listMyChatHistoryMcpSchema,
2929
annotations: KNOWLEDGE_MCP_READ_ONLY,
3030
},

‎apps/sim/tools/generated/tool-outputs.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎apps/sim/tools/organization/list_my_chat_history.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,11 @@ export const organizationListMyChatHistoryTool: InternalToolConfig<
7878
description:
7979
'The questions, newest first by default: timestamp, question, chatId, conversationUrl, surface, answerExcerpt',
8080
},
81+
total: {
82+
type: 'number',
83+
description: 'Questions in the window, on the first page only',
84+
optional: true,
85+
},
8186
nextCursor: { type: 'string', description: 'Cursor for the next page of the same window' },
8287
},
8388
}

0 commit comments

Comments
 (0)