Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions apps/sim/blocks/blocks/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,8 @@ export const OrganizationBlock: BlockConfig = {
id: 'historyStartDate',
title: 'Start Date',
type: 'short-input',
placeholder: '2026-01-01T00:00:00-08:00 (inclusive)',
placeholder: '7 days before End Date, or an inclusive ISO datetime',
condition: { field: 'operation', value: 'list_my_chat_history' },
required: { field: 'operation', value: 'list_my_chat_history' },
},
{
id: 'historyEndDate',
Expand All @@ -117,6 +116,18 @@ export const OrganizationBlock: BlockConfig = {
condition: { field: 'operation', value: 'list_my_chat_history' },
mode: 'advanced',
},
{
id: 'historySortBy',
title: 'Order',
type: 'dropdown',
options: [
{ label: 'Newest first', id: 'newest' },
{ label: 'Oldest first', id: 'oldest' },
],
value: () => 'newest',
condition: { field: 'operation', value: 'list_my_chat_history' },
mode: 'advanced',
},
{
id: 'includeAnswers',
title: 'Include Answers',
Expand Down Expand Up @@ -302,6 +313,7 @@ export const OrganizationBlock: BlockConfig = {
startDate: blockFieldOrToolArg(context, params.historyStartDate, params.startDate),
endDate: blockFieldOrToolArg(context, params.historyEndDate, params.endDate),
cursor: blockFieldOrToolArg(context, params.historyCursor, params.cursor),
sortBy: blockFieldOrToolArg(context, params.historySortBy, params.sortBy),
}
: {}),
...(operation === 'search'
Expand Down Expand Up @@ -353,6 +365,7 @@ export const OrganizationBlock: BlockConfig = {
personId: { type: 'string', description: 'Person to show with their reporting line' },
cursor: { type: 'string', description: 'Next page of a people search or activity listing' },
historyCursor: { type: 'string', description: 'Chat history: next page of the same window' },
historySortBy: { type: 'string', description: 'Chat history: newest or oldest first' },
historyStartDate: {
type: 'string',
description: 'Chat history: inclusive start (ISO datetime)',
Expand Down Expand Up @@ -383,7 +396,7 @@ export const OrganizationBlock: BlockConfig = {
},
questions: {
type: 'array',
description: 'List My Chat History: the person’s own questions, oldest first',
description: 'List My Chat History: the person’s own questions, newest first by default',
},
note: { type: 'string', description: 'Search People: guidance when no one matches' },
window: { type: 'json', description: 'List My Activity: the window read' },
Expand Down
7 changes: 7 additions & 0 deletions apps/sim/lib/api/contracts/knowledge/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import { mcpJsonRpcMessageSchema } from '@/lib/api/contracts/mcp'
import {
listMyActivityInputFieldsSchema,
listMyChatHistoryInputSchema,
readDocumentInputSchema,
refineActivityWindow,
refineSearchWorkspaceInput,
Expand Down Expand Up @@ -75,6 +76,12 @@ export const listMyActivityMcpSchema = listMyActivityInputFieldsSchema
.strict()
.superRefine(refineActivityWindow)

/** list_my_chat_history as the Search MCP presents it: a date without an offset reads as UTC. */
export const listMyChatHistoryMcpSchema = listMyChatHistoryInputSchema.extend({
startDate: mcpDateFilter(listMyChatHistoryInputSchema.shape.startDate),
endDate: mcpDateFilter(listMyChatHistoryInputSchema.shape.endDate),
})

/**
* Previews a search returns when the caller sets no topK. A query across every source shares one
* list among all of them, so it gets more room than a search of one source, a native query, or a
Expand Down
17 changes: 11 additions & 6 deletions apps/sim/lib/api/contracts/mothership-assistant-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -528,24 +528,29 @@ export const searchPeopleInputSchema = z
)

/**
* The caller's own questions to Sim over a window, oldest first. The 92-day window and the page
* bounds are literals so the worker's generated copy stays standalone.
* The caller's own questions to Sim over a window, newest first by default. The 92-day window
* and the page bounds are literals so the worker's generated copy stays standalone.
*/
export const listMyChatHistoryInputSchema = z
.object({
startDate: z
.string()
.datetime({ offset: true })
.optional()
.describe(
'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.'
'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.'
),
endDate: z
.string()
.datetime({ offset: true })
.optional()
.describe(
'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.'
'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.'
),
sortBy: z
.enum(['newest', 'oldest'])
.optional()
.describe('newest (the default) or oldest first.'),
topK: z
.number()
.int()
Expand All @@ -558,7 +563,7 @@ export const listMyChatHistoryInputSchema = z
.min(1)
.max(1024)
.optional()
.describe('nextCursor from the previous page of the same window.'),
.describe('nextCursor from the previous page of the same window and order.'),
includeAnswers: z
.boolean()
.optional()
Expand Down Expand Up @@ -643,7 +648,7 @@ export const assistantToolContracts = [
id: 'list_my_chat_history',
route: 'sim',
description:
'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.',
'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.',
inputSchema: listMyChatHistoryInputSchema,
},
{
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/auth/oauth-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export const OAUTH_SCOPE_DESCRIPTIONS: Record<OAuthScope, string> = {
[OAUTH_API_READ_SCOPE]: 'Read your workspaces, workflows, files, tables, and logs',
[OAUTH_API_WRITE_SCOPE]: 'Read, create, change, run, and delete resources in your workspaces',
[OAUTH_SEARCH_READ_SCOPE]:
'Search and read documents you can access, look up people in your organization, and start private Sim Search conversations',
'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',
}

/**
Expand Down
125 changes: 124 additions & 1 deletion apps/sim/lib/knowledge/application/chat-history.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
copilotChats,
copilotMessages,
member,
mothershipInboxTask,
organization,
permissions,
project,
Expand Down Expand Up @@ -57,13 +58,22 @@ function session(userId: string): SessionPrincipal {
return { kind: 'session', userId, sessionId: generateId() }
}

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

/** Each chat's transcript position, as `persistCopilotChatTurn` numbers saved messages. */
const seqs = new Map<string, number>()
function nextSeq(chatId: string): number {
const seq = (seqs.get(chatId) ?? 0) + 1
seqs.set(chatId, seq)
return seq
}

async function chat(values: Partial<typeof copilotChats.$inferInsert> = {}): Promise<string> {
const id = generateId()
await db.insert(copilotChats).values({
Expand All @@ -87,6 +97,7 @@ async function ask(
messageId: generateId(),
role: 'user',
content: { content },
seq: nextSeq(chatId),
createdAt: new Date(createdAt),
...extra,
})
Expand Down Expand Up @@ -309,6 +320,7 @@ describe('list_my_chat_history', () => {
chatId: id,
messageId: generateId(),
role: 'assistant',
seq: nextSeq(id),
content: {
content: `Two releases shipped <source>{"id":"c1"}</source>. ${'x'.repeat(900)}`,
},
Expand All @@ -321,6 +333,22 @@ describe('list_my_chat_history', () => {
expect((await list()).questions[0]?.answerExcerpt).toBeUndefined()
})

it('never shows hidden thinking cut off by the answer prefix', async () => {
const id = await chat()
await ask(id, 'a long think', '2026-11-02T10:00:00Z')
await db.insert(copilotMessages).values({
chatId: id,
messageId: generateId(),
role: 'assistant',
seq: nextSeq(id),
content: { content: `<thinking>${'private reasoning '.repeat(400)}</thinking>The answer` },
createdAt: new Date('2026-11-02T10:00:30Z'),
})

const [question] = (await list({ includeAnswers: true })).questions
expect(question?.answerExcerpt).toBeUndefined()
})

it("gives an unanswered question no answer, rather than the next question's", async () => {
const id = await chat()
await ask(id, 'stopped question', '2026-11-02T10:00:00Z')
Expand All @@ -329,6 +357,7 @@ describe('list_my_chat_history', () => {
chatId: id,
messageId: generateId(),
role: 'assistant',
seq: nextSeq(id),
content: { content: 'The answer to the deleted question' },
createdAt: new Date('2026-11-02T10:00:30Z'),
})
Expand All @@ -337,6 +366,7 @@ describe('list_my_chat_history', () => {
chatId: id,
messageId: generateId(),
role: 'assistant',
seq: nextSeq(id),
content: { content: 'The answer to the second question' },
createdAt: new Date('2026-11-02T10:01:30Z'),
})
Expand Down Expand Up @@ -400,6 +430,99 @@ describe('list_my_chat_history', () => {
expect(futureEnd.questions.map((q) => q.question)).toContain('recent')
})

it('lists newest first by default, and a cursor only continues the order it came from', async () => {
const id = await chat()
await ask(id, 'earlier', '2026-11-02T10:00:00Z')
await ask(id, 'later', '2026-11-03T10:00:00Z')

const newest = await list({ sortBy: undefined, topK: 1 })
expect(newest.questions.map((q) => q.question)).toEqual(['later'])
expect(
(await list({ sortBy: undefined, cursor: newest.nextCursor })).questions.map(
(q) => q.question
)
).toEqual(['earlier'])
await expect(list({ sortBy: 'oldest', cursor: newest.nextCursor })).rejects.toThrow(
/same sortBy/
)
})

it('continues a page in the window its cursor fixed, whatever dates come with it', async () => {
const id = await chat()
await ask(id, 'first', '2026-11-02T10:00:00Z')
await ask(id, 'second', '2026-11-03T10:00:00Z')

const page = await list({ topK: 1 })
const next = await list({
cursor: page.nextCursor,
startDate: '2026-11-03T12:00:00Z',
endDate: '2026-11-04T00:00:00Z',
})
expect(next.questions.map((q) => q.question)).toEqual(['second'])
})

it('refuses a cursor whose window is longer than a first page may read', async () => {
const forged = Buffer.from(
JSON.stringify([
'oldest',
'2020-01-01T00:00:00.000Z',
'2026-11-08T00:00:00.000Z',
'2026-11-02T10:00:00.000000Z',
generateId(),
])
).toString('base64url')
await expect(list({ cursor: forged })).rejects.toThrow(/nextCursor/)
})

it('finds the answer to a question saved without a transcript seq', async () => {
const id = await chat()
await ask(id, 'unnumbered question', '2026-11-02T10:00:00Z', { seq: null })
await db.insert(copilotMessages).values({
chatId: id,
messageId: generateId(),
role: 'assistant',
content: { content: 'Unnumbered answer' },
createdAt: new Date('2026-11-02T10:00:30Z'),
})

const { questions } = await list({ includeAnswers: true })
expect(questions.map((q) => [q.question, q.answerExcerpt])).toEqual([
['unnumbered question', 'Unnumbered answer'],
])
})

it('reads the 7 days before the end without a startDate, and refuses a startDate in the future', async () => {
const id = await chat()
await ask(id, 'three days ago', new Date(Date.now() - 3 * 86_400_000).toISOString())
await ask(id, 'ten days ago', new Date(Date.now() - 10 * 86_400_000).toISOString())

const lastWeek = await list({ startDate: undefined, endDate: undefined })
expect(lastWeek.questions.map((q) => q.question)).toEqual(['three days ago'])
await expect(
list({ startDate: new Date(Date.now() + 86_400_000).toISOString(), endDate: undefined })
).rejects.toThrow(/startDate is in the future/)
})

it('never lists an inbox email turn run as the caller, nor a forked copy of it', async () => {
const inboxChat = await chat({ organizationId: null, workspaceId: openWorkspaceId })
const emailed = generateId()
await ask(inboxChat, 'an email from someone else', '2026-11-02T10:00:00Z', {
messageId: emailed,
})
await db.insert(mothershipInboxTask).values({
id: generateId(),
workspaceId: openWorkspaceId,
fromEmail: 'stranger@example.test',
subject: 'Request',
chatId: inboxChat,
})
const fork = await chat()
await ask(fork, 'an email from someone else', '2026-11-02T10:00:00Z', { messageId: emailed })
await ask(fork, 'my own follow-up', '2026-11-02T11:00:00Z')

expect((await list()).questions.map((q) => q.question)).toEqual(['my own follow-up'])
})

it('refuses a caller outside the organization and a principal that is not a person', async () => {
await ask(await chat(), 'private', '2026-11-02T10:00:00Z')

Expand Down
Loading
Loading