Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion mobile/src/bots/use-mobile-bot-group-transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { startHostBotRefresh } from './host-bot-refresh'
import {
botChangeBotIds,
botChangeConcerns,
botGroupRoomConcerned,
type BotChangeKind,
type BotChangeScope
} from '../../../src/shared/bots/bot-change-scope'
Expand Down Expand Up @@ -139,7 +140,12 @@ export function useMobileBotGroupTranscript(
if (counts) {
setNeedsYou((last) => (sameCounts(last, counts) ? last : counts))
}
if (!botChangeConcerns(changed, { kinds: ROOM_KINDS })) {
// A groups change naming other rooms leaves this one as it is.
const room =
botChangeConcerns(changed, { kinds: ['bot'] }) ||
(botChangeConcerns(changed, { kinds: ['groups'] }) &&
botGroupRoomConcerned(changed, groupId))
if (!room) {
return
}
const current = ++request
Expand Down
9 changes: 5 additions & 4 deletions src/main/bots/bot-change-notices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ export type BotPaneFacts = {
botOfWorkspace: (worktreeId: string) => string | null
/** The bot whose chat, worker or run a pane is. */
botOfPane: (paneKey: string) => string | null
/** Whether the pane is a member's in a bot group room. */
inGroupRoom: (sessionId: string) => boolean
/** The bot group room whose member the pane is, by group id; null when it is none's. */
groupRoomOf: (sessionId: string) => string | null
/** A Dispatch's worker pane. */
workerPane: (paneKey: string) => boolean
/** Reads the chats of bots never read yet; false when one can't be read, so a worker pane may be an
Expand Down Expand Up @@ -137,8 +137,9 @@ export function botPhaseChangeScopes(
}
const tabId = parsePaneKey(change.paneKey)?.tabId
const sessionId = tabId ? structuredAgentSessionIdOfTab(tabId) : null
if (sessionId && facts.inGroupRoom(sessionId)) {
scopes.push({ kinds: ['groups'] })
const groupId = sessionId ? facts.groupRoomOf(sessionId) : null
if (groupId) {
scopes.push({ kinds: ['groups'], groupIds: [groupId] })
}
return scopes
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/bots/bot-group-automation-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export async function sendBotGroupAutomationRun(
return stored
}
)
groups.changed()
groups.changed(message.groupId)
const [turn] = message.turns
const fingerprint = turn ? await deliverTurn(groups, message, turn, run) : undefined
if (!turn || fingerprint === undefined) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/bots/bot-group-dead-mail-turns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ async function settle(
: item
)
})
groups.changed()
groups.changed(current.groupId)
return false
}

Expand Down
6 changes: 3 additions & 3 deletions src/main/bots/bot-group-delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export async function sendBotGroupMessage(
})
// Marks its asks in flight before any reader can see the post.
void deliverRemoteAsks(groups, message, remoteBodies)
groups.changed()
groups.changed(message.groupId)
for (const turn of message.turns) {
void deliverTurn(groups, message, turn)
}
Expand Down Expand Up @@ -166,7 +166,7 @@ export function assertGroupQueuedMessageAllowed(
assertTurnActive(groups, message, turn)
} catch (error) {
recordTurnError(groups, message.id, operationId, error)
groups.changed()
groups.changed(message.groupId)
throw error
}
}
Expand Down Expand Up @@ -273,7 +273,7 @@ export async function deliverTurn(
} finally {
groups.store.delivered([turn.operationId])
groups.deliveries.delete(turn.operationId)
groups.changed()
groups.changed(message.groupId)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/bots/bot-group-latest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export async function noteBotGroupMemberReply(
{ after, reply }
)
if (kept) {
groups.changed()
groups.changed(owner.group.id)
}
await handOffGroupMentions(groups, message, turn, { full: finished.full, saved: finished.text })
}
2 changes: 1 addition & 1 deletion src/main/bots/bot-group-mention-handoffs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export async function handOffGroupMentions(
)
}
})
groups.changed()
groups.changed(groupId)
return stored
})
for (const line of woken) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/bots/bot-group-peer-answer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ export function saveGroupPeerAnswer(
: turn
)
})
groups.changed()
groups.changed(message.groupId)
}
4 changes: 2 additions & 2 deletions src/main/bots/bot-group-peer-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ export function reserveGroupMailTurn(
}
if (line) {
groups.store.retarget(id, input.operationId)
groups.changed()
groups.changed(group.id)
return
}
const bot = groups.runtime.bots.list().find((bot) => bot.id === member.botId)
Expand Down Expand Up @@ -232,7 +232,7 @@ export function reserveGroupMailTurn(
}
]
})
groups.changed()
groups.changed(group.id)
}

/** The group operation a member is running now (as it starts a worker or answers a peer), read
Expand Down
4 changes: 2 additions & 2 deletions src/main/bots/bot-group-remote-answers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export function remoteRoomMailArrived(groups: BotGroupRuntime, groupId: string):
.prepare('SELECT id, thread_id FROM messages WHERE to_handle = ? AND read = 0')
.all(botGroupRoomMailAddress(groupId))
if (rows.length === 0) {
groups.changed()
groups.changed(groupId)
return
}
if (!db.db.prepare('SELECT 1 FROM bot_groups WHERE id = ?').get(groupId)) {
Expand Down Expand Up @@ -231,7 +231,7 @@ export function remoteRoomMailArrived(groups: BotGroupRuntime, groupId: string):
} catch (error) {
console.warn('[bot-groups] could not read a remote member answer', error)
}
groups.changed()
groups.changed(groupId)
}

/** At startup: settle room mail that arrived while this build wasn't running, as if it had just
Expand Down
2 changes: 1 addition & 1 deletion src/main/bots/bot-group-remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ export async function deliverRemoteAsks(
for (const ask of asks) {
sending.delete(ask.requestId)
}
groups.changed()
groups.changed(message.groupId)
}
}

Expand Down
5 changes: 3 additions & 2 deletions src/main/bots/bot-group-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,9 @@ export class BotGroupRuntime {
this.store = new BotGroupStore(runtime.getOrchestrationDb().db)
}

changed(): void {
this.runtime.notifyBotGroupsChanged()
/** Readers re-read; open rooms of `groupId` only, when it is given (a change inside one room). */
changed(groupId?: string): void {
this.runtime.notifyBotGroupsChanged(groupId === undefined ? undefined : [groupId])
}

create = (input: z.infer<typeof BotGroupCreate>) => createBotGroup(this, input)
Expand Down
2 changes: 1 addition & 1 deletion src/main/bots/bot-group-stop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function stopBotGroup(
}
: { members })
})
groups.changed()
groups.changed(group.id)
const host = await requireStructuredHost(groups.runtime)
return Promise.all(
previous.members.filter(stopping).map(({ sessionId }) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithTer
const dispatchId = this.getAgentStatusOrchestrationContextForPaneKey(paneKey)?.dispatchId
return dispatchId ? (index?.botOfDispatch(dispatchId) ?? null) : null
},
inGroupRoom: (sessionId) => this.botSessions.groupRoomOf(sessionId) !== null,
groupRoomOf: (sessionId) => this.botSessions.groupRoomOf(sessionId)?.group.id ?? null,
workerPane: (paneKey) =>
this.getAgentStatusOrchestrationContextForPaneKey(paneKey) !== undefined,
readEveryBot: () => this.botChatTreeIndex?.readEveryBot() !== false
Expand Down
7 changes: 4 additions & 3 deletions src/main/runtime/orca-runtime-bots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,9 +353,10 @@ export abstract class OrcaRuntimeWithBots extends OrcaRuntimeWithLinearCommands
this.botChangeNotices.changed({ kinds: ['access'] })
}

/** A group's room, members or latest message changed; windows and phones re-read the groups. */
notifyBotGroupsChanged(): void {
this.botChangeNotices.changed({ kinds: ['groups'] })
/** A group's room, members or latest message changed; windows and phones re-read the groups, and
* open rooms of `groupIds` (every room when absent) re-read their page. */
notifyBotGroupsChanged(groupIds?: readonly string[]): void {
this.botChangeNotices.changed({ kinds: ['groups'], ...(groupIds ? { groupIds } : {}) })
}

/** A paired server's worker verdicts changed: their bots re-read (all, if a bot can't be read). */
Expand Down
14 changes: 12 additions & 2 deletions src/renderer/src/components/bots/use-bot-group-transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect, useReducer } from 'react'
import { onBotsChanged } from '@/lib/bots-changed-window-event'
import type { BotRef } from '@/lib/bot-hosts'
import { callBotGroupRpc } from '@/lib/bot-group-rpc'
import { botGroupRoomConcerned } from '../../../../shared/bots/bot-change-scope'
import {
reduceBotGroupTranscript,
type BotGroupTranscript
Expand All @@ -19,7 +20,8 @@ function readPage(
})
}

/** The room's transcript while visible: re-read on every host bots change, older pages on request.
/** The room's transcript while visible: re-read on each host groups change that names this room (or
* names none), older pages on request.
* A thread's room is read when `threadId` is set. */
export function useBotGroupTranscript(
group: BotRef | undefined,
Expand Down Expand Up @@ -49,7 +51,15 @@ export function useBotGroupTranscript(
.catch((error: unknown) => !closed && setError(String(error)))
}
read()
const stopListening = onBotsChanged(read, hostId, { kinds: ['groups'] })
const stopListening = onBotsChanged(
(_host, scope) => {
if (botGroupRoomConcerned(scope, groupId)) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
read()
}
},
hostId,
{ kinds: ['groups'] }
)
return () => {
closed = true
stopListening()
Expand Down
43 changes: 43 additions & 0 deletions src/shared/bots/bot-change-scope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { expect, it } from 'vitest'
import {
addBotChange,
botChangeNotice,
botGroupRoomConcerned,
pendingBotChanges,
readBotChangeScope,
type BotChangeScope
} from './bot-change-scope'

// One quiet window's notice, as it leaves the host and as a reader reads it back.
function notice(...changes: BotChangeScope[]): BotChangeScope | undefined {
const pending = pendingBotChanges()
changes.forEach((change) => addBotChange(pending, change))
return readBotChangeScope(JSON.parse(JSON.stringify(botChangeNotice(pending))))
}

const rooms = (scope: BotChangeScope | undefined) =>
['room-a', 'room-b', 'room-c'].filter((id) => botGroupRoomConcerned(scope, id))

it('re-reads only the rooms a window named, and every room once a change names none', () => {
const named = notice(
{ kinds: ['groups'], groupIds: ['room-a'] },
{ kinds: ['groups'], groupIds: ['room-b'] },
{ botIds: ['bot-1'], kinds: ['status'] }
)
expect(rooms(named)).toEqual(['room-a', 'room-b'])
// A groups change that names no room (a roster edit, an older caller) reaches every room.
expect(rooms(notice({ kinds: ['groups'], groupIds: ['room-a'] }, { kinds: ['groups'] }))).toEqual(
['room-a', 'room-b', 'room-c']
)
expect(rooms(notice({ kinds: ['groups'] }, { kinds: ['groups'], groupIds: ['room-a'] }))).toEqual(
['room-a', 'room-b', 'room-c']
)
// A change of every kind, an older host's bare notice, and a kind this build doesn't know all reach
// every room; another kind alone reaches none.
expect(rooms(notice({ kinds: ['groups'], groupIds: ['room-a'] }, {}))).toHaveLength(3)
expect(rooms(undefined)).toHaveLength(3)
expect(rooms(readBotChangeScope({ kinds: ['future-kind'], groupIds: ['room-a'] }))).toHaveLength(
3
)
expect(rooms(notice({ botIds: ['bot-1'], kinds: ['status'] }))).toEqual([])
})
39 changes: 37 additions & 2 deletions src/shared/bots/bot-change-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ export type BotChangeScope = {
/** The host reads a list's items by uid, so a `workers` change can read just the loaded items that
* link a worker. Absent: an older host, whose lists read whole. */
namesItems?: true
/** A `groups` change's rooms, by group id: an open room re-reads only when its group is named. Absent
* (and an older host's notice): every room re-reads. */
groupIds?: readonly string[]
}

/** The notice of these changed items, by bot; null for none. */
Expand Down Expand Up @@ -139,6 +142,8 @@ const ANY_KIND = '*'
export type PendingBotChanges = {
kinds: Map<BotChangeKind | typeof ANY_KIND, Set<string> | null>
itemUids: Map<string, Set<string> | null>
/** The rooms a `groups` change named; null once one named none (every room), absent before any. */
groupIds?: Set<string> | null
}

export function pendingBotChanges(): PendingBotChanges {
Expand All @@ -151,6 +156,14 @@ export const BOT_CHANGE_ITEM_UIDS_MAX = 100
export function addBotChange(pending: PendingBotChanges, scope: BotChangeScope): void {
const kinds: readonly (BotChangeKind | typeof ANY_KIND)[] =
scope.kinds && scope.kinds.length > 0 ? scope.kinds : [ANY_KIND]
if (kinds.includes('groups') || kinds.includes(ANY_KIND)) {
if (!scope.groupIds || pending.groupIds === null) {
pending.groupIds = null
} else {
pending.groupIds ??= new Set()
scope.groupIds.forEach((id) => pending.groupIds?.add(id))
}
}
for (const kind of kinds) {
const bots = pending.kinds.get(kind)
if (!scope.botIds) {
Expand Down Expand Up @@ -187,6 +200,7 @@ export function botChangeNotice(pending: PendingBotChanges): BotChangeScope {
if (pending.kinds.has(ANY_KIND)) {
return botIds ? { botIds } : {}
}
const groupIds = pending.kinds.has('groups') && pending.groupIds ? [...pending.groupIds] : null
const kinds = entries.map(([kind]) => kind).filter((kind) => kind !== ANY_KIND)
const scoped = entries.flatMap(([kind, bots]) =>
kind !== ANY_KIND && bots ? [[kind, [...bots]] as const] : []
Expand All @@ -204,8 +218,24 @@ export function botChangeNotice(pending: PendingBotChanges): BotChangeScope {
kinds,
...(sameBots || scoped.length === 0 ? {} : { kindBots: Object.fromEntries(scoped) }),
...(named.length > 0 ? { itemUids: Object.fromEntries(named) } : {}),
...(pending.kinds.has('workers') ? { namesItems: true as const } : {})
...(pending.kinds.has('workers') ? { namesItems: true as const } : {}),
...(groupIds ? { groupIds } : {})
}
}

/** Whether an open room of `groupId` re-reads for this notice: a `groups` change (or one of any or an
* unknown kind) that names its group or names none. */
export function botGroupRoomConcerned(scope: BotChangeScope | undefined, groupId: string): boolean {
const known = new Set<string>(BOT_CHANGE_KINDS)
const kinds = scope?.kinds ?? []
// A kind this build does not know counts, as in botChangeConcerns.
if (kinds.some((kind) => !known.has(kind))) {
return true
}
if (kinds.length > 0 && !kinds.includes('groups')) {
return false
}
return scope?.groupIds?.includes(groupId) ?? true
}

/** The scope a runtime event carries, read loosely (a peer of another version may send anything). */
Expand All @@ -223,12 +253,17 @@ export function readBotChangeScope(event: unknown): BotChangeScope | undefined {
: undefined
const kindBots = 'kindBots' in event ? readStringLists(event.kindBots) : undefined
const needsYou = 'needsYou' in event ? readBotNeedsYouCounts(event.needsYou) : undefined
const groupIds =
'groupIds' in event && Array.isArray(event.groupIds)
? event.groupIds.filter((id): id is string => typeof id === 'string')
: undefined
return botIds || kinds
? {
...(botIds ? { botIds } : {}),
...(kinds ? { kinds } : {}),
...(kindBots ? { kindBots } : {}),
...(needsYou ? { needsYou } : {})
...(needsYou ? { needsYou } : {}),
...(groupIds ? { groupIds } : {})
}
: undefined
}
Expand Down
Loading