Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
38 changes: 38 additions & 0 deletions src/renderer/src/lib/bots-changed-window-event.performance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// @vitest-environment happy-dom
import { afterEach, expect, it } from 'vitest'
import { emitBotsChangedWindowEvent, onBotsChanged } from './bots-changed-window-event'
import { botGroupRoomConcerned, type BotChangeScope } from '../../../shared/bots/bot-change-scope'

// A room-scoped groups notice (#47523) reaches every bot view in the window. Guards that the notice is
// read once and shared, not copied per listener, and that only the named rooms' views re-read.

const stops: (() => void)[] = []
afterEach(() => stops.splice(0).forEach((stop) => stop()))

function dispatch(listeners: number, named: number) {
const scopes: (BotChangeScope | undefined)[] = []
let reads = 0
for (let index = 0; index < listeners; index += 1) {
stops.push(
onBotsChanged(
(_host, scope) => {
scopes.push(scope)
if (botGroupRoomConcerned(scope, `room-${index}`)) {
reads += 1
}
},
'local',
{ kinds: ['groups'] }
)
)
}
const groupIds = Array.from({ length: named }, (_, index) => `room-${index}`)
emitBotsChangedWindowEvent('local', { kinds: ['groups'], groupIds })
return { scopes: new Set(scopes).size, heard: scopes.length, reads }
}

it('reads a notice once for every listener and re-reads only the rooms it names', () => {
expect(dispatch(100, 1)).toEqual({ scopes: 1, heard: 100, reads: 1 })
stops.splice(0).forEach((stop) => stop())
expect(dispatch(1_000, 10)).toEqual({ scopes: 1, heard: 1_000, reads: 10 })
})
19 changes: 15 additions & 4 deletions src/renderer/src/lib/bots-changed-window-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ export function emitBotsChangedWindowEvent(hostId: ExecutionHostId, scope?: BotC
)
}

// One read per notice, shared by every listener the window event reaches.
type ReceivedDetail = { readonly scope?: unknown }
const readScopes = new WeakMap<ReceivedDetail, BotChangeScope | undefined>()

function readDetailScope(detail: ReceivedDetail): BotChangeScope | undefined {
if (!readScopes.has(detail)) {
readScopes.set(
detail,
'scope' in detail ? readBotChangeScopeWithItems(detail.scope) : undefined
)
}
return readScopes.get(detail)
}

/**
* Hears each host's bots change. With `hostId`, only that host's changes call `listener`, so a
* view of one bot or one host never re-reads on another host's change; with `interest`, only a
Expand All @@ -46,10 +60,7 @@ export function onBotsChanged(
if (!changed || (hostId !== undefined && changed !== hostId)) {
return
}
const scope =
detail && typeof detail === 'object' && 'scope' in detail
? readBotChangeScopeWithItems(detail.scope)
: undefined
const scope = detail && typeof detail === 'object' ? readDetailScope(detail) : undefined
if (!interest || botChangeConcerns(scope, interest)) {
listener(changed, scope)
}
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([])
})
Loading
Loading