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
34 changes: 34 additions & 0 deletions services/platform/convex/chat/assistant_tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1688,6 +1688,40 @@ describe('rag_search archive context', () => {
});

describe('rag_search reports a listing as a listing', () => {
it('hands the model a date, not an epoch number, on a task due date', async () => {
// Asking the model to convert epoch milliseconds produced dates weeks off
// on a live deployment. Every timestamp the tool emits is now ISO 8601 UTC,
// matching the `Current time:` line in the system prompt.
const { ctx } = createCtx({
reads: {
[TASKS_SEARCH_FN]: () => ({
page: [
{
_id: 'task_1',
title: 'Verify billing',
status: 'todo',
dueDate: 1_787_124_301_288,
},
],
isDone: true,
continueCursor: '',
listed: false,
}),
},
});
const executor = await makeExecutor(ctx);
const result = (await executor.execute({
id: 'c1',
name: 'rag_search',
input: { action: 'search', query: 'billing' },
})) as Record<string, unknown>;

const entries = result.results as Array<{ data?: Record<string, unknown> }>;
const due = entries.find((entry) => entry.data?.dueDate)?.data?.dueDate;
expect(due).toBe('2026-08-19T07:25:01.288Z');
expect(typeof due).toBe('string');
});

it('says the tasks source listed rather than matched', async () => {
const { ctx } = createCtx({
reads: {
Expand Down
13 changes: 8 additions & 5 deletions services/platform/convex/chat/assistant_tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
knowledgeScopeAllows,
type KnowledgeAccessScope,
} from '../../lib/knowledge/types';
import { modelTimestamp } from '../../lib/shared/model-timestamp';
import { internal } from '../_generated/api';
import type { Doc } from '../_generated/dataModel';
import type { ActionCtx } from '../_generated/server';
Expand Down Expand Up @@ -184,7 +185,9 @@ function taskResultEntry(
...(task.priority ? { priority: task.priority } : {}),
...(task.assigneeType ? { assigneeType: task.assigneeType } : {}),
...(task.projectId ? { projectId: String(task.projectId) } : {}),
...(task.dueDate ? { dueDate: task.dueDate } : {}),
...(modelTimestamp(task.dueDate) !== undefined
? { dueDate: modelTimestamp(task.dueDate) }
: {}),
...archiveFlags({
archivedAt: task.archivedAt,
projectId: task.projectId != null ? String(task.projectId) : null,
Expand Down Expand Up @@ -319,8 +322,8 @@ function conversationResultEntry(conversation: {
? {}
: // Unassigned is a real state an admin acts on, not missing data.
{ unassigned: true }),
...(conversation.lastMessageAt
? { lastMessageAt: conversation.lastMessageAt }
...(modelTimestamp(conversation.lastMessageAt) !== undefined
? { lastMessageAt: modelTimestamp(conversation.lastMessageAt) }
: {}),
},
};
Expand Down Expand Up @@ -1488,7 +1491,7 @@ export function createChatToolExecutor(
conversationId: attachment.conversationId,
contentType: attachment.contentType,
sizeBytes: attachment.size,
receivedAt: attachment.receivedAt,
receivedAt: modelTimestamp(attachment.receivedAt),
// A received-but-unindexed attachment cannot be fetched for its
// text. Saying so beats implying it is readable.
indexed: attachment.indexed,
Expand Down Expand Up @@ -1552,7 +1555,7 @@ export function createChatToolExecutor(
data: {
...(doc.extension !== null ? { extension: doc.extension } : {}),
...(doc.folderPath !== null ? { folderPath: doc.folderPath } : {}),
createdAt: doc.createdAt,
createdAt: modelTimestamp(doc.createdAt),
},
}));
// Hub and team files are the whole catalog only for project-less asks —
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import { ConvexError } from 'convex/values';

import { extractExtension } from '../../../lib/shared/file-types';
import { modelTimestamp } from '../../../lib/shared/model-timestamp';
import { internal } from '../../_generated/api';
import type { Doc, Id } from '../../_generated/dataModel';
import type { ActionCtx } from '../../_generated/server';
Expand Down Expand Up @@ -151,8 +152,11 @@ function compactTask(task: Doc<'tasks'>): Record<string, unknown> {
? { externalUrl: task.externalUrl }
: {}),
commentCount: task.commentCount ?? 0,
createdAt: task.createdAt,
updatedAt: task.updatedAt,
// ISO 8601 UTC, not epoch milliseconds: the agent reading this result gets
// the same date format the chat tools answer with, and the same format its
// own `Current time:` directive carries.
createdAt: modelTimestamp(task.createdAt),
updatedAt: modelTimestamp(task.updatedAt),
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1056,6 +1056,41 @@ describe('dispatchWorkspaceTool — write tools (task family + document_create)'
expect(qArgs.projectIds).toEqual(['proj_1', 'proj_2']);
});

it('task_find hands the agent ISO dates, not epoch milliseconds', async () => {
// The same rendering the chat tools use. An agent asked to reason about
// "which of these is stale" cannot do epoch arithmetic reliably, so the
// date arrives already in the format its `Current time:` directive uses.
const { dispatch } = await getActions();
const { ctx } = createCtx({
readQuery: vi.fn((ref: unknown) =>
fnName(ref).includes('listTasksForAgent')
? Promise.resolve([
{
_id: 'task_1',
number: 7,
title: 'Chase the invoice',
status: 'todo',
projectId: 'proj_1',
commentCount: 0,
createdAt: 1_787_124_301_288,
updatedAt: 1_787_210_701_288,
},
])
: Promise.resolve(null),
),
});
const result = await dispatch(ctx, {
...BASE,
tool: 'task_find',
callArgs: {},
});
expect(result.status).toBe('ok');
const [task] = (result.output as { tasks: Record<string, unknown>[] })
.tasks;
expect(task?.createdAt).toBe('2026-08-19T07:25:01.288Z');
expect(task?.updatedAt).toBe('2026-08-20T07:25:01.288Z');
});

it('task_get on a multi-bound org run refuses a task outside the bound set', async () => {
const contextRead = vi.fn<(...a: unknown[]) => Promise<unknown>>(() =>
Promise.resolve({ task: {}, project: {}, comments: [] }),
Expand Down
34 changes: 34 additions & 0 deletions services/platform/lib/shared/model-timestamp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// The one date rendering both agent lanes answer with. A tool result used to
// carry raw epoch milliseconds; on a live deployment the model rendered three
// attachment dates uniformly four weeks late, and the same document as two
// different creation dates on two turns. The sort order was right both times —
// only the arithmetic was wrong.

import { describe, expect, it } from 'vitest';

import { modelTimestamp } from './model-timestamp';

describe('modelTimestamp — dates the model does not have to compute', () => {
it('renders a stored timestamp as ISO 8601 UTC', () => {
// 2026-08-19T07:25:01.288Z — the arrival time of a real attachment.
expect(modelTimestamp(1_787_124_301_288)).toBe('2026-08-19T07:25:01.288Z');
});

it('matches the format the system prompt already uses for the current time', () => {
// `Current time: <ISO> (UTC)` is in the runtime directives, so a comparison
// is between like and like rather than between prose and a number.
const rendered = modelTimestamp(Date.UTC(2026, 7, 19, 7, 25));
expect(rendered).toBe(new Date(Date.UTC(2026, 7, 19, 7, 25)).toISOString());
});

it('omits a value that is not a usable timestamp', () => {
// One bad stored number degrades to a missing field, never a failed turn.
expect(modelTimestamp(undefined)).toBeUndefined();
expect(modelTimestamp(Number.NaN)).toBeUndefined();
expect(modelTimestamp(Number.POSITIVE_INFINITY)).toBeUndefined();
});

it('keeps the epoch itself, which is a real value and not a missing one', () => {
expect(modelTimestamp(0)).toBe('1970-01-01T00:00:00.000Z');
});
});
29 changes: 29 additions & 0 deletions services/platform/lib/shared/model-timestamp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* One rendering of a stored timestamp for anything a language model reads.
*
* Both agent lanes answer tool calls with rows straight out of Convex, where
* every timestamp is epoch milliseconds. Handing that number to a model and
* leaving it to work out a calendar date does not survive contact: on one
* deployment three attachment dates came back uniformly four weeks late, and
* the same document rendered two different creation dates on two turns. The
* ordering was right both times; only the arithmetic was wrong, which is
* exactly the kind of work not to hand a language model.
*
* Lives here rather than beside either lane's tool definitions because the
* chat tools and the sandbox workspace tools both need it, and a second copy
* of a formatter is how two lanes start disagreeing about what a date is.
*/

/**
* A stored timestamp as the model should see it: ISO 8601 UTC, matching the
* `Current time:` line the system prompt already carries, so a comparison is
* between like and like.
*
* Returns `undefined` for a value that is not a finite timestamp, so one bad
* stored number degrades to an omitted field rather than a failed turn.
*/
export function modelTimestamp(ms: number | undefined): string | undefined {
if (ms === undefined || !Number.isFinite(ms)) return undefined;
const iso = new Date(ms).toISOString();
return iso === 'Invalid Date' ? undefined : iso;
}
Loading