From 8cd1097f06b2b380daee1e853f16a90f920ed0f0 Mon Sep 17 00:00:00 2001 From: yoji export Date: Mon, 30 Nov 2026 23:07:15 +0000 Subject: [PATCH] Export yoji from 5c52f0566012 --- convex/_generated/api.d.ts | 2 + convex/agent.ts | 25 +++- convex/agentSchema.ts | 8 + convex/attention.ts | 22 ++- convex/chatTurns.test.ts | 196 +++++++++++++++++++++++++ convex/plainChatStatus.test.ts | 107 ++++++++++++++ convex/plainChats.ts | 88 +++++++---- convex/providers/models.ts | 37 ++++- convex/push.ts | 19 ++- convex/turns.ts | 54 +++++++ docs/agents.md | 4 +- package.json | 2 +- src/main/data.ts | 13 +- src/main/index.ts | 10 +- src/main/notify.ts | 48 +++++- src/renderer/src/Agents.tsx | 23 ++- src/renderer/src/PlainChat.tsx | 4 +- src/renderer/src/layers/Settings.tsx | 4 +- src/shared/agentClient.ts | 2 + src/shared/agentsPanel.ts | 28 +++- src/shared/attention.test.ts | 2 +- src/shared/attention.ts | 15 +- src/shared/i18n/locales/de/notices.ts | 2 + src/shared/i18n/locales/de/settings.ts | 1 + src/shared/i18n/locales/en/notices.ts | 2 + src/shared/i18n/locales/en/settings.ts | 1 + src/shared/i18n/locales/es/notices.ts | 2 + src/shared/i18n/locales/es/settings.ts | 1 + src/shared/i18n/locales/fr/notices.ts | 2 + src/shared/i18n/locales/fr/settings.ts | 1 + src/shared/i18n/locales/ja/notices.ts | 2 + src/shared/i18n/locales/ja/settings.ts | 1 + src/shared/inboxNotice.ts | 12 ++ src/shared/notifySources.ts | 4 +- src/shared/plainChatState.test.ts | 49 +++++++ src/shared/toolCallText.test.ts | 32 ++++ src/shared/toolCallText.ts | 33 ++++- src/shared/turnLease.test.ts | 15 ++ src/shared/turnLease.ts | 7 + src/shared/webSearch.test.ts | 25 +++- src/shared/webSearch.ts | 4 + 41 files changed, 824 insertions(+), 85 deletions(-) create mode 100644 convex/chatTurns.test.ts create mode 100644 convex/plainChatStatus.test.ts create mode 100644 convex/turns.ts create mode 100644 src/shared/plainChatState.test.ts create mode 100644 src/shared/turnLease.test.ts create mode 100644 src/shared/turnLease.ts diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index dac2444..0678a3c 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -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"; @@ -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; diff --git a/convex/agent.ts b/convex/agent.ts index 7e9e0e9..9f3a62e 100644 --- a/convex/agent.ts +++ b/convex/agent.ts @@ -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() }); @@ -145,8 +147,9 @@ 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({ @@ -154,9 +157,9 @@ export const chats = userQuery({ 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 } } : {}) }; })), }); @@ -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) }))) } : {}), @@ -197,7 +202,10 @@ 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; @@ -205,7 +213,7 @@ export const send = userMutation({ } 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 }; }, }); @@ -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; }, }); diff --git a/convex/agentSchema.ts b/convex/agentSchema.ts index 39a691b..df58763 100644 --- a/convex/agentSchema.ts +++ b/convex/agentSchema.ts @@ -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'), @@ -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. */ diff --git a/convex/attention.ts b/convex/attention.ts index 0be6ef0..43d598c 100644 --- a/convex/attention.ts +++ b/convex/attention.ts @@ -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 => - (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 => { + 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 { - 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. */ diff --git a/convex/chatTurns.test.ts b/convex/chatTurns.test.ts new file mode 100644 index 0000000..3fce92f --- /dev/null +++ b/convex/chatTurns.test.ts @@ -0,0 +1,196 @@ +// @vitest-environment edge-runtime +/// +import { convexTest } from 'convex-test'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { api } from './_generated/api'; +import type { Id } from './_generated/dataModel'; +import schema from './schema'; +import { canvasAgent } from './canvasAgent.fixture'; +import { sealedBefore } from './sealed.fixture'; +import { STALLED_TEXT } from './turns'; +import { CANVAS, CANVAS_NAME } from '../src/shared/canvasAgent'; +import { TURN_LEASE_MS } from '../src/shared/turnLease'; + +// A reply's turn in plain Chats and in yoji Agent, on the house model (text only), with the model and Firecrawl mocked: +// the turn runs on the server whatever the app does, a run that ends without finishing its reply reads as stalled and +// never blocks the next message, the lease check ends it in the database, and a reply cut off partway through a tag +// never keeps the fragment. On Nov 30 a plain chat saved "query>…, a form the text protocol didn't run. + +const overlay = vi.hoisted(() => ({ replies: [] as string[], messages: [] as { role: string; content: string }[][] })); +vi.mock('@private/convex', () => ({ default: { model: { id: 'brain', name: 'Brain', model: 'house', generate: async (_token: string, messages: { role: string; content: string }[]) => (overlay.messages.push(messages), { text: overlay.replies.shift() ?? '{"reply": "From the brain."}', claude: true, finish: 'stop', cost: null }) } } })); + +const modules = import.meta.glob('./**/*.ts'); +const ENC = btoa(String.fromCharCode(...new Uint8Array(32).fill(5))); +const Q = 'how much do different rogue weapons and armor cost in honor points in wow forever'; +const PAGE = 'https://wowhead.com/forever/guide/pvp-overview-ranking-rewards'; +const ANSWER = 'Rank 14 weapons cost 26,950 honor in WoW Forever ([wowhead.com](' + PAGE + ')).'; +/** The form Claude Sonnet 5.5 wrote its search in on the house route (live, Nov 30), cut off after "query>WoW Forever rogue PvP weapons armor honor point cost\n new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +beforeEach(() => { + firecrawl = []; + overlay.replies = []; + overlay.messages = []; + vi.stubEnv('YOJI_ENCRYPTION_KEY', ENC); + vi.stubEnv('FIRECRAWL_API_KEY', 'fc-env'); + vi.stubGlobal('fetch', vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input), body = init?.body ? JSON.parse(String(init.body)) : undefined; + if (!url.startsWith('https://api.firecrawl.dev/')) return json({}, 404); + firecrawl.push({ url, body }); + if (url.endsWith('/search')) return json({ success: true, data: { web: [{ url: PAGE, title: 'PvP ranking rewards', description: 'Honor costs per rank.' }] } }); + return json({ success: true, data: { markdown: 'Rank 14 weapons: 26,950 honor.', metadata: { title: 'PvP rewards', sourceURL: PAGE, statusCode: 200 } } }); + })); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.useRealTimers(); +}); + +async function setup() { + const t = convexTest(schema, modules); + await t.mutation(api.data.init, {}); + await t.mutation(api.tasks.create, { task: { status: 'todo', priority: 0, tags: [], length: 60, notes: '', link: '', title: 'Orbit launch' }, day: '2026-10-20' }); + await t.run(async (ctx) => ctx.db.insert('connections', { provider: CANVAS, agent: canvasAgent(), accountId: 'u1', label: CANVAS_NAME, status: 'active', accessToken: await sealedBefore('agent-token'), createdAt: 1 })); + return t; +} + +type T = Awaited>; +type Kind = 'plain' | 'agent'; +const send = (t: T, kind: Kind, text: string, chatId?: string) => + kind === 'plain' ? t.mutation(api.plainChats.send, { text, today: '2026-11-30', timezone: 'America/New_York', ...(chatId ? { chatId } : {}) }) : t.mutation(api.agent.send, { text, today: '2026-11-30', timezone: 'America/New_York', ...(chatId ? { chatId } : {}) }); +const messages = (t: T, chatId: string) => t.query(api.agent.messages, { chatId }); +const row = (t: T, id: string) => t.run((ctx) => ctx.db.get(id as Id<'agentMessages'>)); +const listed = async (t: T, kind: Kind, chatId: string) => (kind === 'plain' ? await t.query(api.plainChats.list, {}) : await t.query(api.agent.chats, {})).find((c) => c._id === chatId)!; +/** Kills a reply's run before it starts, as a deploy or a crash outside its own error handling would. */ +const killRun = async (t: T, id: string) => { + const r = await row(t, id); + await t.run((ctx) => ctx.scheduler.cancel(r!.runId!)); +}; +const runAll = (t: T) => t.finishAllScheduledFunctions(vi.runAllTimers); + +for (const kind of ['plain', 'agent'] as const) { + const name = kind === 'plain' ? 'plain Chats' : 'yoji Agent'; + const answer = kind === 'plain' ? 'Hi there.' : '{"reply": "Hi there."}'; + + describe(name + ': a turn and the app', () => { + it('runs on the server: the app leaving the chat mid-reply (nothing subscribed, nothing sent) never stops it, and the next message goes through', async () => { + const t = await setup(); + vi.useFakeTimers(); + overlay.replies = [answer, answer]; + const first = await send(t, kind, 'hello'); + expect((await row(t, first.messageId))!.runId).toBeDefined(); + await runAll(t); + expect(await row(t, first.messageId)).toMatchObject({ status: 'done', text: 'Hi there.' }); + const next = await send(t, kind, 'and again', first.chatId); + await runAll(t); + expect(await row(t, next.messageId)).toMatchObject({ status: 'done', text: 'Hi there.' }); + expect((await listed(t, kind, first.chatId)).working).toBe(false); + }); + + it('a reply whose run is still going inside its lease keeps the chat busy', async () => { + const t = await setup(); + vi.useFakeTimers(); + const first = await send(t, kind, 'hello'); + expect((await messages(t, first.chatId)).at(-1)).toMatchObject({ status: 'working' }); + expect(await listed(t, kind, first.chatId)).toMatchObject({ working: true }); + expect((await listed(t, kind, first.chatId)).stalled).toBeUndefined(); + await expect(send(t, kind, 'hello?', first.chatId)).rejects.toThrow(/still answering/i); + }); + + it('a run that ended without finishing its reply reads as stalled at once, and the next message ends it and gets its own answer', async () => { + const t = await setup(); + vi.useFakeTimers(); + const first = await send(t, kind, Q); + await killRun(t, first.messageId); + const shown = (await messages(t, first.chatId)).at(-1)!; + expect(shown).toMatchObject({ _id: first.messageId, status: 'error', stalled: true, text: STALLED_TEXT }); + expect(shown).not.toHaveProperty('runId'); + expect(await listed(t, kind, first.chatId)).toMatchObject({ working: false, stalled: true }); + expect((await row(t, first.messageId))!.status).toBe('working'); + overlay.replies = [answer]; + const next = await send(t, kind, 'hello', first.chatId); + expect(await row(t, first.messageId)).toMatchObject({ status: 'error', stalled: true, text: STALLED_TEXT, doneAt: expect.any(Number) }); + await runAll(t); + expect(await row(t, next.messageId)).toMatchObject({ status: 'done', text: 'Hi there.' }); + expect((await listed(t, kind, first.chatId)).stalled).toBeUndefined(); + }); + + it('the lease check ends a stalled reply in the database TURN_LEASE_MS after it started, and leaves a finished one alone', async () => { + const t = await setup(); + vi.useFakeTimers(); + const start = Date.now(); + const dead = await send(t, kind, Q); + await killRun(t, dead.messageId); + await runAll(t); + const ended = (await row(t, dead.messageId))!; + expect(ended).toMatchObject({ status: 'error', stalled: true, text: STALLED_TEXT }); + expect(ended.doneAt! - start).toBeGreaterThanOrEqual(TURN_LEASE_MS); + overlay.replies = [answer]; + const fine = await send(t, kind, 'hello', dead.chatId); + await runAll(t); + expect(await row(t, fine.messageId)).toMatchObject({ status: 'done', text: 'Hi there.' }); + expect((await row(t, fine.messageId))!.stalled).toBeUndefined(); + }); + }); +} + +describe('plain Chats: a reply cut off partway through a tag', () => { + it('house route: runs a search the model wrote as bare text in an invoke, and never saves the cut-off " { + const t = await setup(); + vi.useFakeTimers(); + overlay.replies = [BARE_CUT, ANSWER]; + const s = await send(t, 'plain', Q); + await runAll(t); + expect(firecrawl.map((c) => c.body.query)).toEqual(['WoW Forever rogue PvP weapons armor honor point cost']); + expect(await row(t, s.messageId)).toMatchObject({ status: 'done', text: ANSWER, steps: ['Searched the web for “WoW Forever rogue PvP weapons armor honor point cost”'] }); + }); + + it('house route: a reply that only tried to call, in a form that can’t run, is told the form once and goes again', async () => { + const t = await setup(); + vi.useFakeTimers(); + overlay.replies = ['undefined\nrogue honor costs', ANSWER]; + const s = await send(t, 'plain', Q); + await runAll(t); + expect(overlay.messages[1]!.at(-1)!.content).toContain('wasn’t in the form asked for'); + expect(overlay.messages[1]!.at(-1)!.content).toContain('query'); + expect(firecrawl.map((c) => c.body.query)).toEqual(['rogue honor costs']); + expect(await row(t, s.messageId)).toMatchObject({ status: 'done', text: ANSWER }); + }); + + it('an answer that stops partway through a tag is saved without the fragment', async () => { + const t = await setup(); + vi.useFakeTimers(); + for (const cut of ['\nmore on rank 14', '\n\nrank']) { + overlay.replies = [ANSWER + cut]; + const s = await send(t, 'plain', Q); + await runAll(t); + expect(await row(t, s.messageId)).toMatchObject({ status: 'done', text: ANSWER }); + } + }); + + it('a reply that was nothing but a cut-off tag says it got no answer instead of showing " { + const t = await setup(); + vi.useFakeTimers(); + overlay.replies = [' { + it('is saved without the fragment', async () => { + const t = await setup(); + vi.useFakeTimers(); + overlay.replies = ['{"reply": "Orbit launch is on Oct 20.\\n\\n +// A plain chat's status in Agents, like an agent chat's: working while its reply runs, unread once a reply finishes +// after you last opened it, failed when that reply errors, and both clear when you open the chat (plainChats.read). +// The counters count it, and a finished or failed reply pushes once, then comes down once you open the chat. +import { convexTest } from 'convex-test'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { api, internal } from './_generated/api'; +import type { Id } from './_generated/dataModel'; +import schema from './schema'; +import { plainChatState } from '../src/shared/agentsPanel'; + +const modules = import.meta.glob('./**/*.ts'); +const NOW = Date.parse('2026-11-30T22:00:00Z'); + +beforeEach(() => { + vi.useFakeTimers({ now: NOW, toFake: ['Date'] }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +type T = ReturnType; + +/** A plain chat with one working reply, sent at `readAt`; null is a chat from before yoji kept read state. */ +async function turn(t: T, title: string, readAt: number | null = NOW - 5_000): Promise<{ chat: Id<'agentChats'>; reply: Id<'agentMessages'> }> { + return t.run(async (ctx) => { + const chat = await ctx.db.insert('agentChats', { title, createdAt: NOW - 10_000, updatedAt: NOW - 5_000, plain: true, ...(readAt !== null ? { readAt } : {}) }); + await ctx.db.insert('agentMessages', { chatId: chat, role: 'user', text: 'How much is tier 1?', status: 'done', steps: [], cards: [], createdAt: NOW - 5_000 }); + const reply = await ctx.db.insert('agentMessages', { chatId: chat, role: 'assistant', text: '', status: 'working', steps: [], cards: [], createdAt: NOW - 4_999 }); + return { chat, reply }; + }); +} + +const row = async (t: T, chat: Id<'agentChats'>) => (await t.query(api.plainChats.list, {})).find((c) => c._id === chat)!; +const later = (ms: number) => vi.setSystemTime(Date.now() + ms); + +describe('plain chat status', () => { + it('is working while its reply runs, unread once it finishes, and read once you open it', async () => { + const t = convexTest(schema, modules); + const { chat, reply } = await turn(t, 'Rogue armor'); + expect(plainChatState(await row(t, chat))).toEqual({ state: 'working', unread: false }); + later(3_000); + await t.mutation(internal.agent.finish, { messageId: reply, text: 'Tier 1 costs 1,000 honor.\n\nMore below.', status: 'done' }); + const done = await row(t, chat); + expect(done).toMatchObject({ working: false, repliedAt: NOW + 3_000, readAt: NOW - 5_000, line: 'Tier 1 costs 1,000 honor.' }); + expect(plainChatState(done)).toEqual({ state: 'ready', unread: true }); + expect(await t.query(api.attention.counts, {})).toMatchObject({ chats: 1, agents: 1, badge: 1 }); + later(1_000); + await t.mutation(api.plainChats.read, { chatId: chat }); + expect(plainChatState(await row(t, chat))).toEqual({ state: 'ready', unread: false }); + expect(await t.query(api.attention.counts, {})).toMatchObject({ chats: 0, agents: 0, badge: 0 }); + }); + + it('shows a reply that errored as failed until you open the chat', async () => { + const t = convexTest(schema, modules); + const { chat, reply } = await turn(t, 'Web search'); + later(2_000); + await t.mutation(internal.agent.finish, { messageId: reply, text: 'The provider timed out.', status: 'error' }); + expect(plainChatState(await row(t, chat))).toEqual({ state: 'needs', need: 'failed', unread: false }); + expect(await t.query(api.attention.counts, {})).toMatchObject({ chats: 1 }); + later(1_000); + await t.mutation(api.plainChats.read, { chatId: chat }); + expect(plainChatState(await row(t, chat))).toEqual({ state: 'ready', unread: false }); + }); + + it('keeps chats from before read state existed quiet, and marks a chat read when you send in it', async () => { + const t = convexTest(schema, modules); + const { chat, reply } = await turn(t, 'Old chat', null); + later(2_000); + await t.mutation(internal.agent.finish, { messageId: reply, text: 'Done.', status: 'done' }); + expect(plainChatState(await row(t, chat))).toEqual({ state: 'ready', unread: false }); + later(1_000); + vi.useFakeTimers({ now: Date.now() }); + await t.mutation(api.plainChats.send, { chatId: chat, text: 'And tier 2?', today: '2026-11-30', timezone: 'America/New_York' }); + expect((await row(t, chat)).readAt).toBe(NOW + 3_000); + await t.finishAllScheduledFunctions(vi.runAllTimers); + }); + + it('pushes a finished reply once, and counts it handled once you open the chat', async () => { + const t = convexTest(schema, modules); + await t.run((ctx) => ctx.db.insert('pushTokens', { token: 'ExpoPushToken[x]', createdAt: NOW, badge: 0, handled: '' })); + const { chat, reply } = await turn(t, 'Rogue armor'); + later(2_000); + await t.mutation(internal.agent.finish, { messageId: reply, text: 'Tier 1 costs 1,000 honor.', status: 'done' }); + const first = await t.mutation(internal.push.claim, {}); + expect(first.sends.flatMap((s) => s.text)).toEqual([{ id: chat, title: 'Chat replied · Rogue armor', body: 'Tier 1 costs 1,000 honor.', chat: `plain:${chat}` }]); + expect(first.badge).toBe(1); + expect((await t.mutation(internal.push.claim, {})).sends).toEqual([]); + later(1_000); + await t.mutation(api.plainChats.read, { chatId: chat }); + expect(await t.mutation(internal.push.claim, {})).toMatchObject({ badge: 0, handled: [chat], sends: [] }); + }); + + it('stays quiet when Chats is off under Notify me about', async () => { + const t = convexTest(schema, modules); + await t.run(async (ctx) => { + await ctx.db.insert('pushTokens', { token: 'ExpoPushToken[x]', createdAt: NOW, badge: 0, handled: '' }); + await ctx.db.insert('prefs', { name: 'notifyOff', value: 'chats' } as never); + }); + const { reply } = await turn(t, 'Rogue armor'); + later(2_000); + await t.mutation(internal.agent.finish, { messageId: reply, text: 'Tier 1.', status: 'done' }); + expect((await t.mutation(internal.push.claim, {})).sends).toEqual([]); + }); +}); diff --git a/convex/plainChats.ts b/convex/plainChats.ts index 7d02aae..d7bc71e 100644 --- a/convex/plainChats.ts +++ b/convex/plainChats.ts @@ -9,11 +9,13 @@ // first, and each reply sends the chat's newest ones again within CHAT_FILES_MAX. import { ConvexError, v } from 'convex/values'; import { internal } from './_generated/api'; -import { internalAction, internalQuery } from './_generated/server'; +import { internalAction, internalQuery, type QueryCtx } from './_generated/server'; +import { nudgePush } from './push'; import type { Doc } from './_generated/dataModel'; import { generate, type ChatTurn } from './ai'; import { webTools } from './webSearch'; -import { webOffPrompt, webOnPrompt } from '../src/shared/webSearch'; +import { chatReply, webOffPrompt, webOnPrompt } from '../src/shared/webSearch'; +import { endStalled, stalled, startTurn } from './turns'; import { reasoningMode } from './integrationsSchema'; import { userMutation, userQuery } from './lib'; import { chatRuns, defaultReasoning, makePick, type AgentPick } from './models'; @@ -28,16 +30,41 @@ const HISTORY = 40; export const system = (today: string, timezone: string, web: string) => `You are a helpful assistant. Today is ${today} (${timezone}). Answer in clear, short Markdown. This is a plain chat: you can't see or change anything in the person's apps, so if they ask about their own tasks, calendar or inbox, say that yoji Agent (⌘J) can help with those. ${web}`; -/** The 60 newest plain chats, each with `working` while its last reply is going, `repliedAt` once it finished, its model and its effort. */ +/** The newest reply's first line, as the Agents rows and a notification show it. */ +const firstLine = (text: string) => (text.split('\n').find((l) => l.trim()) ?? '').trim().slice(0, 160); + +/** + * The 60 newest plain chats, each with `working` while its last reply is going, `stalled` when that reply's run ended + * without finishing it and the server hasn't ended it yet (convex/turns.ts; `working` is false then), `repliedAt` once it + * finished and `failed` when that was an error, `readAt` (src/shared/agentsPanel.ts plainChatState), its newest reply's first line, + * its model and its effort. The list, the counters (attention.ts) and the pushes (push.ts) all read it. + */ +export async function plainRows(ctx: QueryCtx) { + return Promise.all((await ctx.db.query('agentChats').withIndex('by_updated').order('desc').filter((q) => q.eq(q.field('plain'), true)).take(60)).map(async (c) => { + const last = await ctx.db.query('agentMessages').withIndex('by_chat', (q) => q.eq('chatId', c._id)).order('desc').first(); + const dead = !!last && (await stalled(ctx, last)), working = last?.status === 'working' && !dead; + const replied = last?.role === 'assistant' && !working && !dead ? last : undefined; + const repliedAt = replied ? replied.doneAt ?? replied.createdAt : undefined; + const line = replied ? firstLine(replied.text) : ''; + return { _id: c._id, title: c.title, updatedAt: c.updatedAt, working, ...(dead ? { stalled: true } : {}), ...(repliedAt ? { repliedAt } : {}), ...(replied?.status === 'error' ? { failed: true } : {}), ...(c.readAt ? { readAt: c.readAt } : {}), ...(line ? { line } : {}), ...(c.model ? { model: { provider: c.model.provider, model: c.model.model } } : {}), ...(c.reasoning ? { reasoning: c.reasoning } : {}) }; + })); +} + export const list = userQuery({ args: {}, - handler: async (ctx) => - Promise.all((await ctx.db.query('agentChats').withIndex('by_updated').order('desc').filter((q) => q.eq(q.field('plain'), true)).take(60)).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.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 } } : {}), ...(c.reasoning ? { reasoning: c.reasoning } : {}) }; - })), + handler: async (ctx) => plainRows(ctx), +}); + +/** Marks a plain chat read: opening it clears its unread dot or failed badge on every device, and takes its notification down. */ +export const read = userMutation({ + args: { chatId: v.string() }, + handler: async (ctx, { chatId }) => { + const id = ctx.db.normalizeId('agentChats', chatId), row = id && (await ctx.db.get(id)); + if (!id || !row?.plain) return null; + await ctx.db.patch(id, { readAt: Date.now() }); + await nudgePush(ctx); + return null; + }, }); /** A one-time URL the app POSTs an attachment to; its answer's storageId goes with send. */ @@ -85,15 +112,18 @@ export const send = userMutation({ } if (chat) { 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('Still answering'); - await ctx.db.patch(chat, { updatedAt: now, ...(reasoning ? { reasoning } : {}) }); + if (last?.status === 'working') { + if (!(await stalled(ctx, last))) throw new ConvexError('Still answering'); + await endStalled(ctx, last); + } + await ctx.db.patch(chat, { updatedAt: now, readAt: now, ...(reasoning ? { reasoning } : {}) }); } else { const effort = reasoning ?? (await defaultReasoning(ctx)); - chat = await ctx.db.insert('agentChats', { title: (body || files[0]!.name).replace(/\s+/g, ' ').slice(0, 60), createdAt: now, updatedAt: now, plain: true, ...(pick ? { model: pick } : {}), ...(effort ? { reasoning: effort } : {}) }); + chat = await ctx.db.insert('agentChats', { title: (body || files[0]!.name).replace(/\s+/g, ' ').slice(0, 60), createdAt: now, updatedAt: now, readAt: now, plain: true, ...(pick ? { model: pick } : {}), ...(effort ? { reasoning: effort } : {}) }); } await ctx.db.insert('agentMessages', { chatId: chat, role: 'user', text: body, status: 'done', steps: [], cards: [], ...(attached.length ? { files: attached } : {}), ...(requestId ? { requestId } : {}), createdAt: now }); const reply = await ctx.db.insert('agentMessages', { chatId: chat, role: 'assistant', text: '', status: 'working', steps: [], cards: [], today, timezone, createdAt: now + 1 }); - await ctx.scheduler.runAfter(0, internal.plainChats.run, { messageId: reply }); + await startTurn(ctx, reply, internal.plainChats.run); return { chatId: chat as string, messageId: reply as string }; }, }); @@ -132,27 +162,27 @@ export const run = internalAction({ handler: async (ctx, { messageId }) => { const t = await ctx.runQuery(internal.plainChats.turn, { messageId }); if (!t) return; - let room = CHAT_FILES_MAX; - const sent = new Set(); - for (const m of [...t.before].reverse()) for (const f of m.files) if (f.bytes <= room) (room -= f.bytes), sent.add(f.storageId); - const turns = await Promise.all(t.before.map(async (m): Promise => { - const files: TurnFile[] = [], left: string[] = []; - for (const f of m.files) { - const blob = sent.has(f.storageId) ? await ctx.storage.get(f.storageId) : null; - if (blob) files.push({ type: f.type, name: f.name, data: base64(await blob.arrayBuffer()) }); - else left.push(f.name); - } - const content = [m.text, left.length ? `(Attached ${left.join(', ')} earlier, not sent again with this message.)` : ''].filter(Boolean).join('\n\n'); - return { role: m.role, content, ...(files.length ? { files } : {}) }; - })); const end = (text: string, status: 'done' | 'error', sources: { kind: 'url'; id: string; label: string }[] = []) => ctx.runMutation(internal.agent.finish, { messageId, text, status, ...(sources.length ? { sources } : {}) }); try { + let room = CHAT_FILES_MAX; + const sent = new Set(); + for (const m of [...t.before].reverse()) for (const f of m.files) if (f.bytes <= room) (room -= f.bytes), sent.add(f.storageId); + const turns = await Promise.all(t.before.map(async (m): Promise => { + const files: TurnFile[] = [], left: string[] = []; + for (const f of m.files) { + const blob = sent.has(f.storageId) ? await ctx.storage.get(f.storageId) : null; + if (blob) files.push({ type: f.type, name: f.name, data: base64(await blob.arrayBuffer()) }); + else left.push(f.name); + } + const content = [m.text, left.length ? `(Attached ${left.join(', ')} earlier, not sent again with this message.)` : ''].filter(Boolean).join('\n\n'); + return { role: m.role, content, ...(files.length ? { files } : {}) }; + })); const web = await webTools(ctx, messageId); const messages: ChatTurn[] = [{ role: 'system', content: system(t.today, t.timezone, 'kit' in web ? webOnPrompt(t.today) : webOffPrompt(web.off)) }, ...turns]; const r = await generate(ctx, messages, t.reasoning ? { effort: t.reasoning } : {}, { chat: t.chatId }, 'kit' in web ? web.kit : undefined); if (!r) return void (await end('This chat needs a model. Connect one in Settings › Chats, then ask again.', 'error')); - const text = r.text?.trim(); - await end(text || 'The model sent back an empty answer.', text ? 'done' : 'error', text && 'kit' in web ? web.sources(text) : []); + const raw = r.text?.trim() ?? '', text = chatReply(raw); + await end(text || (raw ? 'I didn’t get an answer back. Try again?' : 'The model sent back an empty answer.'), text ? 'done' : 'error', text && 'kit' in web ? web.sources(text) : []); } catch (e) { await end(e instanceof Error ? e.message : String(e), 'error'); } diff --git a/convex/providers/models.ts b/convex/providers/models.ts index 8b72eec..a1c710d 100644 --- a/convex/providers/models.ts +++ b/convex/providers/models.ts @@ -232,20 +232,33 @@ export async function generate(e: ModelEndpoint, messages: ChatTurn[], o: Genera /** The text protocol's call for a function: its one argument between tags named for it, query. */ const callTag = (t: FunctionSpec) => `<${t.name}>${t.parameters.required[0] ?? 'input'}`; +/** A body a model wrote where the argument goes when it had nothing to put there. */ +const PLACEHOLDER = /^(?:undefined|null|value|query|url|input|\.\.\.)$/i; + /** * The calls in a reply on the text protocol, each function's one argument by name, at most 3. A model that calls them in - * its own tool-call markup instead (shared/toolCallText.ts) gets those calls run too. + * its own tool-call markup instead (shared/toolCallText.ts) gets those calls run too. An invoke that holds its argument + * as bare text, query>rogue gear cost, runs only when the reply has no better call: + * Claude writes that form first and then the call properly about a third of the time on the house route. */ export function textCalls(text: string, specs: FunctionSpec[]): { name: string; args: Record }[] { const out: { name: string; args: Record }[] = []; + const keyOf = (name: string) => specs.find((s) => s.name === name)?.parameters.required[0] ?? 'input'; const add = (name: string, arg: unknown) => { - const spec = specs.find((s) => s.name === name), key = spec?.parameters.required[0] ?? 'input'; - if (spec && typeof arg === 'string' && arg.trim() && out.length < 3) out.push({ name: spec.name, args: { [key]: arg.trim() } }); + const spec = specs.find((s) => s.name === name); + if (spec && typeof arg === 'string' && arg.trim() && out.length < 3) out.push({ name: spec.name, args: { [keyOf(name)]: arg.trim() } }); }; for (const m of text.matchAll(/<([a-z_]+)>([\s\S]*?)<\/\1>/g)) add(m[1]!, m[2]); + const bare: { name: string; body: string }[] = []; for (const c of toolCallsInText(text)) { - const key = specs.find((s) => s.name === c.name)?.parameters.required[0] ?? 'input'; - add(c.name, c.args[key] ?? Object.values(c.args)[0]); + if (c.body !== undefined) bare.push({ name: c.name, body: c.body }); + else add(c.name, c.args[keyOf(c.name)] ?? Object.values(c.args)[0]); + } + if (!out.length) { + for (const b of bare) { + const arg = b.body.replace(new RegExp('^' + keyOf(b.name) + '["\']?\\s*>\\s*'), '').trim(); + if (!PLACEHOLDER.test(arg)) add(b.name, arg); + } } return out; } @@ -253,7 +266,8 @@ export function textCalls(text: string, specs: FunctionSpec[]): { name: string; /** * Tools for a model that has no tool calling (the house model, a server that refused them): the system prompt says * how to call each one as a tag, a reply that holds calls gets their results back as the next user turn, and the turn - * after `tools.rounds` such replies is told to answer. Works on any model that follows instructions. + * after `tools.rounds` such replies is told to answer. Works on any model that follows instructions. A reply that only + * tried to call one, in a form that can't run, is told the form once and goes again, instead of becoming the answer. */ export async function textTools(ask: (messages: ChatTurn[]) => Promise, messages: ChatTurn[], tools: ToolKit): Promise { const how = [ @@ -262,11 +276,20 @@ export async function textTools(ask: (messages: ChatTurn[]) => Promise m.role === 'system').map((m) => m.content).join('\n\n'), how].filter(Boolean).join('\n\n') }, ...messages.filter((m) => m.role !== 'system')]; + const names = tools.specs.map((t) => t.name); + const retry = `That call wasn’t in the form asked for, so it didn’t run. Call a tool exactly as ${tools.specs.map(callTag).join(' or ')}, or answer.`; + let retried = false; for (let round = 0; ; round++) { const last = round >= tools.rounds; const r = await ask(last ? [...convo.slice(0, -1), { ...convo[convo.length - 1]!, content: `${convo[convo.length - 1]!.content}\n\nAnswer now from what you have. Don't call any more tools.` }] : convo); const calls = r?.text ? textCalls(r.text, tools.specs) : []; - if (!r || last || !calls.length) return r && r.text ? { ...r, text: withoutToolCalls(r.text).replace(/<([a-z_]+)>[\s\S]*?<\/\1>/g, (all, name: string) => (tools.specs.some((s) => s.name === name) ? '' : all)).trim() || null } : r; + const shown = r?.text ? withoutToolCalls(r.text, names) : ''; + if (r?.text && !last && !calls.length && !shown && !retried) { + retried = true; + convo.push({ role: 'assistant', content: r.text }, { role: 'user', content: retry }); + continue; + } + if (!r || last || !calls.length) return r && r.text ? { ...r, text: shown || null } : r; convo.push({ role: 'assistant', content: r.text! }); const results = await Promise.all(calls.map(async (c) => `${c.name}(${JSON.stringify(Object.values(c.args)[0])}):\n${await tools.run(c.name, c.args)}`)); convo.push({ role: 'user', content: `Tool results:\n\n${results.join('\n\n')}` }); diff --git a/convex/push.ts b/convex/push.ts index 57dc7ff..4d47beb 100644 --- a/convex/push.ts +++ b/convex/push.ts @@ -10,7 +10,9 @@ import { getAuthSessionId } from '@convex-dev/auth/server'; import { ConvexError, v } from 'convex/values'; import { HANDLED_LIMIT } from '../src/shared/attention'; import { attentionNow, handledIds } from './attention'; -import { inboxNotices } from '../src/shared/inboxNotice'; +import { inboxNotices, plainNotices } from '../src/shared/inboxNotice'; +import { plainWaiting } from '../src/shared/agentsPanel'; +import { plainRows } from './plainChats'; import { NOTIFY_PREF, notifiesAbout, notifyOff } from '../src/shared/notifySources'; import { signInNoticeText } from '../src/shared/claim'; import { isLang, translator, type Lang, type Translate } from '../src/shared/i18n'; @@ -177,6 +179,14 @@ export const claim = internalMutation({ const fresh = (await ctx.db.query('inbox').withIndex('by_created', (q) => q.gt('createdAt', since)).order('desc').collect()) .filter((i) => !i.read && !i.archived && (i.notifiedAt ?? 0) < i.createdAt); for (const i of fresh) await ctx.db.patch(i._id, { notifiedAt: i.createdAt }); + const plain = (await plainRows(ctx)).filter((c) => c.repliedAt && c.repliedAt > since && plainWaiting(c)); + const replied: typeof plain = []; + for (const c of plain) { + const row = await ctx.db.get(c._id); + if (!row || (row.notifiedAt ?? 0) >= c.repliedAt!) continue; + await ctx.db.patch(c._id, { notifiedAt: c.repliedAt }); + replied.push(c); + } const { badge } = await attentionNow(ctx); const handled = (await handledIds(ctx)).slice(0, HANDLED_LIMIT); const handledKey = handled.join(','); @@ -184,13 +194,14 @@ export const claim = internalMutation({ for (const t of stale) await ctx.db.patch(t._id, { badge, handled: handledKey }); const now = Date.now(), quiet = (t: (typeof tokens)[number]) => !!t.off || (t.pausedUntil ?? 0) > now; const off = notifyOff({ [NOTIFY_PREF]: (await ctx.db.query('prefs').withIndex('by_name', (q) => q.eq('name', NOTIFY_PREF)).unique())?.value }); - const notifying = fresh.filter((i) => notifiesAbout(off, i.provider)); - const sends = notifying.length ? await byLanguage(ctx, tokens.filter((t) => !quiet(t)), (tr) => inboxNotices(notifying, tr)) : []; + const notifying = fresh.filter((i) => notifiesAbout(off, i.provider)), chats = notifiesAbout(off, 'chats') ? replied : []; + const any = notifying.length + chats.length > 0; + const sends = any ? await byLanguage(ctx, tokens.filter((t) => !quiet(t)), (tr) => [...inboxNotices(notifying, tr), ...plainNotices(chats, tr)]) : []; return { sends, badge, handled, - badgeOnly: notifying.length ? tokens.filter(quiet).map((t) => t.token) : stale.map((t) => t.token), + badgeOnly: any ? tokens.filter(quiet).map((t) => t.token) : stale.map((t) => t.token), }; }, }); diff --git a/convex/turns.ts b/convex/turns.ts new file mode 100644 index 0000000..9cb979c --- /dev/null +++ b/convex/turns.ts @@ -0,0 +1,54 @@ +// A reply's turn: one scheduled action (plainChats.run for a plain chat, agent.run for yoji Agent) that runs on the +// server, so leaving the chat, closing the window or switching tabs never stops it. A run that ends without finishing its +// reply (a crash outside its own error handling, a deploy, Convex's ten-minute action limit) would leave the reply +// working for good, and every later message in that chat refused as still answering. So each reply keeps its run's id +// and counts as stalled once that run is no longer pending or running (a reply with no run on record, once it outlives +// TURN_LEASE_MS, src/shared/turnLease.ts). A stalled reply reads as ended at once in what the apps read (agent.messages, +// agent.chats, plainChats.list), and is ended as an error by the next message sent in its chat, or by the check that +// runs TURN_LEASE_MS after it started, past Convex's ten-minute limit, by when any run has ended one way or the other. +import { v } from 'convex/values'; +import { internal } from './_generated/api'; +import type { Doc, Id } from './_generated/dataModel'; +import { internalMutation, type MutationCtx, type QueryCtx } from './_generated/server'; +import type { FunctionReference } from 'convex/server'; +import { TURN_LEASE_MS, turnStalled } from '../src/shared/turnLease'; + +/** What a stalled reply that had no words yet says. */ +export const STALLED_TEXT = 'This reply stopped before it finished. Ask again?'; + +/** + * Whether a working reply has stalled: its run is no longer pending or running, yet the reply never finished. A reply + * with no run on record (one sent before runs were kept, or whose job row is gone) has stalled once it is past its lease. + */ +export async function stalled(ctx: QueryCtx, m: Doc<'agentMessages'>, now = Date.now()): Promise { + if (m.status !== 'working') return false; + const job = m.runId ? await ctx.db.system.get(m.runId) : null; + if (job) return job.state.kind !== 'pending' && job.state.kind !== 'inProgress'; + return turnStalled(m, now); +} + +/** A reply as the apps read it: a stalled one already reads as ended, before the server has written that. */ +export const asRead = (m: Doc<'agentMessages'>, isStalled: boolean): Doc<'agentMessages'> => (isStalled ? { ...m, status: 'error', stalled: true, text: m.text.trim() ? m.text : STALLED_TEXT } : m); + +/** Ends a stalled reply as an error, keeping the steps and words it had. */ +export async function endStalled(ctx: MutationCtx, m: Doc<'agentMessages'>): Promise { + const now = Date.now(); + await ctx.db.patch(m._id, { status: 'error', stalled: true, doneAt: now, ...(m.text.trim() ? {} : { text: STALLED_TEXT }) }); + await ctx.db.patch(m.chatId, { updatedAt: now }); +} + +/** Schedules a reply's run, keeps its id on the reply, and schedules the check that ends the reply if the run never does. */ +export async function startTurn(ctx: MutationCtx, reply: Id<'agentMessages'>, run: FunctionReference<'action', 'internal', { messageId: Id<'agentMessages'> }>): Promise { + const runId = await ctx.scheduler.runAfter(0, run, { messageId: reply }); + await ctx.db.patch(reply, { runId }); + await ctx.scheduler.runAfter(TURN_LEASE_MS + 1000, internal.turns.reap, { messageId: reply }); +} + +/** Ends the reply if it stalled; a reply that finished, or whose run is still going, is left alone. */ +export const reap = internalMutation({ + args: { messageId: v.id('agentMessages') }, + handler: async (ctx, { messageId }) => { + const m = await ctx.db.get(messageId); + if (m && (await stalled(ctx, m))) await endStalled(ctx, m); + }, +}); diff --git a/docs/agents.md b/docs/agents.md index daffcb0..5b248de 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -24,7 +24,9 @@ Capy has no push, so yoji polls it. The poll runs only while a yoji app is open, Settings → Models connects a plain model API that runs yoji's own features: yoji Agent (⌘J) and AI task drafts. Add an Anthropic or OpenAI key, or any OpenAI-compatible server with its base URL (and a key if it needs one). A base URL must be public and `https://`. A server on a private network, or on the backend's own machine such as Ollama at `http://localhost:11434/v1`, works with `YOJI_ALLOW_PRIVATE_URLS=1`, which `pnpm run setup` sets on a local deployment ([self-hosting.md](self-hosting.md#mcp-servers-for-yoji-agent)). yoji checks the key by listing the provider's models, then stores it encrypted in the deployment, and you pick which model to use. -yoji Agent asks every model for one JSON object per step, on every route. Models sometimes call a tool in the markup they were trained on instead, such as Anthropic's `` tags or a `` tag. yoji reads those calls and runs them like any other step, and no answer, in yoji Agent or in Chats, ever shows tool-call markup outside a code block. +yoji Agent asks every model for one JSON object per step, on every route. Models sometimes call a tool in the markup they were trained on instead, such as Anthropic's `` tags or a `` tag. yoji reads those calls and runs them like any other step, and no answer, in yoji Agent or in Chats, ever shows tool-call markup outside a code block. That holds for a reply that stops partway through a tag too, such as one that ends in ` void) | null = null; let unsubscribeInbox: (() => void) | null = null; let unsubscribeCounts: (() => void) | null = null; +let unsubscribePlain: (() => void) | null = null; let windowCheck: ReturnType | null = null; let model: Model | null = null; @@ -22,10 +24,13 @@ export const currentModel = (): Model | null => model; export const dataClient = (): ConvexClient | null => client; /** `fetchToken` signs the connection in to this Mac's yoji account (session.ts). */ -export function connectData(url: string, fetchToken: AuthTokenFetcher | null, onChange: (m: Model | null) => void, onInbox: (items: InboxItem[] | null) => void, onCounts: (counts: Counts | null) => void): void { +export function connectData(url: string, fetchToken: AuthTokenFetcher | null, onChange: (m: Model | null) => void, onInbox: (items: InboxItem[] | null) => void, onCounts: (counts: Counts | null) => void, onPlain: (chats: PlainPanelChat[] | null) => void): void { unsubscribe?.(); unsubscribeInbox?.(); unsubscribeCounts?.(); + unsubscribePlain?.(); + unsubscribePlain = null; + onPlain(null); if (windowCheck) clearInterval(windowCheck); windowCheck = null; onInbox(null); @@ -82,4 +87,10 @@ export function connectData(url: string, fetchToken: AuthTokenFetcher | null, on (counts) => onCounts(counts), (err) => console.error('[yoji] attention query failed:', err.message), ); + unsubscribePlain = client.onUpdate( + api.plainChats.list, + {}, + (chats) => onPlain(chats), + (err) => console.error('[yoji] plain chats query failed:', err.message), + ); } diff --git a/src/main/index.ts b/src/main/index.ts index 13b2330..0beb1d1 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -27,7 +27,8 @@ import { setUpDeployment } from './deploySetup'; import { pairDevice } from './pairing'; import { handledSet } from '../shared/attention'; import type { Counts, InboxItem } from '../shared/integrations'; -import { dismissHandled, notifyInbox, notifySignIns, scheduleNotifications } from './notify'; +import { dismissHandled, notifyInbox, notifyPlain, notifySignIns, scheduleNotifications } from './notify'; +import type { PlainPanelChat } from '../shared/agentsPanel'; import { notifyOff as readNotifyOff, type NotifySource } from '../shared/notifySources'; import { hideWindow } from './fullscreen'; import { holdPages, pagesReach, registerAppScheme, serveApp } from './appProtocol'; @@ -201,6 +202,11 @@ function onInbox(items: InboxItem[] | null): void { onAttention(); } +/** A plain chat's reply that finished or failed while you were away notifies like an agent chat's, and opens it in Agents. */ +function onPlain(chats: PlainPanelChat[] | null): void { + notifyPlain(chats, notificationsOn(), (chat) => showMain({ type: 'openChat', chat }), notifyOff); +} + function onCounts(next: Counts | null): void { counts = next; onAttention(); @@ -220,7 +226,7 @@ function connect(): void { const s = settings(); // A page loaded before this deployment can't reach it (csp.ts), as when first run signs in. if (pagesReach(s.convexUrl)) reloadPages(); - connectData(s.convexUrl, account() ? ({ forceRefreshToken }) => authToken(forceRefreshToken) : null, onData, onInbox, onCounts); + connectData(s.convexUrl, account() ? ({ forceRefreshToken }) => authToken(forceRefreshToken) : null, onData, onInbox, onCounts, onPlain); unwatchMe?.(); unwatchMe = dataClient()?.onUpdate(api.account.me, {}, (me) => { noteProfile(me); diff --git a/src/main/notify.ts b/src/main/notify.ts index 2079fec..681ec8c 100644 --- a/src/main/notify.ts +++ b/src/main/notify.ts @@ -5,7 +5,8 @@ import { t } from '../shared/i18n'; import { settings } from './config'; import { noticeHandled } from '../shared/attention'; import { signInNoticeText, type SignInNotice } from '../shared/claim'; -import { inboxNotices } from '../shared/inboxNotice'; +import { inboxNotices, plainNotices } from '../shared/inboxNotice'; +import { plainWaiting, type PlainPanelChat } from '../shared/agentsPanel'; import { notifiesAbout } from '../shared/notifySources'; import type { InboxItem } from '../shared/integrations'; import { sessionNotice } from '../shared/menubar'; @@ -120,6 +121,51 @@ export function notifyInbox(items: InboxItem[] | null, enabled: boolean, open: ( } } +/** Each plain chat's newest repliedAt as last listed (null until the first list after connecting), and the chats themselves. */ +let seenPlain: Map | null = null; +const plainNow = new Map(); +/** How long a finished reply waits before it notifies: a chat you're watching is marked read by then and stays quiet. */ +const PLAIN_SETTLE_MS = 1500; + +/** + * A notification for each plain chat whose reply finishes or fails while yoji runs and you haven't opened it, like an + * agent chat's (src/shared/inboxNotice.ts plainNotices). The first list after connecting only records what's there, + * and a reply older than ten minutes stays quiet. It comes down once you open the chat (dismissHandled). + */ +export function notifyPlain(chats: PlainPanelChat[] | null, enabled: boolean, open: (chat: string) => void, off: ReadonlySet = new Set()): void { + if (!chats) { + seenPlain = null; + plainNow.clear(); + return; + } + const was = seenPlain; + seenPlain = new Map(chats.map((c) => [c._id, c.repliedAt ?? 0])); + plainNow.clear(); + for (const c of chats) plainNow.set(c._id, c); + if (!was) return; + const fresh = chats.filter((c) => c.repliedAt && c.repliedAt > (was.get(c._id) ?? 0) && c.repliedAt > Date.now() - 10 * 60e3); + if (!enabled || !fresh.length || !notifiesAbout(off, 'chats') || !Notification.isSupported()) return; + setTimeout(() => { + const still = fresh.flatMap((c) => { + const now = plainNow.get(c._id); + return now && now.repliedAt === c.repliedAt && plainWaiting(now) ? [now] : []; + }); + if (paused()) return; + for (const { id, title, body, chat } of plainNotices(still)) { + const n = new Notification({ title, body: body.replace(/\s+/g, ' ').slice(0, 220), silent: false }); + const done = () => (live.delete(n), notices.delete(n)); + live.add(n); + notices.set(n, [id]); + n.on('click', () => { + done(); + open(chat); + }); + n.on('close', done); + n.show(); + } + }, PLAIN_SETTLE_MS); +} + const seenSignIns = new Set(); /** diff --git a/src/renderer/src/Agents.tsx b/src/renderer/src/Agents.tsx index 2559b01..a3296e4 100644 --- a/src/renderer/src/Agents.tsx +++ b/src/renderer/src/Agents.tsx @@ -20,10 +20,10 @@ import { AgentButton } from './AgentButton'; import { Offline, useLoadState } from './Connection'; import { AgentRow, ChatRow, DraftChatPane, SectionHead, MakeAgentDialog, StarterPane, StarterRow, type AgentDraft } from './AgentsBeta'; import { PlainChatPane, plainOf } from './PlainChat'; -import { useAgentModel, useModelStatus, usePlainChats } from '../../shared/agentClient'; +import { plainRead, useAgentModel, useModelStatus, usePlainChats } from '../../shared/agentClient'; import { chatMaker } from '../../shared/agentModels'; import { useAgentConn } from './data'; -import { archivedChats, capyChatKey, panelChats, panelSections, panelTitle, STARTER_AGENT, type CapyChat, type PanelChat } from '../../shared/agentsPanel'; +import { archivedChats, capyChatKey, panelChats, panelSections, panelTitle, plainChatState, plainWaiting, STARTER_AGENT, type CapyChat, type PanelChat } from '../../shared/agentsPanel'; import { ListRail } from './ListRail'; import { useCapyChatsFrom } from '../../shared/integrations'; import { clearCaptainFrom, syncError, integrationError, openExternal, prefetchCaptain, relativeTime, useAgentConnections, useCapyModels, useCaptains, useIntegrations, type IntegrationsSource } from './integrationsData'; @@ -294,7 +294,7 @@ export function Agents(): ReactElement { const via = (kind: 'capy' | 'mcp') => (agentConns && agentConns.length > 1 ? agentConns.find((c) => c.kind === kind)?.label : undefined); useEffect(() => { if (!focus) return; - if (focus.startsWith('capy:')) { + if (focus.startsWith('capy:') || focus.startsWith('plain:')) { setSelected(focus); return void setUI({ agentFocus: null }); } @@ -409,6 +409,18 @@ export function Agents(): ReactElement { seen.current = mark; if (current.turns.some((t) => !t.read)) void source.reviewChat(current.ref).catch(fail); }, [current, source, chosen]); + /** + * A plain chat you picked is marked read while you're looking at it (this window focused, Agents on screen): opening it + * clears its dot or failed badge, and a reply that finishes while you watch never shows as unread or notifies. + */ + const plainShown = plainId && key === selected && paneLive ? (plainChats ?? []).find((c) => c._id === plainId) : undefined; + useEffect(() => { + if (!plainShown || !agentConn) return; + const mark = () => document.hasFocus() && plainWaiting(plainShown) && void plainRead(agentConn, plainShown._id).catch(fail); + mark(); + window.addEventListener('focus', mark); + return () => window.removeEventListener('focus', mark); + }, [plainShown, agentConn]); useLayoutEffect(() => { listRef.current?.querySelector('.ag-row.on')?.scrollIntoView({ block: 'nearest' }); }, [current?.key]); @@ -452,7 +464,10 @@ export function Agents(): ReactElement { const rowMenu = (x: number, y: number, top: number) => setMenu({ x, y, key: c.key, top }); const base = { on: key === c.key, tab: tabKey === c.key, menu: menu?.key === c.key, now, onPick: () => setSelected(c.key), onMenu: rowMenu }; if (c.canvas) return } line={c.canvas.line} dim={dim} onPin={() => pin(c.canvas!)} />; - if (c.plain) return ; + if (c.plain) { + const state = plainChatState(c.plain); + return } line={state.state === 'working' ? t('agents.list.working') : c.plain.line} dim={dim} />; + } if (c.capy) return pinCapyChat(c.capy!)} read={() => prefetchCaptain(source, c.capy!.id)} />; return null; }; diff --git a/src/renderer/src/PlainChat.tsx b/src/renderer/src/PlainChat.tsx index eea0052..98f529e 100644 --- a/src/renderer/src/PlainChat.tsx +++ b/src/renderer/src/PlainChat.tsx @@ -33,7 +33,7 @@ import { toast } from './store'; import { UploadChips, useUploads } from './uploads'; import { plainKey } from '../../shared/agentsPanel'; import { useT } from '../../shared/i18n/react'; -import { withoutToolCalls } from '../../shared/toolCallText'; +import { chatReply } from '../../shared/webSearch'; /** The plain chat a row key in the Agents list names (agentsPanel plainKey). */ export const plainOf = (key: string | null): string | null => (key?.startsWith('plain:') ? key.slice(6) : null); @@ -144,7 +144,7 @@ export function PlainChatPane({ id, source, onStarted }: { id: string | null; so
{m.steps?.length ? : null} - {m.status !== 'working' ? : null} + {m.status !== 'working' ? : null} {m.status === 'done' && m.sources?.length ? (
{m.sources.filter((x) => x.kind === 'url').map((x) => )} diff --git a/src/renderer/src/layers/Settings.tsx b/src/renderer/src/layers/Settings.tsx index beca5d4..b48fe90 100644 --- a/src/renderer/src/layers/Settings.tsx +++ b/src/renderer/src/layers/Settings.tsx @@ -290,13 +290,15 @@ const SOURCES: [NotifySource, string | Key, Key][] = [ ['asana', 'Asana', 'settings.notif.asana'], [CANVAS, CANVAS_NAME, 'settings.notif.canvas'], ['sessions', 'settings.notif.sessions', 'settings.notif.sessions.desc'], + ['chats', 'agents.panel.chats', 'settings.notif.chats'], ]; function Notifications(): ReactElement { const cfg = useConfig(), prefs = usePrefs(), { connections } = useIntegrations(); const t = useT(); const off = notifyOff(prefs); - const sources = SOURCES.filter(([id]) => id === 'sessions' || connections.some((c) => c.provider === id)).map(([id, title, desc]): [NotifySource, string, string] => [id, id === 'sessions' ? t(title as Key) : title, t(desc)]); + const own = (id: NotifySource) => id === 'sessions' || id === 'chats'; + const sources = SOURCES.filter(([id]) => own(id) || connections.some((c) => c.provider === id)).map(([id, title, desc]): [NotifySource, string, string] => [id, own(id) ? t(title as Key) : title, t(desc)]); return ( <> diff --git a/src/shared/agentClient.ts b/src/shared/agentClient.ts index 0a01b7f..e2f5f49 100644 --- a/src/shared/agentClient.ts +++ b/src/shared/agentClient.ts @@ -148,6 +148,8 @@ export const plainSend = (c: AgentConn, text: string, chatId: string | null, req c.client.mutation(api.plainChats.send, { text, today: todayKey(), timezone: timezone(), requestId, ...(chatId ? { chatId } : {}), ...(model && !chatId ? { model: { provider: model.provider, model: model.model } } : {}), ...(reasoning ? { reasoning } : {}), ...(files?.length ? { files: files.map((f) => ({ storageId: f.storageId as Id<'_storage'>, name: f.name })) } : {}) }); /** Sets a started plain chat's effort from its composer. */ export const plainReasoning = (c: AgentConn, chatId: string, reasoning: ReasoningMode) => c.client.mutation(api.plainChats.setReasoning, { chatId, reasoning }); +/** Marks a plain chat read on every device: its unread dot or failed badge clears and its notification comes down. */ +export const plainRead = (c: AgentConn, chatId: string) => c.client.mutation(api.plainChats.read, { chatId }); /** A model a picker chose, as the backend stores it: a connected provider's id, or the house model's, and the model on it. */ export interface ChatPick { provider: string; model: string } diff --git a/src/shared/agentsPanel.ts b/src/shared/agentsPanel.ts index b1d19e5..8914fac 100644 --- a/src/shared/agentsPanel.ts +++ b/src/shared/agentsPanel.ts @@ -75,8 +75,32 @@ export const STARTER_AGENT = { /** A Capy chat's row key in the panel. */ export const capyChatKey = (c: Pick): string => `capychat:${c.id}`; -/** A plain model chat as convex/plainChats.ts lists it. */ -export interface PlainPanelChat { _id: string; title: string; updatedAt: number; working: boolean; repliedAt?: number; model?: { provider: string; model: string } } +/** + * A plain model chat as convex/plainChats.ts lists it: `working` while its reply runs, `stalled` while a reply that + * stopped showing life waits for recovery (src/shared/turnLease.ts), `repliedAt` once its reply ended and `failed` + * when that ended in an error, `readAt` when you last opened or sent in it, and `line` its newest reply's first line. + */ +export interface PlainPanelChat { _id: string; title: string; updatedAt: number; working: boolean; stalled?: boolean; repliedAt?: number; failed?: boolean; readAt?: number; line?: string; model?: { provider: string; model: string } } + +/** + * A plain chat's row state in the agent chats' own terms (Chat's state, need and unread), so the Mac and the phone + * draw it with the agent chats' ChatBadge: working while its reply runs, stale once that reply stalled, failed (needs) + * when it ended in an error you haven't opened, and unread when it finished after you last opened the chat. A chat + * with no readAt (one from before yoji kept it) reads as read. + */ +export function plainChatState(c: Pick): Pick { + if (c.stalled) return { state: 'stale', unread: false }; + if (c.working) return { state: 'working', unread: false }; + const fresh = c.readAt !== undefined && c.repliedAt !== undefined && c.repliedAt > c.readAt; + if (c.failed && fresh) return { state: 'needs', need: 'failed', unread: false }; + return { state: 'ready', unread: fresh }; +} + +/** Whether a plain chat counts toward the Agents counter and app badge, as an agent chat that needs you or has a reply you haven't read does. */ +export const plainWaiting = (c: Pick): boolean => { + const s = plainChatState(c); + return s.state === 'needs' || s.unread; +}; /** A plain chat's row key in the Agents list. */ export const plainKey = (id: string): string => `plain:${id}`; diff --git a/src/shared/attention.test.ts b/src/shared/attention.test.ts index b30663b..a3eb3c8 100644 --- a/src/shared/attention.test.ts +++ b/src/shared/attention.test.ts @@ -14,7 +14,7 @@ const cap = (id: string, extra: Partial = {}): Captain => ({ id, name: describe('attention', () => { it(`adds Inbox unread, ${CANVAS_NAME} chats that want you and Captains you have not cleared into the badge`, () => { const a = attention([row('a'), row('b', { read: true }), row('c', { archived: true })], [turn('x'), turn('y', { read: true })], [cap('k', { needsYou: true }), cap('l', { crewNeedsYou: 2, cleared: true }), cap('m')]); - expect(a).toEqual({ inbox: 1, canvas: 1, captains: 1, agents: 2, badge: 3 }); + expect(a).toEqual({ inbox: 1, canvas: 1, captains: 1, chats: 0, agents: 2, badge: 3 }); }); it(`leaves archived ${CANVAS_NAME} chats out`, () => { diff --git a/src/shared/attention.ts b/src/shared/attention.ts index 879e2b0..7298771 100644 --- a/src/shared/attention.ts +++ b/src/shared/attention.ts @@ -5,6 +5,9 @@ import { agentsBadgeCount, chatList, inboxUnread } from './agents'; import { captainsBadge, type Captain } from './captains'; import type { InboxItem } from './integrations'; import { CANVAS } from './canvasAgent'; +import { plainWaiting, type PlainPanelChat } from './agentsPanel'; + +type PlainState = Pick; export interface Attention { /** Unread rows the Inbox shows. */ @@ -13,7 +16,9 @@ export interface Attention { canvas: number; /** Captains waiting on you that you haven't cleared. */ captains: number; - /** The Agents counter: canvas + captains. */ + /** Plain model chats that failed or have a reply you haven't read (agentsPanel plainWaiting). */ + chats: number; + /** The Agents counter: canvas + captains + chats. */ agents: number; /** The app icon: inbox + agents. */ badge: number; @@ -21,10 +26,10 @@ export interface Attention { type Row = Pick; -/** `inbox` is the Inbox's rows, `canvas` every agent turn (agents:list), `captains` the Captains with yoji's cleared flags. */ -export function attention(inbox: readonly Row[], canvas: readonly InboxItem[], captains: readonly Captain[]): Attention { - const a = agentsBadgeCount(chatList(canvas)), c = captainsBadge(captains), i = inboxUnread(inbox); - return { inbox: i, canvas: a, captains: c, agents: a + c, badge: i + a + c }; +/** `inbox` is the Inbox's rows, `canvas` every agent turn (agents:list), `captains` the Captains with yoji's cleared flags, `plain` the plain chats (plainChats:list). */ +export function attention(inbox: readonly Row[], canvas: readonly InboxItem[], captains: readonly Captain[], plain: readonly PlainState[] = []): Attention { + const a = agentsBadgeCount(chatList(canvas)), c = captainsBadge(captains), i = inboxUnread(inbox), p = plain.filter(plainWaiting).length; + return { inbox: i, canvas: a, captains: c, chats: p, agents: a + c + p, badge: i + a + c + p }; } /** The Inbox items a notification stands for: its own id, or every item a summary covers. */ diff --git a/src/shared/i18n/locales/de/notices.ts b/src/shared/i18n/locales/de/notices.ts index 55c47ba..6ad3171 100644 --- a/src/shared/i18n/locales/de/notices.ts +++ b/src/shared/i18n/locales/de/notices.ts @@ -7,6 +7,8 @@ export default { 'notice.agent.question': '{agent} hat eine Frage · {where}', 'notice.agent.failed': '{agent} ist fehlgeschlagen · {where}', 'notice.agent.finished': '{agent} ist fertig · {where}', + 'notice.chat.finished': 'Chat hat geantwortet · {where}', + 'notice.chat.failed': 'Chat ist fehlgeschlagen · {where}', 'notice.outputs': { one: '{count} Ergebnis bereit', other: '{count} Ergebnisse bereit' }, 'notice.likedComment': '{author} gefällt dein Kommentar zu {title}', 'notice.likedTask': '{author} gefällt deine Aufgabe', diff --git a/src/shared/i18n/locales/de/settings.ts b/src/shared/i18n/locales/de/settings.ts index 180a6d1..4852464 100644 --- a/src/shared/i18n/locales/de/settings.ts +++ b/src/shared/i18n/locales/de/settings.ts @@ -257,6 +257,7 @@ export default { 'settings.notif.slack': 'Erwähnungen, Direktnachrichten und Antworten in Threads, denen du folgst.', 'settings.notif.asana': 'Dir zugewiesene Aufgaben und Kommentare zu deinen Aufgaben.', 'settings.notif.canvas': 'Chats, die fertig werden, fehlschlagen oder dir eine Frage stellen.', + 'settings.notif.chats': 'Antworten eines Modells, die fertig werden oder fehlschlagen, während du weg bist.', 'settings.notif.sessions': 'Aufgaben-Sessions', 'settings.notif.sessions.desc': 'Wenn eine geplante Session beginnt. Nur die Desktop-App zeigt diese an.', 'settings.notif.signIns': 'Neue Anmeldungen bei deinem Konto melden sich immer, auf jedem Gerät.', diff --git a/src/shared/i18n/locales/en/notices.ts b/src/shared/i18n/locales/en/notices.ts index 3565766..54e6d0a 100644 --- a/src/shared/i18n/locales/en/notices.ts +++ b/src/shared/i18n/locales/en/notices.ts @@ -4,6 +4,8 @@ export default { 'notice.agent.question': '{agent} has a question · {where}', 'notice.agent.failed': '{agent} failed · {where}', 'notice.agent.finished': '{agent} finished · {where}', + 'notice.chat.finished': 'Chat replied · {where}', + 'notice.chat.failed': 'Chat failed · {where}', 'notice.outputs': { one: '{count} output ready', other: '{count} outputs ready' }, 'notice.likedComment': '{author} liked your comment on {title}', 'notice.likedTask': '{author} liked your task', diff --git a/src/shared/i18n/locales/en/settings.ts b/src/shared/i18n/locales/en/settings.ts index 0f28948..081b1e7 100644 --- a/src/shared/i18n/locales/en/settings.ts +++ b/src/shared/i18n/locales/en/settings.ts @@ -254,6 +254,7 @@ export default { 'settings.notif.slack': 'Mentions, direct messages and replies in threads you follow.', 'settings.notif.asana': 'Tasks assigned to you and comments on your tasks.', 'settings.notif.canvas': 'Chats that finish, fail or ask you a question.', + 'settings.notif.chats': 'Replies from a model that finish or fail while you’re away.', 'settings.notif.sessions': 'Task sessions', 'settings.notif.sessions.desc': 'When a session you planned starts. Only the desktop app shows these.', 'settings.notif.signIns': 'New sign-ins to your account always notify you, on every device.', diff --git a/src/shared/i18n/locales/es/notices.ts b/src/shared/i18n/locales/es/notices.ts index 8c74818..c5a61f8 100644 --- a/src/shared/i18n/locales/es/notices.ts +++ b/src/shared/i18n/locales/es/notices.ts @@ -7,6 +7,8 @@ export default { 'notice.agent.question': '{agent} tiene una pregunta · {where}', 'notice.agent.failed': '{agent} falló · {where}', 'notice.agent.finished': '{agent} terminó · {where}', + 'notice.chat.finished': 'El chat respondió · {where}', + 'notice.chat.failed': 'El chat falló · {where}', 'notice.outputs': { one: '{count} resultado listo', other: '{count} resultados listos' }, 'notice.likedComment': 'A {author} le gustó tu comentario en {title}', 'notice.likedTask': 'A {author} le gustó tu tarea', diff --git a/src/shared/i18n/locales/es/settings.ts b/src/shared/i18n/locales/es/settings.ts index 53f1f8f..c39dfb4 100644 --- a/src/shared/i18n/locales/es/settings.ts +++ b/src/shared/i18n/locales/es/settings.ts @@ -257,6 +257,7 @@ export default { 'settings.notif.slack': 'Menciones, mensajes directos y respuestas en los hilos que sigues.', 'settings.notif.asana': 'Tareas que te asignan y comentarios en tus tareas.', 'settings.notif.canvas': 'Chats que terminan, fallan o te hacen una pregunta.', + 'settings.notif.chats': 'Respuestas de un modelo que terminan o fallan mientras no estás.', 'settings.notif.sessions': 'Sesiones de tareas', 'settings.notif.sessions.desc': 'Cuando empieza una sesión que planificaste. Solo la app de escritorio las muestra.', 'settings.notif.signIns': 'Los nuevos inicios de sesión en tu cuenta siempre te avisan, en todos los dispositivos.', diff --git a/src/shared/i18n/locales/fr/notices.ts b/src/shared/i18n/locales/fr/notices.ts index 42160c5..5c4b19b 100644 --- a/src/shared/i18n/locales/fr/notices.ts +++ b/src/shared/i18n/locales/fr/notices.ts @@ -8,6 +8,8 @@ export default { 'notice.agent.question': '{agent} a une question · {where}', 'notice.agent.failed': '{agent} a échoué · {where}', 'notice.agent.finished': '{agent} a terminé · {where}', + 'notice.chat.finished': 'Le chat a répondu · {where}', + 'notice.chat.failed': 'Le chat a échoué · {where}', 'notice.outputs': { one: '{count} résultat prêt', other: '{count} résultats prêts' }, 'notice.likedComment': '{author} a aimé votre commentaire sur {title}', 'notice.likedTask': '{author} a aimé votre tâche', diff --git a/src/shared/i18n/locales/fr/settings.ts b/src/shared/i18n/locales/fr/settings.ts index 87f5df8..9967800 100644 --- a/src/shared/i18n/locales/fr/settings.ts +++ b/src/shared/i18n/locales/fr/settings.ts @@ -251,6 +251,7 @@ export default { 'settings.notif.slack': 'Les mentions, messages directs et réponses dans les fils que vous suivez.', 'settings.notif.asana': 'Les tâches qui vous sont assignées et les commentaires sur vos tâches.', 'settings.notif.canvas': 'Les chats qui se terminent, échouent ou vous posent une question.', + 'settings.notif.chats': 'Les réponses d’un modèle qui se terminent ou échouent pendant votre absence.', 'settings.notif.sessions': 'Sessions de tâches', 'settings.notif.sessions.desc': 'Quand une session prévue commence. Seule l’app de bureau les affiche.', 'settings.notif.signIns': 'Les nouvelles connexions à votre compte vous notifient toujours, sur tous les appareils.', diff --git a/src/shared/i18n/locales/ja/notices.ts b/src/shared/i18n/locales/ja/notices.ts index 2857f17..940f2d0 100644 --- a/src/shared/i18n/locales/ja/notices.ts +++ b/src/shared/i18n/locales/ja/notices.ts @@ -7,6 +7,8 @@ export default { 'notice.agent.question': '{agent}から質問があります · {where}', 'notice.agent.failed': '{agent}が失敗しました · {where}', 'notice.agent.finished': '{agent}が完了しました · {where}', + 'notice.chat.finished': 'チャットが返信しました · {where}', + 'notice.chat.failed': 'チャットが失敗しました · {where}', 'notice.outputs': { other: '{count}件の成果物ができました' }, 'notice.likedComment': '{author}が{title}へのコメントに「いいね」しました', 'notice.likedTask': '{author}があなたのタスクに「いいね」しました', diff --git a/src/shared/i18n/locales/ja/settings.ts b/src/shared/i18n/locales/ja/settings.ts index df0d5d2..03b7891 100644 --- a/src/shared/i18n/locales/ja/settings.ts +++ b/src/shared/i18n/locales/ja/settings.ts @@ -258,6 +258,7 @@ export default { 'settings.notif.slack': 'メンション、ダイレクトメッセージ、フォロー中のスレッドへの返信。', 'settings.notif.asana': '自分に割り当てられたタスクと、自分のタスクへのコメント。', 'settings.notif.canvas': '完了したチャット、失敗したチャット、質問してきたチャット。', + 'settings.notif.chats': '離れている間にモデルの返信が完了または失敗したとき。', 'settings.notif.sessions': 'タスクのセッション', 'settings.notif.sessions.desc': '予定したセッションが始まったとき。デスクトップアプリでのみ表示されます。', 'settings.notif.signIns': 'アカウントへの新しいサインインは、すべてのデバイスで常に通知されます。', diff --git a/src/shared/inboxNotice.ts b/src/shared/inboxNotice.ts index 2b8a633..3d7af75 100644 --- a/src/shared/inboxNotice.ts +++ b/src/shared/inboxNotice.ts @@ -2,6 +2,7 @@ // backend's phone pushes: who and where on top, what they said below, like Slack's own. Pushes are written in each // phone's language, so every function here takes the translator to write with. import { chatKey } from './agents'; +import { plainKey } from './agentsPanel'; import { t, type Translate } from './i18n'; import { plainText, slackLinkLabels } from './markdown'; import { reactionText } from './inboxReactions'; @@ -39,6 +40,17 @@ function notice(i: NoticeItem, tr: Translate): { title: string; body: string } { return { title: tr(inThread(i) ? 'notice.thread' : 'notice.where', { author: i.author, where: whereOf(i.context) }), body: i.body || i.title }; } +/** A plain chat whose reply just finished or failed, as plainChats:list gives it. */ +export type PlainNoticeChat = { _id: string; title: string; failed?: boolean; line?: string }; + +/** + * A notification for each plain chat whose reply finished or failed while you were away, like an agent chat's: the + * chat's title on top, the reply's first line below. Its id is the chat's, which a click or tap opens in Agents and + * which comes down once you open the chat (attention.ts handledIds). + */ +export const plainNotices = (chats: readonly PlainNoticeChat[], tr: Translate = t): { id: string; ids?: string[]; title: string; body: string; chat: string }[] => + chats.map((c) => ({ id: c._id, title: tr(c.failed ? 'notice.chat.failed' : 'notice.chat.finished', { where: c.title }), body: plainText(c.line ?? '') || c.title, chat: plainKey(c._id) })); + /** * More than three arrivals at once become one summary, which names every item it covers (`ids`) so it comes down once * they're all handled. An agent notice carries its chat, which a click or tap opens in Agents. diff --git a/src/shared/notifySources.ts b/src/shared/notifySources.ts index f74bae5..9863e5b 100644 --- a/src/shared/notifySources.ts +++ b/src/shared/notifySources.ts @@ -6,8 +6,8 @@ import { CANVAS } from './canvasAgent'; /** The prefs row: the sources turned off, comma separated; unset or empty notifies about everything. */ export const NOTIFY_PREF = 'notifyOff'; -/** Inbox providers that notify, and task sessions, which only the Mac shows. */ -export const NOTIFY_SOURCES = ['slack', 'asana', CANVAS, 'sessions'] as const; +/** Inbox providers that notify, task sessions, which only the Mac shows, and plain chats' replies (Agents › Chats). */ +export const NOTIFY_SOURCES = ['slack', 'asana', CANVAS, 'sessions', 'chats'] as const; export type NotifySource = (typeof NOTIFY_SOURCES)[number]; const known = (s: string): s is NotifySource => (NOTIFY_SOURCES as readonly string[]).includes(s); diff --git a/src/shared/plainChatState.test.ts b/src/shared/plainChatState.test.ts new file mode 100644 index 0000000..2c73657 --- /dev/null +++ b/src/shared/plainChatState.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest'; +import { plainChatState, plainWaiting } from './agentsPanel'; +import { attention } from './attention'; +import { plainNotices } from './inboxNotice'; + +// A plain chat's row state in the agent chats' terms, so the Mac and the phone draw it with the same ChatBadge. +describe('plainChatState', () => { + const read = 1_000; + it('is working while its reply runs, and stale once that reply stalled', () => { + expect(plainChatState({ working: true, readAt: read })).toEqual({ state: 'working', unread: false }); + expect(plainChatState({ working: false, stalled: true, readAt: read })).toEqual({ state: 'stale', unread: false }); + }); + + it('is unread when a reply finished after you last opened the chat, and read after', () => { + expect(plainChatState({ working: false, repliedAt: 2_000, readAt: read })).toEqual({ state: 'ready', unread: true }); + expect(plainChatState({ working: false, repliedAt: 2_000, readAt: 2_500 })).toEqual({ state: 'ready', unread: false }); + }); + + it('is failed when that reply errored, until you open the chat', () => { + expect(plainChatState({ working: false, repliedAt: 2_000, failed: true, readAt: read })).toEqual({ state: 'needs', need: 'failed', unread: false }); + expect(plainChatState({ working: false, repliedAt: 2_000, failed: true, readAt: 3_000 })).toEqual({ state: 'ready', unread: false }); + }); + + it('reads a chat from before read state existed as read', () => { + expect(plainChatState({ working: false, repliedAt: 2_000 })).toEqual({ state: 'ready', unread: false }); + expect(plainChatState({ working: false })).toEqual({ state: 'ready', unread: false }); + }); + + it('counts failed and unread chats toward the Agents counter and the badge, never working or stale ones', () => { + const chats = [ + { working: false, repliedAt: 2_000, readAt: read }, + { working: false, repliedAt: 2_000, failed: true, readAt: read }, + { working: true, readAt: read }, + { working: false, stalled: true, readAt: read }, + { working: false, repliedAt: 2_000, readAt: 3_000 }, + ]; + expect(chats.map(plainWaiting)).toEqual([true, true, false, false, false]); + expect(attention([], [], [], chats)).toEqual({ inbox: 0, canvas: 0, captains: 0, chats: 2, agents: 2, badge: 2 }); + }); +}); + +describe('plainNotices', () => { + it('names the chat and its reply, and opens the plain chat', () => { + expect(plainNotices([{ _id: 'c1', title: 'Rogue armor', line: 'Tier 1 costs **1,000** honor.' }, { _id: 'c2', title: 'Web search', failed: true }])).toEqual([ + { id: 'c1', title: 'Chat replied · Rogue armor', body: 'Tier 1 costs 1,000 honor.', chat: 'plain:c1' }, + { id: 'c2', title: 'Chat failed · Web search', body: 'Web search', chat: 'plain:c2' }, + ]); + }); +}); diff --git a/src/shared/toolCallText.test.ts b/src/shared/toolCallText.test.ts index b52210c..e2d8d55 100644 --- a/src/shared/toolCallText.test.ts +++ b/src/shared/toolCallText.test.ts @@ -25,6 +25,12 @@ describe('toolCallsInText', () => { expect(toolCallsInText(text)).toEqual([{ name: 'web_search', args: { query: 'pdf parsing' } }, { name: 'findTasks', args: { text: 'launch' } }]); }); + it('keeps the bare text of an invoke with no parameter tags as its body, and reads a JSON object there as the arguments', () => { + expect(toolCallsInText('query>rogue honor costs')).toEqual([{ name: 'web_search', args: {}, body: 'query>rogue honor costs' }]); + expect(toolCallsInText('{"task": "YJ-1"}')).toEqual([{ name: 'getTask', args: { task: 'YJ-1' } }]); + expect(toolCallsInText('')).toEqual([{ name: 'listLabels', args: {} }]); + }); + it('ignores markup inside code and text with no markup', () => { expect(toolCallsInText(FENCE + 'xml\nYJ-1\n' + FENCE)).toEqual([]); expect(toolCallsInText('Use \x60\x60 tags.')).toEqual([]); @@ -59,6 +65,32 @@ describe('withoutToolCalls', () => { expect(withoutToolCalls('Odd tag and 1 left.')).toBe('Odd tag and left.'); }); + it('drops a tag the reply stopped partway through, at its very end (a chat once saved " { + expect(withoutToolCalls('query>rogue honor costs\nrank 14')).toBe('Here it is.'); + }); + + it('takes out the extra tags it is given, whole or cut off, and leaves other tags', () => { + const tags = ['web_search', 'web_fetch']; + expect(withoutToolCalls('rogue honor\nAnswer.', tags)).toBe('Answer.'); + expect(withoutToolCalls('Answer.\nhttps://example.com', tags)).toBe('Answer.'); + expect(withoutToolCalls('Answer.\n', tags)).toBe('Answer.'); + expect(withoutToolCalls('Moved to Friday.', tags)).toBe('Moved to Friday.'); + expect(withoutToolCalls('x stays without the names.')).toBe('x stays without the names.'); + }); + + it('keeps a cut-off tag inside code, and text that only looks like one', () => { + const open = 'Close it like this:\n\n' + FENCE + 'html\nbold')).toBe('Wrap it in bold'); + }); + it('leaves code and ordinary text exactly as they were', () => { const code = 'Claude writes calls like this:\n\n' + FENCE + 'xml\n\nYJ-1\n\n' + FENCE + '\n\nand \x60\x60 for Qwen.'; expect(withoutToolCalls(code)).toBe(code); diff --git a/src/shared/toolCallText.ts b/src/shared/toolCallText.ts index a70bd95..bdc2b80 100644 --- a/src/shared/toolCallText.ts +++ b/src/shared/toolCallText.ts @@ -2,10 +2,11 @@ // house model, a server that refuses them, yoji Agent's JSON steps on every route) sometimes falls back to the markup it // was trained to call tools with: Anthropic's invoke and parameter tags, or the tool_call tag Qwen, Hermes and others // use. yoji reads those calls so they run (shared/agent.ts parseStep, providers/models.ts textTools), and never shows -// the markup: every reply is saved (agent.finish) and drawn without it. Markup inside a code block or inline code is -// left alone, so an answer about the syntax still reads. +// the markup: every reply is saved (agent.finish) and drawn without it, even when the reply stops partway through a tag. +// Markup inside a code block or inline code is left alone, so an answer about the syntax still reads. -export interface TextCall { name: string; args: Record } +/** `body` is what an invoke with no parameter tags holds as plain text, such as a query. */ +export interface TextCall { name: string; args: Record; body?: string } const INVOKE = /<(?:[a-z]+:)?invoke\s+name\s*=\s*["']([^"']+)["']\s*>([\s\S]*?)<\/(?:[a-z]+:)?invoke\s*>/gi; const PARAMETER = /<(?:[a-z]+:)?parameter\s+name\s*=\s*["']([^"']+)["']\s*>([\s\S]*?)<\/(?:[a-z]+:)?parameter\s*>/gi; @@ -17,10 +18,13 @@ const LEFTOVERS = [ /<\/?(?:[a-z]+:)?function_calls\s*>/gi, PARAMETER, /<(?:[a-z]+:)?invoke\b[\s\S]*$/i, + /<(?:[a-z]+:)?parameter\b[\s\S]*$/i, /[\s\S]*$/i, /<\/(?:(?:[a-z]+:)?invoke|(?:[a-z]+:)?parameter|tool_call)\s*>/gi, ]; const MARKUP = /<\/?(?:[a-z]+:)?(?:invoke|parameter|function_calls|tool_call)\b/i; +/** A tag the reply stopped in the middle of, at its very end, such as "<", "]*)?)?$/i; /** Fenced code blocks (an unclosed one runs to the end) and inline code. */ const CODE = /(\x60\x60\x60[\s\S]*?(?:\x60\x60\x60|$)|\x60[^\x60\n]+\x60)/; @@ -58,6 +62,11 @@ export function toolCallsInText(text: string): TextCall[] { for (const m of prose.matchAll(new RegExp(INVOKE.source + '|' + TOOL_CALL.source, 'gi'))) { if (m[1] !== undefined) { const params = [...m[2]!.matchAll(PARAMETER)].map((p) => [p[1]!, value(p[2]!)] as const); + if (!params.length) { + const body = m[2]!.trim(), json = record(body); + out.push(Object.keys(json).length ? { name: m[1].trim(), args: json } : { name: m[1].trim(), args: {}, ...(body ? { body } : {}) }); + continue; + } const [only] = params, wrapped = params.length === 1 && /^(?:args|arguments|input)$/.test(only![0]) && record(only![1]); out.push({ name: m[1].trim(), args: wrapped && Object.keys(wrapped).length ? wrapped : Object.fromEntries(params) }); continue; @@ -84,10 +93,20 @@ export function fieldsInMarkup(text: string): Record | null { return out; } -/** A reply without any tool-call markup outside code; empty when the markup was all it had. */ -export function withoutToolCalls(text: string): string { - if (!MARKUP.test(text)) return text; - return outsideCode(text, (prose) => [ANY_INVOKE, TOOL_CALL, ...LEFTOVERS].reduce((s, re) => s.replace(re, ''), prose)) +/** + * A reply without any tool-call markup outside code, and without a tag it stopped partway through; empty when the markup + * was all it had. `tags` are more tag names to take out the same way, whole or cut off: a plain chat's web tools, which + * its text protocol calls as query (convex/providers/models.ts textTools). + */ +export function withoutToolCalls(text: string, tags: readonly string[] = []): string { + const names = tags.map((t) => t.replace(/[^\w-]/g, '')).filter(Boolean).join('|'); + const own = names ? [new RegExp('<(' + names + ')>[\\s\\S]*?<\\/\\1\\s*>', 'g'), new RegExp('<(?:' + names + ')>[\\s\\S]*$'), new RegExp('<\\/(?:' + names + ')\\s*>', 'g')] : []; + const parts = text.split(CODE), last = parts.length - 1; + const cut = last % 2 === 0 && CUT_TAG.test(parts[last]!); + if (!MARKUP.test(text) && !cut && !(names && new RegExp('<\\/?(?:' + names + ')>').test(text))) return text; + return parts + .map((part, i) => (i % 2 ? part : [ANY_INVOKE, TOOL_CALL, ...LEFTOVERS, ...own, ...(i === last ? [CUT_TAG] : [])].reduce((s, re) => s.replace(re, ''), part))) + .join('') .replace(/[ \t]+\n/g, '\n') .replace(/\n{3,}/g, '\n\n') .trim(); diff --git a/src/shared/turnLease.test.ts b/src/shared/turnLease.test.ts new file mode 100644 index 0000000..22b3d56 --- /dev/null +++ b/src/shared/turnLease.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { TURN_LEASE_MS, turnStalled } from './turnLease'; + +describe('turnStalled', () => { + it('is past Convex’s ten-minute action limit, so a run still going is never cut short', () => { + expect(TURN_LEASE_MS).toBeGreaterThan(10 * 60_000); + }); + + it('holds only for a working reply older than the lease', () => { + expect(turnStalled({ status: 'working', createdAt: 0 }, TURN_LEASE_MS)).toBe(false); + expect(turnStalled({ status: 'working', createdAt: 0 }, TURN_LEASE_MS + 1)).toBe(true); + expect(turnStalled({ status: 'done', createdAt: 0 }, TURN_LEASE_MS * 2)).toBe(false); + expect(turnStalled({ status: 'error', createdAt: 0 }, TURN_LEASE_MS * 2)).toBe(false); + }); +}); diff --git a/src/shared/turnLease.ts b/src/shared/turnLease.ts new file mode 100644 index 0000000..c80ceda --- /dev/null +++ b/src/shared/turnLease.ts @@ -0,0 +1,7 @@ +// How long a reply may work before it counts as stalled (convex/turns.ts), shared so the apps and the server agree. + +/** Past Convex's ten-minute action limit, so a run that's still going is never cut short. In milliseconds. */ +export const TURN_LEASE_MS = 11 * 60_000; + +/** Whether a reply is still working after its lease ran out, by its createdAt (ms). */ +export const turnStalled = (m: { status: string; createdAt: number }, now: number): boolean => m.status === 'working' && now - m.createdAt > TURN_LEASE_MS; diff --git a/src/shared/webSearch.test.ts b/src/shared/webSearch.test.ts index 439bd0c..d63aa7b 100644 --- a/src/shared/webSearch.test.ts +++ b/src/shared/webSearch.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { stepRow } from './agentView'; -import { answerSources, readStep, searchedStep, shortUrl, unreadStep, webOffPrompt, webOnPrompt } from './webSearch'; +import { answerSources, chatReply, readStep, searchedStep, shortUrl, unreadStep, webOffPrompt, webOnPrompt } from './webSearch'; import { textCalls } from '../../convex/providers/models'; import { WEB_TOOLS } from './webSearch'; @@ -37,6 +37,29 @@ describe('text protocol', () => { }); }); +describe('text protocol: what Claude Sonnet 5.5 wrote live on the house route (Nov 30)', () => { + it('runs an invoke holding its query as bare text when the reply has no proper call', () => { + expect(textCalls('query>WoW honor point costs rogue weapons armor\n\nquery">WoW Forever rogue gear cost', WEB_TOOLS)).toEqual([{ name: 'web_search', args: { query: 'WoW honor point costs rogue weapons armor' } }, { name: 'web_search', args: { query: 'WoW Forever rogue gear cost' } }]); + expect(textCalls('Rogue PvP honor costs\n { + const text = 'value\n\n\n\nWoW rogue PvP gear honor point cost\n'; + expect(textCalls(text, WEB_TOOLS)).toEqual([{ name: 'web_search', args: { query: 'WoW rogue PvP gear honor point cost' } }]); + expect(textCalls('undefined', WEB_TOOLS)).toEqual([]); + }); +}); + +describe('a chat reply as saved and drawn', () => { + it('has no markup and no web tool tags, whole or cut off partway', () => { + expect(chatReply('query>rogue honor costs\nrogue honor\nRank 14 costs 26,950 honor.\nmore')).toBe('Rank 14 costs 26,950 honor.'); + expect(chatReply('Plain **answer**.')).toBe('Plain **answer**.'); + }); +}); + describe('the web prompts', () => { it('carry no em or en dashes', () => { expect(webOnPrompt('2026-11-30') + webOffPrompt('noKey') + webOffPrompt('off')).not.toMatch(/[–—]/); diff --git a/src/shared/webSearch.ts b/src/shared/webSearch.ts index fce197a..28a2b4a 100644 --- a/src/shared/webSearch.ts +++ b/src/shared/webSearch.ts @@ -2,6 +2,7 @@ // backed by Firecrawl (convex/webSearch.ts), the prompt that tells a model to look things up instead of refusing a // question newer than its training, how each call reads as a step in the chat, and which pages the answer cites. // Shared so the apps word the steps the way the server writes them. +import { withoutToolCalls } from './toolCallText'; /** A function the model can call, in the JSON Schema shape every provider's tool calling takes. */ export interface FunctionSpec { name: string; description: string; parameters: { type: 'object'; properties: Record; required: string[] } } @@ -28,6 +29,9 @@ export const WEB_TOOLS: FunctionSpec[] = [ */ export const WEB_LIMITS = { rounds: 5, calls: 10, results: 8, snippetChars: 400, pageChars: 12_000 }; +/** A plain chat's reply as it's saved and drawn: no tool-call markup and no web tool tags, whole or cut off partway. */ +export const chatReply = (text: string): string => withoutToolCalls(text, [WEB_SEARCH, WEB_FETCH]); + /** What the system prompt adds for a chat that can search the web. */ export const webOnPrompt = (today: string): string => [