Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { ConnectorWorkLink } from '../../shared/connector-work-link-contrac
import type { ExternalConversationLink } from '../../shared/connectors/external-conversation-link'
import { chatPaneKey } from './external-conversation-chat'
import { ChatTurns } from './external-conversation-chat-turns'
import { ChatDeliveries } from './external-conversation-chat-delivery'
import type { AgentJournalRenderItem } from '../../shared/agent-session/journal/agent-session-journal-types'
import type { ConversationEvent } from './external-conversation-events'

const SESSION = 'session-1'
Expand Down Expand Up @@ -284,6 +286,45 @@ describe('questions of a bot turn typed in Orca (10:27Z regression)', () => {
expect(h.events).toEqual([])
})

const steered = {
account: 'a',
conversation: { source: 'slack', externalId: 'T1:D7:U9' },
deliveryId: 'd1'
}
it.each([
['first adopted', false, 'success', [], 'someone_else'],
['first adopted', false, 'failure', [steered], undefined],
['first adopted', false, 'success', [steered], undefined],
['re-adopted after a restart', true, 'success', [steered], undefined]
] as const)(
'reads whom a turn %s (restarted: %s, %s, stamps %j) acts for from its journal',
async (_, restarted, outcome, stamps, turnFor) => {
// The restart forgot any delivery steered in; only the journal's stamps still show it.
const h = mailStartedBot('bot-chat')
let turns = h.create()
turns.observe(h.link.paneKey)
turns.news({ kind: 'prompt', sessionId: SESSION })
if (restarted) {
h.restart()
turns = h.create()
expect(turns.hears(h.link)).toBe(true)
turns.adopt(h.link.paneKey)
}
turns.news({
kind: 'turn-ended',
sessionId: SESSION,
outcome,
at: 600,
readTurn: async () => ({ ...(await h.end('Done.')()), stamps: [...stamps] })
})
await vi.waitFor(() =>
expect(h.events.at(-1)).toMatchObject({ kind: 'turn-ended', origin: 'local' })
)
const ended = h.events.at(-1)
expect(ended?.kind === 'turn-ended' ? ended.turnFor : null).toBe(turnFor)
}
)

it('keeps a relinked conversation’s prompt restricted even when its turn has a delivery stamp', () => {
const h = mailStartedBot('bot-chat')
h.relink()
Expand Down Expand Up @@ -393,3 +434,81 @@ describe('an Orca-typed turn in a chat that posts to its Slack thread', () => {
expect(events.some((event) => event.kind === 'turn-ended' && event.mirror)).toBe(false)
})
})

describe('a turn its conversation heard across a host restart', () => {
const link: ExternalConversationLink = {
source: 'slack',
externalId: 'T1:C9:1792.9:U5',
sessionId: SESSION,
agent: 'claude',
paneKey: chatPaneKey(SESSION),
bot: { kind: 'bot', botId: 'b1' },
createdAt: 0
}
const queuedDelivery = {
kind: 'message' as const,
role: 'user' as const,
blocks: [],
origin: 'connector' as const,
connectorConversation: { source: 'slack', externalId: link.externalId }
}

async function turnForAfterRestart(opener: AgentJournalRenderItem['body']) {
// The restarted host remembers no delivery; only the chat's journal survived.
const deliveries = new ChatDeliveries(() => {})
const events: ConversationEvent[] = []
const turns = new ChatTurns({
promptsAudience: () => true,
turnOpener: () => null,
keepAdoptedTurn: () => {},
readHookRow: () => ({
paneKey: chatPaneKey(SESSION),
structuredHost: 'owned',
state: 'working',
tabId: 'tab',
worktreeId: 'wt',
connectionId: null,
prompt: '',
agentType: 'claude',
receivedAt: 3,
stateStartedAt: 3
}),
pendingPrompt: () => null,
chatTurnOrigin: (sessionId, turnAt) => deliveries.origin(sessionId, turnAt),
chatTurnDelivered: (sessionId) => deliveries.pending(sessionId),
chatTurnDelivery: (sessionId, turnAt) => deliveries.started(sessionId, turnAt),
chatTurnWaiting: (sessionId) => deliveries.waiting(sessionId),
runningTurnReported: () => false,
workLinks: async () => [],
workerActivities: async () => null,
actsForOf: () => 'owner',
linkedFor: () => ({ link, workspace: { worktreeId: 'wt', sshHostId: null } }),
emit: (event) => events.push(event),
setTimer: () => ({ cancel: () => {} }),
now: () => 0
})
// The watch's snapshot adopts the turn the queued message started.
turns.adopt(link.paneKey)
turns.news({
kind: 'turn-ended',
sessionId: SESSION,
outcome: 'success',
at: 5,
readTurn: async () => ({
lastAssistantMessage: 'Done.',
opener: { itemId: 'm1', revision: 0, sequence: 1, observedAt: 1, body: opener }
})
})
await vi.waitFor(() => expect(events).toHaveLength(1))
const [ended] = events
return ended?.kind === 'turn-ended' ? ended.turnFor : null
}

it('leaves a queued delivery’s turn to the cloud, never acting for the owner', async () => {
expect(await turnForAfterRestart(queuedDelivery)).toBeUndefined()
})

it('still says the owner for a turn the journal shows the owner typed', async () => {
expect(await turnForAfterRestart({ kind: 'message', role: 'user', blocks: [] })).toBe('owner')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -269,16 +269,14 @@ export class ChatTurns {
}
return
}
// The turn's identity is fixed now; its message is read from the journal after.
// Read in the same tick as its end's turn id, so both name one turn.
// Read with the end's turn id in one tick so both name one turn; its message is read later.
const origin = this.deps.chatTurnOrigin(news.sessionId, this.turnOf(paneKey))
const ended = {
kind: 'turn-ended' as const,
...at,
turnId: this.turnOf(paneKey),
stopReason: news.outcome,
at: news.at,
...chatTurnFor(origin, this.deps.actsForOf?.(news.sessionId))
at: news.at
}
this.startedAt.delete(paneKey)
const heard = this.told.delete(paneKey) || origin === 'delivery'
Expand All @@ -291,6 +289,7 @@ export class ChatTurns {
news,
agent: linked.link.agent,
emit: this.deps.emit,
turnFor: chatTurnFor(origin, this.deps.actsForOf?.(news.sessionId)),
workersChecked: () => this.workers.check(paneKey, 'turn-ended'),
current: () => generation === this.generation
}
Expand Down Expand Up @@ -335,6 +334,7 @@ export class ChatTurns {
// Owner words steered in and posted to the thread go before the answer.
;(mirrored ? mirrored.release : this.deps.emit)({
...ended,
...end.turnFor(turn),
origin: reported ? 'delivery' : origin,
...(message && !quiet(message) ? { lastAssistantMessage: message } : {}),
...(news.outcome === 'failure'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ it("keeps a failed turn's reason on its state-only end, which the cloud stores f
},
agent: 'claude',
emit,
turnFor: () => ({}),
workersChecked: async () => undefined,
current: () => true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export type ChatTurnEnd = {
news: Extract<ChatNews, { kind: 'turn-ended' }>
agent: NativeChatAgent
emit: (event: ConversationEvent) => void
/** Whom the turn acts for, once its journal is read. */
turnFor: (turn: EndedChatTurn) => Pick<ChatTurnEnd['ended'], 'turnFor'>
/** The turn's workers are read, so its end never reads done while they run. */
workersChecked: () => Promise<unknown>
/** Still the same signed-in account: false after a reset, so the end reaches no one. */
Expand All @@ -26,7 +28,7 @@ export type ChatTurnEnd = {
/** An adopted turn's end: how it went, never what it said or the links its work opened. */
export function endAdoptedTurn(end: ChatTurnEnd, promptsAudience: () => boolean): void {
const failed = end.news.outcome === 'failure'
void (failed ? end.news.readTurn() : Promise.resolve(null)).then(async (turn) => {
void end.news.readTurn().then(async (turn) => {
if (!end.current()) {
return
}
Expand All @@ -36,8 +38,9 @@ export function endAdoptedTurn(end: ChatTurnEnd, promptsAudience: () => boolean)
}
end.emit({
...end.ended,
...end.turnFor(turn),
origin: 'local',
...(failed ? { failure: connectorFailure(turn?.failure, end.agent) } : {})
...(failed ? { failure: connectorFailure(turn.failure, end.agent) } : {})
})
})
}
Expand All @@ -56,6 +59,7 @@ export function endMirroredTurn(end: ChatTurnEnd, mirrored: SlackMirrorTurn): vo
const message = read.lastAssistantMessage
mirrored.release({
...end.ended,
...end.turnFor(read),
origin: 'local',
mirror: true,
...(message && !isQuietBotResult(message) ? { lastAssistantMessage: message } : {}),
Expand Down Expand Up @@ -117,7 +121,7 @@ export async function endRepliedTurn(
await end.workersChecked()
if (end.current()) {
// The cloud keeps the thread's failure from whichever of this and the reply lands last.
end.emit({ ...end.ended, stateOnly: true, ...failure })
end.emit({ ...end.ended, ...end.turnFor(turn), stateOnly: true, ...failure })
}
return true
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
ConnectorTurnFor,
ConnectorTurnOrigin
} from '../../shared/connectors/connector-cloud-contract'
import type { EndedChatTurn } from './external-conversation-ended-turn'

/** The lead agent's own state; background work can keep the combined row working across turns. */
export function leadOf(row: AgentStatusIpcPayload): {
Expand Down Expand Up @@ -40,10 +41,26 @@ export function conversationWorking(row: AgentStatusIpcPayload | null): boolean

/** Whom an ended chat turn acts for, as its final post tells Orca Cloud: none for a delivery's turn,
* whose person the cloud reads from its own record; else the owner only when Orca recorded that the
* conversation acts for them (bot-turn-for.ts says why). */
* conversation acts for them (bot-turn-for.ts says why). A delivery is remembered only until a
* restart, so a "local" turn also needs its journal to show Orca began it; unproven, it says none. */
export function chatTurnFor(
origin: ConnectorTurnOrigin,
actsFor: ConnectorActsFor | undefined
): { turnFor?: ConnectorTurnFor } {
return origin === 'delivery' ? {} : { turnFor: actsFor === 'owner' ? 'owner' : 'someone_else' }
): (turn: Pick<EndedChatTurn, 'opener' | 'stamps'>) => { turnFor?: ConnectorTurnFor } {
return (turn) =>
origin === 'delivery' || !journalShowsLocalTurn(turn)
? {}
: { turnFor: actsFor === 'owner' ? 'owner' : 'someone_else' }
}

/** A message no connector sent opened the turn, and it answered no delivery. */
function journalShowsLocalTurn({ opener, stamps }: Pick<EndedChatTurn, 'opener' | 'stamps'>) {
const body = opener?.body
return (
body?.kind === 'message' &&
body.origin !== 'connector' &&
!body.connectorDelivery &&
!body.connectorConversation &&
!stamps?.length
)
}
Loading