Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
f69e2bc
perf(bots): read Bot Home items as summaries, by changed uid, without…
brennanb2025 Nov 20, 2026
543f552
test(bots): summary list, Closed page alone, named items, and named-i…
brennanb2025 Nov 20, 2026
47603e9
perf(bots): look named items up by uid
brennanb2025 Nov 20, 2026
5c7c7e1
fix(bots): keep Closed paging whole across unheard changes, races and…
brennanb2025 Nov 20, 2026
25177a7
fix(bots): keep the merge the phone app uses; carry Closed pages only…
brennanb2025 Nov 20, 2026
0de1887
fix(bots): named merges keep the host's order, group Closed waits at …
brennanb2025 Nov 20, 2026
fe6513b
fix(bots): read loaded Closed pages again after a whole read; named r…
brennanb2025 Nov 21, 2026
ccfb2ee
fix(bots): follow named reads through batched renders, keep pages acr…
brennanb2025 Nov 21, 2026
65eedab
test(bots): build the named read through the merge
brennanb2025 Nov 21, 2026
922402b
fix(bots): open items win a Dispatch lookup; whole chat reads revalid…
brennanb2025 Nov 21, 2026
bc6d909
fix(bots): named merges keep a whole read's shape; pushed-out and nam…
brennanb2025 Nov 21, 2026
9d96a6c
fix(bots): named Closed copies reach loaded pages above their end, an…
brennanb2025 Nov 21, 2026
de65b3b
fix(bots): typecheck and lint fixes for the Closed pages hook and tests
brennanb2025 Nov 21, 2026
5bcc35d
fix(bots): a named Closed item moved below the first page's end leave…
brennanb2025 Nov 21, 2026
9ad48e5
fix(bots): a late Closed page takes named items newly Closed within i…
brennanb2025 Nov 21, 2026
3034b77
fix(bots): drop a late Closed page when what changed meanwhile is no …
brennanb2025 Nov 21, 2026
48d01c1
fix(bots): one set lookup for named uids; a late page with unknown hi…
brennanb2025 Nov 21, 2026
ab31860
fix(bots): a Show more still out when the depth is read again is read…
brennanb2025 Nov 21, 2026
7dcac47
refactor(bots): load Closed pages inside the one serialized Items rea…
brennanb2025 Nov 21, 2026
75e17cf
fix(bots): worker notices read only the loaded items that link a work…
brennanb2025 Nov 21, 2026
1eec284
fix(bots): the host names the items a worker change touches; an older…
brennanb2025 Nov 21, 2026
02767ff
fix(bots): a worker change the host didn't name reads the list whole;…
brennanb2025 Nov 21, 2026
573cb5d
fix(bots): a failed worker item lookup reads lists whole; a list read…
brennanb2025 Nov 21, 2026
e25cd0c
fix(bots): a whole read stops paging once nothing shows its list
brennanb2025 Nov 21, 2026
afe031f
fix(bots): a Closed list read to its end keeps room for its pages; an…
brennanb2025 Nov 21, 2026
4c53cc8
fix(bots): a worker change naming more items than a notice holds read…
brennanb2025 Nov 21, 2026
d8d9f7d
fix(bots): an older host's unchanged first page reads only the page S…
brennanb2025 Nov 21, 2026
8d5cfbd
fix(bots): a worker on a reused terminal names the items linked to th…
brennanb2025 Nov 21, 2026
54d6401
perf(bots): the reused-terminal walk reads each terminal once and reu…
brennanb2025 Nov 21, 2026
5979c26
perf(bots): a worker's terminal names the Dispatches that held it wit…
brennanb2025 Nov 21, 2026
e8a1896
fix(bots): a worker change reads the loaded items that link a worker …
brennanb2025 Nov 21, 2026
548ddf8
perf(bots): worker-linked items read a hundred a call; an unchanged f…
brennanb2025 Nov 21, 2026
5aefc7c
fix(bots): a whole read shows nothing until its depth lands, so Retry…
brennanb2025 Nov 21, 2026
3d8b8c9
fix(bots): named reads join their batches without a spread of a narro…
brennanb2025 Nov 21, 2026
57acebb
fix(bots): a failed page below a whole read's first page keeps that f…
brennanb2025 Nov 21, 2026
b4042a6
fix(bots): a whole read shows its fresh first page at once; a failed …
brennanb2025 Nov 21, 2026
4e585a0
test(bots): the list loader's call counts move to a performance contract
brennanb2025 Nov 21, 2026
5be7be5
test(bots): the loader's pages below the first ask for Closed rows alone
brennanb2025 Nov 21, 2026
f09321f
test(bots): the loader's perf contracts reach the depth pages they guard
brennanb2025 Nov 21, 2026
b43ab06
perf(bots): the phone bundle parses no item names it never reads; lis…
brennanb2025 Nov 21, 2026
0a8780c
perf(bots): a host read's reply that no view shows is not compared wi…
brennanb2025 Nov 21, 2026
3d409ce
fix(bots): re-reading the loaded Closed pages stops for a newer updat…
brennanb2025 Nov 21, 2026
bc43cee
fix(bots): a finished Closed re-read clears its stop mark and an unch…
brennanb2025 Nov 21, 2026
67957a1
fix(bots): a failed Show more's read lands without type casts
brennanb2025 Nov 21, 2026
8c3ad84
fix(bots): going on below a stopped read starts at the list's end whe…
brennanb2025 Nov 21, 2026
cd3a7ad
perf(bots): a named read takes no more calls than a whole read of the…
brennanb2025 Nov 21, 2026
671a3a5
fix(bots): a named read that would cost more calls than the loaded pa…
brennanb2025 Nov 21, 2026
0a889c9
fix(bots): a chat's list clears its failure once a read with a failed…
brennanb2025 Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion src/main/bots/bot-change-notices.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import {
followWorktreeLifecycleForBots
} from './bot-change-notices'
import { botChangeBotIds, botChangeConcerns } from '../../shared/bots/bot-change-scope'
import {
BOT_ITEMS_WORKER_LINKED,
botItemsNoticeParts
} from '../../shared/bots/bot-items-notice-parts'

vi.mock('../telemetry/client', () => ({ track: vi.fn() }))
vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) }))
Expand Down Expand Up @@ -53,7 +57,8 @@ describe('BotChangeNotices', () => {
const mixed = emit.mock.lastCall?.[0]
expect(mixed).toEqual({
kinds: ['workers', 'automations'],
kindBots: { workers: ['bot-a'] }
kindBots: { workers: ['bot-a'] },
namesItems: true
})
expect(botChangeConcerns(mixed, { botId: 'bot-b', kinds: ['workers'] })).toBe(false)
expect(botChangeConcerns(mixed, { botId: 'bot-a', kinds: ['workers'] })).toBe(true)
Expand Down Expand Up @@ -115,6 +120,29 @@ describe('BotChangeNotices', () => {
expect(emit.mock.calls).toEqual([[{ botIds: ['bot-a'], kinds: ['items'] }]])
})

it("names each bot's changed items while every change of them named them", () => {
const emit = vi.fn()
const notices = new BotChangeNotices({ emit, hasBots: () => true })
notices.changed({ botIds: ['bot-a'], kinds: ['items'], itemUids: { 'bot-a': ['i1'] } })
notices.changed({
botIds: ['bot-a', 'bot-b'],
kinds: ['items'],
itemUids: { 'bot-a': ['i2'], 'bot-b': ['i3'] }
})
notices.changed({ botIds: ['bot-b'], kinds: ['items'] })
vi.advanceTimersByTime(0)
const notice = emit.mock.calls[0]![0]
expect(notice.itemUids).toEqual({ 'bot-a': ['i1', 'i2'] })
expect(botItemsNoticeParts(notice, 'bot-a')).toEqual(['i1', 'i2'])
expect(botItemsNoticeParts(notice, 'bot-b')).toBeNull()
// A workers change reads the items that link a worker; from an older host, the whole list.
notices.changed({ botIds: ['bot-a'], kinds: ['workers'] })
vi.advanceTimersByTime(500)
const workers = emit.mock.calls[1]![0]
expect(botItemsNoticeParts(workers, 'bot-a')).toEqual([BOT_ITEMS_WORKER_LINKED])
expect(botItemsNoticeParts({ ...workers, namesItems: undefined }, 'bot-a')).toBeNull()
})

it('stays quiet on a host without bots', () => {
const emit = vi.fn()
new BotChangeNotices({ emit, hasBots: () => false }).changed()
Expand Down
3 changes: 2 additions & 1 deletion src/main/bots/bot-change-notices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { structuredAgentSessionIdOfTab } from '../../shared/agent-session/view/s
import {
addBotChange,
botChangeNotice,
pendingBotChanges,
type BotChangeKind,
type PendingBotChanges,
type BotChangeScope,
Expand Down Expand Up @@ -40,7 +41,7 @@ export class BotChangeNotices {
if (!this.deps.hasBots()) {
return
}
this.pending ??= new Map()
this.pending ??= pendingBotChanges()
addBotChange(this.pending, scope)
if (!this.timer) {
// The next tick, so one call's several writes go out as one notice.
Expand Down
9 changes: 8 additions & 1 deletion src/main/bots/bot-items-reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export type BotItemListQuery = {
chatIds?: readonly string[]
/** Only items linking this: `item list --link`. */
link?: { kind: BotItemLinkKind; ref: string }
/** Only these items; the counts stay the whole scope's. */
uids?: readonly string[]
limit: number
/** The last row of the previous page. */
cursor?: { at: number; number: number }
Expand Down Expand Up @@ -68,16 +70,21 @@ export class BotItemsReads extends BotItemsTables {
.all(...scopeArgs)) {
counts[statusOf(row.status)] = Number(row.count ?? 0)
}
// Named items are looked up by uid (CROSS JOIN keeps that order), not found in the bot's scan.
const from = query.uids
? 'json_each(?) AS named CROSS JOIN items WHERE items.uid = named.value AND'
: 'items WHERE'
const cursor = query.cursor
? ' AND (last_activity_at < ? OR (last_activity_at = ? AND number < ?))'
: ''
const items = this.db
.prepare(
`SELECT * FROM items WHERE ${scope}
`SELECT items.* FROM ${from} ${scope}
AND status IN (SELECT value FROM json_each(?))${cursor}
ORDER BY last_activity_at DESC, number DESC LIMIT ?`
)
.all(
...(query.uids ? [JSON.stringify(query.uids)] : []),
...scopeArgs,
JSON.stringify(query.statuses),
...(query.cursor ? [query.cursor.at, query.cursor.at, query.cursor.number] : []),
Expand Down
10 changes: 7 additions & 3 deletions src/main/bots/bot-items-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,14 +242,16 @@ describe('bot items host', () => {
await store.link(uid, [{ kind: 'dispatch', ref: 'ctx_1' }], owner)
await heartbeats(host, 'ctx_2', 1)

expect(fake.notified).toEqual([{ botIds: ['bot-a'], kinds: ['items'] }])
expect(fake.notified).toEqual([
{ botIds: ['bot-a'], kinds: ['items'], itemUids: { 'bot-a': [uid] } }
])
})

it('re-reads a linked item on a Dispatch change in a fresh runtime, before any write', async () => {
const first = fakeHost()
host = first.host
const links = [{ kind: 'dispatch' as const, ref: 'ctx_1' }]
await host.store().add(item({ status: 'working', links }), owner)
const { uid } = await host.store().add(item({ status: 'working', links }), owner)
host.dispose()
closeBotsDbStores()

Expand All @@ -258,7 +260,9 @@ describe('bot items host', () => {
host.store()
await heartbeats(host, 'ctx_1', 1)

expect(fake.notified).toEqual([{ botIds: ['bot-a'], kinds: ['items'] }])
expect(fake.notified).toEqual([
{ botIds: ['bot-a'], kinds: ['items'], itemUids: { 'bot-a': [uid] } }
])
})
})

Expand Down
27 changes: 17 additions & 10 deletions src/main/bots/bot-items-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ import {
} from '../../shared/bots/bot-items'
import { botItemsNeedingOwnerByBot } from '../../shared/bots/bot-item-groups'
import { botItemQuestionView } from '../../shared/bots/bot-item-ask'
import type { BotChangeScope, BotNeedsYouCounts } from '../../shared/bots/bot-change-scope'
import {
botItemsChangeScope,
type BotChangeScope,
type BotNeedsYouCounts
} from '../../shared/bots/bot-change-scope'
import { isOrcaSessionId } from '../../shared/agent-session/identity/orca-session-address'
import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths'
import { allLinks } from '../external-conversations/external-conversation-links'
Expand Down Expand Up @@ -166,9 +170,11 @@ export class BotItemsHost {
return { id, kind: source.kind, title: this.deps.chatTitle(id) ?? source.title, ...gone }
}

changed(botIds: readonly string[]): void {
if (botIds.length > 0) {
this.deps.notify({ botIds: [...new Set(botIds)], kinds: ['items'] })
/** These items changed: their bots' lists re-read just them. */
changed(items: readonly Pick<BotItemRecord, 'uid' | 'ownerBotId'>[]): void {
const scope = botItemsChangeScope(items)
if (scope) {
this.deps.notify(scope)
}
}

Expand Down Expand Up @@ -224,8 +230,9 @@ export class BotItemsHost {
return rows && { ...botItemsNeedingOwnerByBot(rows, this.deps.bots(), now), at: now }
}

/** Items as the wire shows them, links joined in one batch. */
async views(items: readonly BotItemRecord[]): Promise<BotItem[]> {
/** Items as the wire shows them, links joined in one batch; `summary` leaves out the long texts a
* list doesn't show. */
async views(items: readonly BotItemRecord[], summary = false): Promise<BotItem[]> {
if (items.length === 0) {
return []
}
Expand All @@ -246,15 +253,15 @@ export class BotItemsHost {
number: item.number,
owner: { botId: item.ownerBotId, name: nameOf(item.ownerBotId) },
title: item.title,
description: item.description,
doneMeans: item.doneMeans,
description: summary ? null : item.description,
doneMeans: summary ? null : item.doneMeans,
status: item.status,
chat: this.owningChat(item),
madeBy: madeBy
? { botId: madeBy.botId, name: nameOf(madeBy.botId), chatId: madeBy.chatId }
: null,
question: question ? botItemQuestionView(botItemEventId(question.id), question.data) : null,
closeNote: item.closeNote,
closeNote: summary ? null : item.closeNote,
links: (rows.links[item.uid] ?? []).map((link) =>
this.join.linkView(link, workers.get(link.ref))
),
Expand Down Expand Up @@ -291,7 +298,7 @@ export class BotItemsHost {
return
}
const rows = await store.viewRows([...new Set(uids)])
this.changed(rows.items.map((item) => item.ownerBotId))
this.changed(rows.items)
}
}

Expand Down
80 changes: 57 additions & 23 deletions src/main/runtime/rpc/methods/bots-items-owner-methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import {
BOT_ITEM_LIMITS,
BOT_ITEM_OPEN_STATUSES,
BOT_ITEM_STATUSES,
botItemEventId,
parseBotItemEventId
} from '../../../../shared/bots/bot-items'
Expand All @@ -24,6 +25,7 @@ import {
import { botChatTakingMail } from './bots-chats'
import type { BotItemOwnerActor } from '../../../bots/bot-items-input'
import type { BotItemRecord } from '../../../bots/bot-items-schema'
import type { BotItemsRemote } from '../../../bots/bot-items-ops'
import { defineMethod, type RpcContext } from '../core'
import { ownerOnly } from './bots-caller-gates'
import { parseCursor, resolveItem } from './bots-items-write-support'
Expand All @@ -38,6 +40,31 @@ function ownerActor(context: RpcContext): BotItemOwnerActor {
: { kind: 'owner' }
}

/** Every open item of the bot (or its chats), however many, read a page at a time. */
async function allOpenItems(
store: BotItemsRemote,
botId: string,
chat: { chatIds?: readonly string[] }
): Promise<BotItemRecord[]> {
const open: BotItemRecord[] = []
let cursor: { at: number; number: number } | undefined
for (;;) {
const page = await store.list({
botId,
...chat,
statuses: BOT_ITEM_OPEN_STATUSES,
limit: BOT_ITEM_LIMITS.listPageMax + 1,
...(cursor ? { cursor } : {})
})
open.push(...page.items.slice(0, BOT_ITEM_LIMITS.listPageMax))
const last = page.items[BOT_ITEM_LIMITS.listPageMax - 1]
if (page.items.length <= BOT_ITEM_LIMITS.listPageMax || !last) {
return open
}
cursor = { at: last.lastActivityAt, number: last.number }
}
}

const LIST = defineMethod({
name: 'bots.items.owner.list',
permission: 'workspace',
Expand All @@ -49,41 +76,48 @@ const LIST = defineMethod({
// An older client names one chat; a group's panel names its rooms' member sessions.
const chatIds = params.chatIds ?? (params.chatId !== undefined ? [params.chatId] : undefined)
const chat = chatIds ? { chatIds } : {}
// Every open item, however many, then closed ones a page at a time.
const open: BotItemRecord[] = []
let cursor: { at: number; number: number } | undefined
for (;;) {
const page = await store.list({
// Read after the rows, so a mark another device moved meanwhile is the one sent.
const seenEventId = (): string =>
botItemEventId(
context.runtime.bots.list().find((bot) => bot.id === params.botId)?.itemsSeen ?? 0
)
if (params.uids) {
// What a notice named: those items (an absent one is deleted or out of scope), with the counts.
const named = await store.list({
botId: params.botId,
...chat,
statuses: BOT_ITEM_OPEN_STATUSES,
limit: BOT_ITEM_LIMITS.listPageMax + 1,
...(cursor ? { cursor } : {})
statuses: BOT_ITEM_STATUSES,
uids: params.uids,
limit: params.uids.length
})
open.push(...page.items.slice(0, BOT_ITEM_LIMITS.listPageMax))
const last = page.items[BOT_ITEM_LIMITS.listPageMax - 1]
if (page.items.length <= BOT_ITEM_LIMITS.listPageMax || !last) {
break
return {
items: await botItems.views(named.items, params.summary),
counts: named.counts,
seenEventId: seenEventId()
}
cursor = { at: last.lastActivityAt, number: last.number }
}
// Every open item, then closed ones a page at a time; a Closed page asked alone skips the open.
const closedCursor = parseCursor(params.closedCursor)
const open =
closedCursor && params.closedOnly ? [] : await allOpenItems(store, params.botId, chat)
const pageSize = params.closedLimit ?? BOT_ITEM_LIMITS.listPage
const closed = await store.list({
botId: params.botId,
...chat,
statuses: ['done', 'canceled'],
limit: BOT_ITEM_LIMITS.listPage + 1,
limit: pageSize + 1,
...(closedCursor ? { cursor: closedCursor } : {})
})
const closedRows = closed.items.slice(0, BOT_ITEM_LIMITS.listPage)
const closedRows = closed.items.slice(0, pageSize)
const lastClosed = closedRows.at(-1)
// An item closed between the two reads is in both: once, as Closed.
const closedUids = new Set(closedRows.map((item) => item.uid))
const stillOpen = open.filter((item) => !closedUids.has(item.uid))
return {
items: await botItems.views([...open, ...closedRows]),
items: await botItems.views([...stillOpen, ...closedRows], params.summary),
counts: closed.counts,
seenEventId: botItemEventId(
context.runtime.bots.list().find((bot) => bot.id === params.botId)?.itemsSeen ?? 0
),
...(closed.items.length > BOT_ITEM_LIMITS.listPage && lastClosed
seenEventId: seenEventId(),
...(closed.items.length > pageSize && lastClosed
? { nextClosedCursor: `${lastClosed.lastActivityAt}:${lastClosed.number}` }
: {})
}
Expand Down Expand Up @@ -162,7 +196,7 @@ const COMMENT = defineMethod({
undefined,
params.requestId
)
botItems.changed([item.ownerBotId])
botItems.changed([item])
// The comment is stored and its mail owed: the reply never waits on the chat taking it.
void botItems
.sendOwedMail()
Expand Down Expand Up @@ -190,7 +224,7 @@ const STATUS = defineMethod({
},
actor
)
botItems.changed(items.map((item) => item.ownerBotId))
botItems.changed(items)
await botItems.sendOwedMail()
return {
items: result.items.map((entry) => ({
Expand Down Expand Up @@ -221,7 +255,7 @@ const SNOOZE = defineMethod({
},
actor
)
botItems.changed(items.map((item) => item.ownerBotId))
botItems.changed(items)
return {
items: result.items.map((entry) => ({
uid: entry.uid,
Expand Down
2 changes: 1 addition & 1 deletion src/main/runtime/rpc/methods/bots-items-write-support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export async function writeResult(
if (!record) {
throw new BotItemError('not_found', 'The item is gone.')
}
runtime.botItems.changed([record.ownerBotId])
runtime.botItems.changed([record])
const [item] = await runtime.botItems.views([record])
if (outcome.eventId !== null) {
await noteBotItemWrite(store, writer.sessionId, record, outcome.eventId, item!.links)
Expand Down
Loading
Loading