Skip to content

Commit 65f07c0

Browse files
authored
fix(search): chat history leaves out inbox turns, reads newest first, and uses an indexed scan (#10560)
* fix(search): chat history leaves out inbox turns, reads newest first, and uses an indexed scan * fix(search): never show thinking cut off by the answer prefix
1 parent e0ae4c4 commit 65f07c0

19 files changed

Lines changed: 34832 additions & 72 deletions

File tree

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

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,8 @@ export const OrganizationBlock: BlockConfig = {
9898
id: 'historyStartDate',
9999
title: 'Start Date',
100100
type: 'short-input',
101-
placeholder: '2026-01-01T00:00:00-08:00 (inclusive)',
101+
placeholder: '7 days before End Date, or an inclusive ISO datetime',
102102
condition: { field: 'operation', value: 'list_my_chat_history' },
103-
required: { field: 'operation', value: 'list_my_chat_history' },
104103
},
105104
{
106105
id: 'historyEndDate',
@@ -117,6 +116,18 @@ export const OrganizationBlock: BlockConfig = {
117116
condition: { field: 'operation', value: 'list_my_chat_history' },
118117
mode: 'advanced',
119118
},
119+
{
120+
id: 'historySortBy',
121+
title: 'Order',
122+
type: 'dropdown',
123+
options: [
124+
{ label: 'Newest first', id: 'newest' },
125+
{ label: 'Oldest first', id: 'oldest' },
126+
],
127+
value: () => 'newest',
128+
condition: { field: 'operation', value: 'list_my_chat_history' },
129+
mode: 'advanced',
130+
},
120131
{
121132
id: 'includeAnswers',
122133
title: 'Include Answers',
@@ -302,6 +313,7 @@ export const OrganizationBlock: BlockConfig = {
302313
startDate: blockFieldOrToolArg(context, params.historyStartDate, params.startDate),
303314
endDate: blockFieldOrToolArg(context, params.historyEndDate, params.endDate),
304315
cursor: blockFieldOrToolArg(context, params.historyCursor, params.cursor),
316+
sortBy: blockFieldOrToolArg(context, params.historySortBy, params.sortBy),
305317
}
306318
: {}),
307319
...(operation === 'search'
@@ -353,6 +365,7 @@ export const OrganizationBlock: BlockConfig = {
353365
personId: { type: 'string', description: 'Person to show with their reporting line' },
354366
cursor: { type: 'string', description: 'Next page of a people search or activity listing' },
355367
historyCursor: { type: 'string', description: 'Chat history: next page of the same window' },
368+
historySortBy: { type: 'string', description: 'Chat history: newest or oldest first' },
356369
historyStartDate: {
357370
type: 'string',
358371
description: 'Chat history: inclusive start (ISO datetime)',
@@ -383,7 +396,7 @@ export const OrganizationBlock: BlockConfig = {
383396
},
384397
questions: {
385398
type: 'array',
386-
description: 'List My Chat History: the person’s own questions, oldest first',
399+
description: 'List My Chat History: the person’s own questions, newest first by default',
387400
},
388401
note: { type: 'string', description: 'Search People: guidance when no one matches' },
389402
window: { type: 'json', description: 'List My Activity: the window read' },

‎apps/sim/lib/api/contracts/knowledge/mcp.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
import { mcpJsonRpcMessageSchema } from '@/lib/api/contracts/mcp'
77
import {
88
listMyActivityInputFieldsSchema,
9+
listMyChatHistoryInputSchema,
910
readDocumentInputSchema,
1011
refineActivityWindow,
1112
refineSearchWorkspaceInput,
@@ -75,6 +76,12 @@ export const listMyActivityMcpSchema = listMyActivityInputFieldsSchema
7576
.strict()
7677
.superRefine(refineActivityWindow)
7778

79+
/** list_my_chat_history as the Search MCP presents it: a date without an offset reads as UTC. */
80+
export const listMyChatHistoryMcpSchema = listMyChatHistoryInputSchema.extend({
81+
startDate: mcpDateFilter(listMyChatHistoryInputSchema.shape.startDate),
82+
endDate: mcpDateFilter(listMyChatHistoryInputSchema.shape.endDate),
83+
})
84+
7885
/**
7986
* Previews a search returns when the caller sets no topK. A query across every source shares one
8087
* list among all of them, so it gets more room than a search of one source, a native query, or a

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

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -528,24 +528,29 @@ export const searchPeopleInputSchema = z
528528
)
529529

530530
/**
531-
* The caller's own questions to Sim over a window, oldest first. The 92-day window and the page
532-
* bounds are literals so the worker's generated copy stays standalone.
531+
* The caller's own questions to Sim over a window, newest first by default. The 92-day window
532+
* and the page bounds are literals so the worker's generated copy stays standalone.
533533
*/
534534
export const listMyChatHistoryInputSchema = z
535535
.object({
536536
startDate: z
537537
.string()
538538
.datetime({ offset: true })
539+
.optional()
539540
.describe(
540-
'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.'
541+
'Inclusive start of the window, an ISO datetime with your timezone offset. Defaults to 7 days before endDate; the window spans at most 92 days.'
541542
),
542543
endDate: z
543544
.string()
544545
.datetime({ offset: true })
545546
.optional()
546547
.describe(
547-
'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.'
548+
'Exclusive end of the window, an ISO datetime with your timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.'
548549
),
550+
sortBy: z
551+
.enum(['newest', 'oldest'])
552+
.optional()
553+
.describe('newest (the default) or oldest first.'),
549554
topK: z
550555
.number()
551556
.int()
@@ -558,7 +563,7 @@ export const listMyChatHistoryInputSchema = z
558563
.min(1)
559564
.max(1024)
560565
.optional()
561-
.describe('nextCursor from the previous page of the same window.'),
566+
.describe('nextCursor from the previous page of the same window and order.'),
562567
includeAnswers: z
563568
.boolean()
564569
.optional()
@@ -643,7 +648,7 @@ export const assistantToolContracts = [
643648
id: 'list_my_chat_history',
644649
route: 'sim',
645650
description:
646-
'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.',
651+
'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, newest first, each with a link to its conversation. Covers only your own conversations that still exist.',
647652
inputSchema: listMyChatHistoryInputSchema,
648653
},
649654
{

‎apps/sim/lib/auth/oauth-provider.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export const OAUTH_SCOPE_DESCRIPTIONS: Record<OAuthScope, string> = {
9595
[OAUTH_API_READ_SCOPE]: 'Read your workspaces, workflows, files, tables, and logs',
9696
[OAUTH_API_WRITE_SCOPE]: 'Read, create, change, run, and delete resources in your workspaces',
9797
[OAUTH_SEARCH_READ_SCOPE]:
98-
'Search and read documents you can access, look up people in your organization, and start private Sim Search conversations',
98+
'Search and read documents you can access, look up people in your organization, start private Sim Search conversations, and list your own questions to Sim',
9999
}
100100

101101
/**

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

Lines changed: 124 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
copilotChats,
1010
copilotMessages,
1111
member,
12+
mothershipInboxTask,
1213
organization,
1314
permissions,
1415
project,
@@ -57,13 +58,22 @@ function session(userId: string): SessionPrincipal {
5758
return { kind: 'session', userId, sessionId: generateId() }
5859
}
5960

61+
/** Oldest first unless a test asks otherwise, so fixtures read in the order they were written. */
6062
function list(input: Record<string, unknown> = {}, userId = callerId) {
6163
return listMyChatHistory.execute({
6264
principal: session(userId),
63-
input: { ...WINDOW, organizationId, ...input },
65+
input: { ...WINDOW, sortBy: 'oldest', organizationId, ...input },
6466
})
6567
}
6668

69+
/** Each chat's transcript position, as `persistCopilotChatTurn` numbers saved messages. */
70+
const seqs = new Map<string, number>()
71+
function nextSeq(chatId: string): number {
72+
const seq = (seqs.get(chatId) ?? 0) + 1
73+
seqs.set(chatId, seq)
74+
return seq
75+
}
76+
6777
async function chat(values: Partial<typeof copilotChats.$inferInsert> = {}): Promise<string> {
6878
const id = generateId()
6979
await db.insert(copilotChats).values({
@@ -87,6 +97,7 @@ async function ask(
8797
messageId: generateId(),
8898
role: 'user',
8999
content: { content },
100+
seq: nextSeq(chatId),
90101
createdAt: new Date(createdAt),
91102
...extra,
92103
})
@@ -309,6 +320,7 @@ describe('list_my_chat_history', () => {
309320
chatId: id,
310321
messageId: generateId(),
311322
role: 'assistant',
323+
seq: nextSeq(id),
312324
content: {
313325
content: `Two releases shipped <source>{"id":"c1"}</source>. ${'x'.repeat(900)}`,
314326
},
@@ -321,6 +333,22 @@ describe('list_my_chat_history', () => {
321333
expect((await list()).questions[0]?.answerExcerpt).toBeUndefined()
322334
})
323335

336+
it('never shows hidden thinking cut off by the answer prefix', async () => {
337+
const id = await chat()
338+
await ask(id, 'a long think', '2026-11-02T10:00:00Z')
339+
await db.insert(copilotMessages).values({
340+
chatId: id,
341+
messageId: generateId(),
342+
role: 'assistant',
343+
seq: nextSeq(id),
344+
content: { content: `<thinking>${'private reasoning '.repeat(400)}</thinking>The answer` },
345+
createdAt: new Date('2026-11-02T10:00:30Z'),
346+
})
347+
348+
const [question] = (await list({ includeAnswers: true })).questions
349+
expect(question?.answerExcerpt).toBeUndefined()
350+
})
351+
324352
it("gives an unanswered question no answer, rather than the next question's", async () => {
325353
const id = await chat()
326354
await ask(id, 'stopped question', '2026-11-02T10:00:00Z')
@@ -329,6 +357,7 @@ describe('list_my_chat_history', () => {
329357
chatId: id,
330358
messageId: generateId(),
331359
role: 'assistant',
360+
seq: nextSeq(id),
332361
content: { content: 'The answer to the deleted question' },
333362
createdAt: new Date('2026-11-02T10:00:30Z'),
334363
})
@@ -337,6 +366,7 @@ describe('list_my_chat_history', () => {
337366
chatId: id,
338367
messageId: generateId(),
339368
role: 'assistant',
369+
seq: nextSeq(id),
340370
content: { content: 'The answer to the second question' },
341371
createdAt: new Date('2026-11-02T10:01:30Z'),
342372
})
@@ -400,6 +430,99 @@ describe('list_my_chat_history', () => {
400430
expect(futureEnd.questions.map((q) => q.question)).toContain('recent')
401431
})
402432

433+
it('lists newest first by default, and a cursor only continues the order it came from', async () => {
434+
const id = await chat()
435+
await ask(id, 'earlier', '2026-11-02T10:00:00Z')
436+
await ask(id, 'later', '2026-11-03T10:00:00Z')
437+
438+
const newest = await list({ sortBy: undefined, topK: 1 })
439+
expect(newest.questions.map((q) => q.question)).toEqual(['later'])
440+
expect(
441+
(await list({ sortBy: undefined, cursor: newest.nextCursor })).questions.map(
442+
(q) => q.question
443+
)
444+
).toEqual(['earlier'])
445+
await expect(list({ sortBy: 'oldest', cursor: newest.nextCursor })).rejects.toThrow(
446+
/same sortBy/
447+
)
448+
})
449+
450+
it('continues a page in the window its cursor fixed, whatever dates come with it', async () => {
451+
const id = await chat()
452+
await ask(id, 'first', '2026-11-02T10:00:00Z')
453+
await ask(id, 'second', '2026-11-03T10:00:00Z')
454+
455+
const page = await list({ topK: 1 })
456+
const next = await list({
457+
cursor: page.nextCursor,
458+
startDate: '2026-11-03T12:00:00Z',
459+
endDate: '2026-11-04T00:00:00Z',
460+
})
461+
expect(next.questions.map((q) => q.question)).toEqual(['second'])
462+
})
463+
464+
it('refuses a cursor whose window is longer than a first page may read', async () => {
465+
const forged = Buffer.from(
466+
JSON.stringify([
467+
'oldest',
468+
'2020-01-01T00:00:00.000Z',
469+
'2026-11-08T00:00:00.000Z',
470+
'2026-11-02T10:00:00.000000Z',
471+
generateId(),
472+
])
473+
).toString('base64url')
474+
await expect(list({ cursor: forged })).rejects.toThrow(/nextCursor/)
475+
})
476+
477+
it('finds the answer to a question saved without a transcript seq', async () => {
478+
const id = await chat()
479+
await ask(id, 'unnumbered question', '2026-11-02T10:00:00Z', { seq: null })
480+
await db.insert(copilotMessages).values({
481+
chatId: id,
482+
messageId: generateId(),
483+
role: 'assistant',
484+
content: { content: 'Unnumbered answer' },
485+
createdAt: new Date('2026-11-02T10:00:30Z'),
486+
})
487+
488+
const { questions } = await list({ includeAnswers: true })
489+
expect(questions.map((q) => [q.question, q.answerExcerpt])).toEqual([
490+
['unnumbered question', 'Unnumbered answer'],
491+
])
492+
})
493+
494+
it('reads the 7 days before the end without a startDate, and refuses a startDate in the future', async () => {
495+
const id = await chat()
496+
await ask(id, 'three days ago', new Date(Date.now() - 3 * 86_400_000).toISOString())
497+
await ask(id, 'ten days ago', new Date(Date.now() - 10 * 86_400_000).toISOString())
498+
499+
const lastWeek = await list({ startDate: undefined, endDate: undefined })
500+
expect(lastWeek.questions.map((q) => q.question)).toEqual(['three days ago'])
501+
await expect(
502+
list({ startDate: new Date(Date.now() + 86_400_000).toISOString(), endDate: undefined })
503+
).rejects.toThrow(/startDate is in the future/)
504+
})
505+
506+
it('never lists an inbox email turn run as the caller, nor a forked copy of it', async () => {
507+
const inboxChat = await chat({ organizationId: null, workspaceId: openWorkspaceId })
508+
const emailed = generateId()
509+
await ask(inboxChat, 'an email from someone else', '2026-11-02T10:00:00Z', {
510+
messageId: emailed,
511+
})
512+
await db.insert(mothershipInboxTask).values({
513+
id: generateId(),
514+
workspaceId: openWorkspaceId,
515+
fromEmail: 'stranger@example.test',
516+
subject: 'Request',
517+
chatId: inboxChat,
518+
})
519+
const fork = await chat()
520+
await ask(fork, 'an email from someone else', '2026-11-02T10:00:00Z', { messageId: emailed })
521+
await ask(fork, 'my own follow-up', '2026-11-02T11:00:00Z')
522+
523+
expect((await list()).questions.map((q) => q.question)).toEqual(['my own follow-up'])
524+
})
525+
403526
it('refuses a caller outside the organization and a principal that is not a person', async () => {
404527
await ask(await chat(), 'private', '2026-11-02T10:00:00Z')
405528

0 commit comments

Comments
 (0)