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
2 changes: 2 additions & 0 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import type * as tags from "../tags.js";
import type * as tasks from "../tasks.js";
import type * as tokens from "../tokens.js";
import type * as toolSources from "../toolSources.js";
import type * as turns from "../turns.js";
import type * as undo from "../undo.js";
import type * as validators from "../validators.js";
import type * as voice from "../voice.js";
Expand Down Expand Up @@ -146,6 +147,7 @@ declare const fullApi: ApiFromModules<{
tasks: typeof tasks;
tokens: typeof tokens;
toolSources: typeof toolSources;
turns: typeof turns;
undo: typeof undo;
validators: typeof validators;
voice: typeof voice;
Expand Down
25 changes: 17 additions & 8 deletions convex/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import { capyAdapter, capyConn, capyConnected } from './adapters/capy';
import { CANVAS } from '../src/shared/canvasAgent';
import { makePick } from './models';
import { withoutToolCalls } from '../src/shared/toolCallText';
import { asRead, endStalled, stalled, startTurn } from './turns';
import { nudgePush } from './push';

/** A model the composer picked: a connected provider's id, or the house model's, and the model on it. */
const chatModel = v.object({ provider: v.string(), model: v.string() });
Expand Down Expand Up @@ -145,18 +147,19 @@ const withCard = (m: Doc<'agentMessages'>, i: number, card: Card) => m.cards.map
/* ---------- what the apps call ---------- */

/**
* The 40 newest chats, each with `working` (its last reply is still going) and `repliedAt` (when its last reply
* finished; none while it works, or when you stopped it), from its last message. The Mac's tabs and History mark a chat
* The 40 newest chats, each with `working` (its last reply is still going), `stalled` (its run ended without finishing it,
* convex/turns.ts) and `repliedAt` (when its last reply finished; none while it works, or when you stopped it), from its
* last message. The Mac's tabs and History mark a chat
* that's working or has a reply you haven't seen from these.
*/
export const chats = userQuery({
args: {},
handler: async (ctx) =>
Promise.all((await ctx.db.query('agentChats').withIndex('by_updated').order('desc').filter((q) => q.neq(q.field('plain'), true)).take(40)).map(async (c) => {
const last = await ctx.db.query('agentMessages').withIndex('by_chat', (q) => q.eq('chatId', c._id)).order('desc').first();
const working = last?.status === 'working';
const repliedAt = last?.role === 'assistant' && !working && !last.stopped ? last.doneAt ?? last.createdAt : undefined;
return { _id: c._id, title: c.title, updatedAt: c.updatedAt, working, ...(repliedAt ? { repliedAt } : {}), ...(c.model ? { model: { provider: c.model.provider, model: c.model.model } } : {}) };
const dead = !!last && (await stalled(ctx, last)), working = last?.status === 'working' && !dead;
const repliedAt = last?.role === 'assistant' && !working && !dead && !last.stopped ? last.doneAt ?? last.createdAt : undefined;
return { _id: c._id, title: c.title, updatedAt: c.updatedAt, working, ...(dead ? { stalled: true } : {}), ...(repliedAt ? { repliedAt } : {}), ...(c.model ? { model: { provider: c.model.provider, model: c.model.model } } : {}) };
})),
});

Expand All @@ -165,7 +168,9 @@ export const messages = userQuery({
handler: async (ctx, { chatId }) => {
const id = ctx.db.normalizeId('agentChats', chatId);
if (!id) return [];
return Promise.all((await ctx.db.query('agentMessages').withIndex('by_chat', (q) => q.eq('chatId', id)).collect()).map(async ({ cards, files, ...m }) => ({
const rows = await ctx.db.query('agentMessages').withIndex('by_chat', (q) => q.eq('chatId', id)).collect();
const read = await Promise.all(rows.map(async (m) => asRead(m, await stalled(ctx, m))));
return Promise.all(read.map(async ({ cards, files, runId: _runId, ...m }) => ({
...m,
cards: cards.map(({ undo, playbooks, links, calls, ...c }) => ({ ...c, undoable: !!(undo?.length || playbooks?.length || links?.length) })),
...(files ? { files: await Promise.all(files.map(async ({ storageId, ...f }) => ({ ...f, url: await ctx.storage.getUrl(storageId) }))) } : {}),
Expand Down Expand Up @@ -197,15 +202,18 @@ export const send = userMutation({
if (chat) {
if ((await ctx.db.get(chat))?.plain) throw new ConvexError('That chat is a plain chat in Agents');
const last = await ctx.db.query('agentMessages').withIndex('by_chat', (q) => q.eq('chatId', chat!)).order('desc').first();
if (last?.status === 'working') throw new ConvexError('yoji Agent is still answering');
if (last?.status === 'working') {
if (!(await stalled(ctx, last))) throw new ConvexError('yoji Agent is still answering');
await endStalled(ctx, last);
}
await ctx.db.patch(chat, { updatedAt: now });
} else {
const pick = model ? await makePick(ctx, model.provider, model.model) : null;
chat = await ctx.db.insert('agentChats', { title: body.replace(/\s+/g, ' ').slice(0, 60), createdAt: now, updatedAt: now, ...(pick ? { model: pick } : {}) });
}
await ctx.db.insert('agentMessages', { chatId: chat, role: 'user', text: body, status: 'done', steps: [], cards: [], ...(context ? { context } : {}), ...(requestId ? { requestId } : {}), createdAt: now });
const reply = await ctx.db.insert('agentMessages', { chatId: chat, role: 'assistant', text: '', status: 'working', steps: [], cards: [], today, timezone, ...(isLang(language) ? { language } : {}), createdAt: now + 1 });
await ctx.scheduler.runAfter(0, internal.agent.run, { messageId: reply });
await startTurn(ctx, reply, internal.agent.run);
return { chatId: chat as string, messageId: reply as string };
},
});
Expand Down Expand Up @@ -510,6 +518,7 @@ export const finish = internalMutation({
const text = withoutToolCalls(rest.text), empty = !text && !!rest.text.trim();
await ctx.db.patch(messageId, { ...rest, ...(empty ? { text: 'I didn’t get an answer back. Try again?', status: 'error' as const } : { text }), doneAt: Date.now() });
await ctx.db.patch(m.chatId, { updatedAt: Date.now() });
if ((await ctx.db.get(m.chatId))?.plain) await nudgePush(ctx);
return null;
},
});
Expand Down
8 changes: 8 additions & 0 deletions convex/agentSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ export const agentTables = {
plain: v.optional(v.boolean()),
/** A plain chat's reasoning effort, from its composer or Settings › Chats' default; none runs at the provider's own. */
reasoning: v.optional(reasoningMode),
/** A plain chat: when you last opened it or sent in it, so a reply that ends after it shows as unread (or failed) in the Agents lists. */
readAt: v.optional(v.number()),
/** A plain chat: the doneAt of the newest reply a notification went out for (push.ts, src/main/notify.ts), so each reply notifies once. */
notifiedAt: v.optional(v.number()),
}).index('by_updated', ['updatedAt']),
agentMessages: defineTable({
chatId: v.id('agentChats'),
Expand All @@ -124,6 +128,10 @@ export const agentTables = {
doneAt: v.optional(v.number()),
/** The user stopped it before it answered. */
stopped: v.optional(v.boolean()),
/** On a reply: its scheduled run (plainChats.run or agent.run), so a reply whose run ended without finishing it counts as stalled (convex/turns.ts). */
runId: v.optional(v.id('_scheduled_functions')),
/** On a reply: it stalled (its run ended without finishing it, or it outlived TURN_LEASE_MS), so it was ended as an error. */
stalled: v.optional(v.boolean()),
/** On a reply: it read text from outside yoji (Inbox, docs, a tool's answer), so later turns ask before outbound tools too. */
untrusted: v.optional(v.boolean()),
/** On a reply: the standing instructions and skills it ran with, for its Applied note. */
Expand Down
22 changes: 16 additions & 6 deletions convex/attention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,31 @@ import { attention, HANDLED_WINDOW, type Attention } from '../src/shared/attenti
import type { QueryCtx } from './_generated/server';
import { canvasRows } from './agents';
import { captainRows } from './capy';
import { plainRows } from './plainChats';
import { userQuery } from './lib';

/** The newest 300 unread, unarchived rows, read through by_unread so read rows cost nothing. */
export const unreadRows = (ctx: QueryCtx) =>
ctx.db.query('inbox').withIndex('by_unread', (q) => q.eq('archived', false).eq('read', false)).order('desc').take(300);

/** Items a notification went out for that you've since read or archived, newest first, from the last day. */
export const handledIds = async (ctx: QueryCtx): Promise<string[]> =>
(await ctx.db.query('inbox').withIndex('by_created', (q) => q.gt('createdAt', Date.now() - HANDLED_WINDOW)).order('desc').collect())
/**
* Items a notification went out for that you've since read or archived, newest first, from the last day, then the
* plain chats you opened since their reply notified (a plain chat's notice carries the chat's id).
*/
export const handledIds = async (ctx: QueryCtx): Promise<string[]> => {
const since = Date.now() - HANDLED_WINDOW;
const inbox = (await ctx.db.query('inbox').withIndex('by_created', (q) => q.gt('createdAt', since)).order('desc').collect())
.filter((i) => i.notifiedAt && (i.read || i.archived))
.map((i) => i._id);
.map((i) => i._id as string);
const chats = (await ctx.db.query('agentChats').withIndex('by_updated', (q) => q.gt('updatedAt', since)).order('desc').filter((q) => q.eq(q.field('plain'), true)).take(60))
.filter((c) => c.notifiedAt && c.readAt && c.readAt >= c.notifiedAt)
.map((c) => c._id as string);
return [...chats, ...inbox];
};

export async function attentionNow(ctx: QueryCtx): Promise<Attention> {
const [inbox, canvas, captains] = await Promise.all([unreadRows(ctx), canvasRows(ctx), captainRows(ctx)]);
return attention(inbox, canvas, captains);
const [inbox, canvas, captains, plain] = await Promise.all([unreadRows(ctx), canvasRows(ctx), captainRows(ctx), plainRows(ctx)]);
return attention(inbox, canvas, captains, plain);
}

/** The counts, and `handled`: notified items since read or archived, whose notifications the apps take down. */
Expand Down
Loading