mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Preserve goal attachment ownership and read finite mailbox work
This commit is contained in:
@@ -100,6 +100,7 @@ function publicJournalSqlValue(
|
||||
operation === 'dispatch' ||
|
||||
operation === 'lifecycle' ||
|
||||
operation === 'tombstone' ||
|
||||
operation === 'goal-withdraw' ||
|
||||
operation === 'context-clear' ||
|
||||
operation === 'context-rewind' ||
|
||||
operation === 'epoch-replace' ||
|
||||
|
||||
@@ -11,7 +11,7 @@ import { applyJournalDomainQueueCommand } from './journal-domain-queue-command'
|
||||
import { applyJournalDomainInputRecovery } from './journal-domain-input-recovery'
|
||||
import { applyJournalDomainCommandTurn } from './journal-domain-command-turn'
|
||||
import { applyJournalDomainContextCommand } from './journal-domain-context-command'
|
||||
import { applyJournalDomainTombstone } from './journal-domain-item-removal'
|
||||
import { applyJournalSqlTombstoneCommand } from './journal-sql-tombstone-command'
|
||||
import { applyJournalDomainGenerationSettlement } from './journal-domain-generation-settlement'
|
||||
import { applyJournalDomainLifecycleOperation } from './journal-domain-taken-stop'
|
||||
import { applyJournalDomainPromptMutation } from './journal-domain-prompt-mutation'
|
||||
@@ -154,18 +154,14 @@ export class JournalSqlCommand {
|
||||
[...result.items.map((item) => item.itemId), ...result.removedItemIds]
|
||||
)
|
||||
}
|
||||
case 'tombstone': {
|
||||
const result = applyJournalDomainTombstone(this.db, target, operation, savedAt)
|
||||
return finishJournalSqlCommand(
|
||||
case 'tombstone':
|
||||
case 'goal-withdraw':
|
||||
return applyJournalSqlTombstoneCommand(
|
||||
this.db,
|
||||
this.stateDirectory,
|
||||
command,
|
||||
{ ...result, cards: [], receipts: [], inputChanged: true },
|
||||
result.cursor,
|
||||
[{ kind: 'tombstone', epoch: target.epoch, seq: result.cursor.sequence }],
|
||||
[...result.items.map((item) => item.itemId), ...result.removedItemIds]
|
||||
{ ...command, operation },
|
||||
savedAt
|
||||
)
|
||||
}
|
||||
case 'queue-insert':
|
||||
case 'queue-update':
|
||||
case 'queue-hold':
|
||||
|
||||
@@ -16,14 +16,14 @@ export function claimJournalSqlItemInputs(
|
||||
const userItems = publication.items.filter(
|
||||
(item) => item.body.kind === 'message' && item.body.role === 'user'
|
||||
)
|
||||
if (operation.kind !== 'item-claiming' && userItems.length === 0) {
|
||||
return { referencedUploads: publication.referencedUploads ?? [] }
|
||||
}
|
||||
const goals = new JournalGoalAttachmentInverse(target.sessionId)
|
||||
if (command.facts?.goals) {
|
||||
goals.adopt(command.facts.goals)
|
||||
}
|
||||
const referencedUploads = [...(publication.referencedUploads ?? [])]
|
||||
if (operation.kind !== 'item-claiming') {
|
||||
goals.acquired(new Set(referencedUploads), [])
|
||||
}
|
||||
if (operation.kind === 'item-claiming') {
|
||||
const itemId = agentJournalItemKey(operation.identity)
|
||||
const claim = claimAgentSessionAttachmentsInTransaction(db, {
|
||||
|
||||
@@ -11,7 +11,6 @@ import { readJournalDomainHistoryPage } from './journal-domain-history-page'
|
||||
import { ensureAgentSessionAttachmentClaimTables } from '../agent-session-attachments/agent-session-attachment-claims'
|
||||
import { agentSessionAttachmentStoreRoot } from '../agent-session-attachments/agent-session-attachment-references'
|
||||
import { ensureCommandReceiptsTable } from './writing/command-receipt-schema'
|
||||
import { JournalGoalAttachmentInverse } from './writing/journal-goal-attachment-inverse'
|
||||
|
||||
const cleanups: (() => void)[] = []
|
||||
afterEach(() => {
|
||||
@@ -109,54 +108,89 @@ it('publishes and binds ordinary writes to the same public epoch as history afte
|
||||
})
|
||||
})
|
||||
|
||||
it('rolls back missing and swept goal attachments and returns committed inverse accounting', async () => {
|
||||
it.each(['item', 'queue'] as const)(
|
||||
'keeps goal attachments used by an independent %s when withdrawing the goal',
|
||||
async (use) => {
|
||||
const f = domainLifecycleFixture(cleanups)
|
||||
ensureAgentSessionAttachmentClaimTables(f.db)
|
||||
const upload = '10000000-0000-4000-8000-000000000001'
|
||||
const root = agentSessionAttachmentStoreRoot(f.directory)
|
||||
const file = join(root, upload, 'pasted.txt')
|
||||
const body = {
|
||||
kind: 'message' as const,
|
||||
role: 'user' as const,
|
||||
sentAs: 'goal' as const,
|
||||
blocks: [{ type: 'text' as const, text: file }]
|
||||
}
|
||||
const operation = { kind: 'item-claiming' as const, identity: identity('goal'), body, options }
|
||||
await expect(f.run(operation)).rejects.toThrow('no longer stored')
|
||||
expect(f.item('orca:goal')).toBeUndefined()
|
||||
mkdirSync(join(root, upload), { recursive: true })
|
||||
writeFileSync(file, 'attachment')
|
||||
f.db.prepare(`INSERT INTO agent_session_attachment_sweeps VALUES(?,50)`).run(upload)
|
||||
await expect(f.run(operation)).rejects.toThrow('no longer stored')
|
||||
expect(f.item('orca:goal')).toBeUndefined()
|
||||
expect(f.db.prepare(`SELECT last_sequence FROM journal_chat_state`).get()).toEqual({
|
||||
last_sequence: 0
|
||||
})
|
||||
f.db.prepare(`DELETE FROM agent_session_attachment_sweeps WHERE upload_id=?`).run(upload)
|
||||
const committed = await f.run(operation)
|
||||
expect(committed.goals).toEqual({
|
||||
uploads: [[upload, ['orca:goal']]],
|
||||
goals: [['orca:goal', [upload]]]
|
||||
})
|
||||
expect(committed.publication?.referencedUploads).toEqual([upload])
|
||||
expect(
|
||||
f.db.prepare(`SELECT upload_id,session_id FROM agent_session_attachment_claims`).all()
|
||||
).toEqual([{ upload_id: upload, session_id: 'chat' }])
|
||||
const independent = await f.run(
|
||||
use === 'item'
|
||||
? {
|
||||
kind: 'item',
|
||||
identity: identity('independent'),
|
||||
body: { ...body, sentAs: undefined },
|
||||
options
|
||||
}
|
||||
: {
|
||||
kind: 'queue-insert',
|
||||
input: { messageId: 'independent', body: { ...body, sentAs: undefined } }
|
||||
},
|
||||
{ ...facts, goals: committed.goals }
|
||||
)
|
||||
const withdrawn = await f.run(
|
||||
{ kind: 'goal-withdraw', identity: identity('goal'), fence: 1 },
|
||||
{ ...facts, goals: independent.goals }
|
||||
)
|
||||
expect(withdrawn.goals).toEqual({ uploads: [], goals: [] })
|
||||
expect(f.item('orca:goal')).toBeUndefined()
|
||||
expect(f.db.prepare(`SELECT upload_id FROM agent_session_attachment_claims`).all()).toEqual([
|
||||
{ upload_id: upload }
|
||||
])
|
||||
}
|
||||
)
|
||||
|
||||
it('withdraws a goal and its exclusive attachment claim in the writer transaction', async () => {
|
||||
const f = domainLifecycleFixture(cleanups)
|
||||
ensureAgentSessionAttachmentClaimTables(f.db)
|
||||
const upload = '10000000-0000-4000-8000-000000000001'
|
||||
const root = agentSessionAttachmentStoreRoot(f.directory)
|
||||
const file = join(root, upload, 'pasted.txt')
|
||||
const body = {
|
||||
kind: 'message' as const,
|
||||
role: 'user' as const,
|
||||
sentAs: 'goal' as const,
|
||||
blocks: [{ type: 'text' as const, text: file }]
|
||||
}
|
||||
const operation = { kind: 'item-claiming' as const, identity: identity('goal'), body, options }
|
||||
await expect(f.run(operation)).rejects.toThrow('no longer stored')
|
||||
expect(f.item('orca:goal')).toBeUndefined()
|
||||
mkdirSync(join(root, upload), { recursive: true })
|
||||
writeFileSync(file, 'attachment')
|
||||
f.db.prepare(`INSERT INTO agent_session_attachment_sweeps VALUES(?,50)`).run(upload)
|
||||
await expect(f.run(operation)).rejects.toThrow('no longer stored')
|
||||
expect(f.item('orca:goal')).toBeUndefined()
|
||||
expect(f.db.prepare(`SELECT last_sequence FROM journal_chat_state`).get()).toEqual({
|
||||
last_sequence: 0
|
||||
const upload = '10000000-0000-4000-8000-000000000002'
|
||||
const root = join(agentSessionAttachmentStoreRoot(f.directory), upload)
|
||||
mkdirSync(root, { recursive: true })
|
||||
writeFileSync(join(root, 'pasted.txt'), 'attachment')
|
||||
const goal = await f.run({
|
||||
kind: 'item-claiming',
|
||||
identity: identity('goal'),
|
||||
options,
|
||||
body: {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
sentAs: 'goal',
|
||||
blocks: [{ type: 'text', text: join(root, 'pasted.txt') }]
|
||||
}
|
||||
})
|
||||
f.db.prepare(`DELETE FROM agent_session_attachment_sweeps WHERE upload_id=?`).run(upload)
|
||||
const committed = await f.run(operation)
|
||||
expect(committed.goals).toEqual({
|
||||
uploads: [[upload, ['orca:goal']]],
|
||||
goals: [['orca:goal', [upload]]]
|
||||
})
|
||||
expect(committed.publication?.referencedUploads).toEqual([upload])
|
||||
expect(
|
||||
f.db.prepare(`SELECT upload_id,session_id FROM agent_session_attachment_claims`).all()
|
||||
).toEqual([{ upload_id: upload, session_id: 'chat' }])
|
||||
const independent = await f.run(
|
||||
{
|
||||
kind: 'item',
|
||||
identity: identity('independent'),
|
||||
body: { ...body, sentAs: undefined },
|
||||
options
|
||||
},
|
||||
{ ...facts, goals: committed.goals }
|
||||
await f.run(
|
||||
{ kind: 'goal-withdraw', identity: identity('goal'), fence: 1 },
|
||||
{ ...facts, goals: goal.goals }
|
||||
)
|
||||
const inverse = new JournalGoalAttachmentInverse('chat')
|
||||
inverse.adopt(independent.goals!)
|
||||
const withdraw = inverse.withdraw('orca:goal')
|
||||
withdraw.write(f.db)
|
||||
withdraw.committed?.()
|
||||
expect(f.db.prepare(`SELECT upload_id FROM agent_session_attachment_claims`).all()).toEqual([
|
||||
{ upload_id: upload }
|
||||
])
|
||||
expect(f.item('orca:goal')).toBeUndefined()
|
||||
expect(f.db.prepare(`SELECT upload_id FROM agent_session_attachment_claims`).all()).toEqual([])
|
||||
})
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { applyJournalDomainTombstone } from './journal-domain-item-removal'
|
||||
import { finishJournalSqlCommand } from './journal-sql-command-result'
|
||||
import type { JournalWriterCommand } from './journal-writer-command'
|
||||
import { JournalGoalAttachmentInverse } from './writing/journal-goal-attachment-inverse'
|
||||
|
||||
/** Goal withdrawal uses only this handle's acknowledged proof of exclusive ownership. */
|
||||
export function applyJournalSqlTombstoneCommand(
|
||||
db: Database.Database,
|
||||
stateDirectory: string,
|
||||
command: JournalWriterCommand & {
|
||||
operation: Extract<JournalWriterCommand['operation'], { kind: 'tombstone' | 'goal-withdraw' }>
|
||||
},
|
||||
savedAt: number
|
||||
) {
|
||||
const { target, operation } = command
|
||||
const result = applyJournalDomainTombstone(
|
||||
db,
|
||||
target,
|
||||
operation.kind === 'goal-withdraw' ? { ...operation, releasedUploads: [] } : operation,
|
||||
savedAt
|
||||
)
|
||||
const commit = finishJournalSqlCommand(
|
||||
db,
|
||||
stateDirectory,
|
||||
command,
|
||||
{ ...result, cards: [], receipts: [], inputChanged: true },
|
||||
result.cursor,
|
||||
[{ kind: 'tombstone', epoch: target.epoch, seq: result.cursor.sequence }],
|
||||
[...result.items.map((item) => item.itemId), ...result.removedItemIds]
|
||||
)
|
||||
if (operation.kind === 'goal-withdraw') {
|
||||
const goals = new JournalGoalAttachmentInverse(target.sessionId)
|
||||
if (command.facts?.goals) {
|
||||
goals.adopt(command.facts.goals)
|
||||
}
|
||||
const withdrawal = goals.withdraw(agentJournalItemKey(operation.identity))
|
||||
withdrawal.write?.(db)
|
||||
withdrawal.committed?.()
|
||||
commit.goals = goals.snapshot()
|
||||
}
|
||||
return commit
|
||||
}
|
||||
+6
@@ -3,6 +3,7 @@ import {
|
||||
structuredAgentSessionCatalogScopeOwned
|
||||
} from '../options/structured-agent-session-catalog-reads'
|
||||
import { revealStructuredAgentSession } from './structured-agent-session-reveal'
|
||||
import { hostStructuredAgentSessionCurrentWork } from '../observations/structured-agent-session-host-current-work'
|
||||
import type { StructuredAgentSessionClientDelivery } from '../publication/subscribers/structured-agent-session-client-delivery'
|
||||
import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import type { StructuredAttentionRead } from '../../../../shared/agent-session/agent-session-attention'
|
||||
@@ -55,6 +56,11 @@ export function createStructuredAgentSessionConversationReads(context: () => Rea
|
||||
}))
|
||||
const journalOf = async (id: string) => (await context().conversation(id)).journal
|
||||
return {
|
||||
currentWorkAtRest: async (sessionId: string) => {
|
||||
await context().conversation(sessionId)
|
||||
const { deps, sessions } = context()
|
||||
return hostStructuredAgentSessionCurrentWork({ store: deps.store, sessions }, sessionId)
|
||||
},
|
||||
journalCurrentRead: async (sessionId: string, inputIds?: readonly string[]) =>
|
||||
(await context().conversation(sessionId)).journal.currentRead(inputIds),
|
||||
|
||||
|
||||
@@ -149,8 +149,7 @@ export class StructuredAgentSessionHost {
|
||||
deps: this.deps,
|
||||
sessions: this.sessions,
|
||||
serialize: this.serialize,
|
||||
readCommands: (id, commandsOnRequest) =>
|
||||
this.clientDelivery.readCommandsSettled(id, commandsOnRequest),
|
||||
readCommands: this.clientDelivery.readCommandsSettled,
|
||||
conversation: (id) => this.lifetime.conversation(id)
|
||||
}))
|
||||
sessionAgent = this.reads.sessionAgent
|
||||
@@ -310,7 +309,6 @@ export class StructuredAgentSessionHost {
|
||||
journalSnapshot = (sessionId: string) => this.backgroundTasks.journalSnapshot(sessionId)
|
||||
journalCurrentRead = this.reads.journalCurrentRead
|
||||
queuedSendAnswer = this.reads.queuedSendAnswer
|
||||
/** What became of one send, answered by key, for callers that follow many sends. */
|
||||
sendAnswer = this.reads.sendAnswer
|
||||
wakeQueuedMessages = (sessionId: string) => this.queued.refresh(sessionId)
|
||||
|
||||
@@ -322,6 +320,7 @@ export class StructuredAgentSessionHost {
|
||||
appendAgentStart = this.startJournal.appendAgentStart
|
||||
|
||||
currentWork = this.clientDelivery.readCurrentWork
|
||||
currentWorkAtRest = this.reads.currentWorkAtRest
|
||||
readCurrentRequests: BackgroundTasks['currentRequests'] = (...args) =>
|
||||
this.backgroundTasks.currentRequests(...args)
|
||||
|
||||
|
||||
-35
@@ -4,7 +4,6 @@ import {
|
||||
agentSessionRecordFixture
|
||||
} from '../../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentJournalRenderItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type { AgentMessageSource } from '../../../../../shared/agent-session/agent-session-message-source'
|
||||
|
||||
const hostRef: { current: unknown } = { current: null }
|
||||
@@ -18,31 +17,10 @@ vi.mock(
|
||||
|
||||
const {
|
||||
createStructuredMailboxPointerHost,
|
||||
readStructuredSessionGateFacts,
|
||||
structuredPointerCallerKey,
|
||||
structuredSessionPointerCallerKey
|
||||
} = await import('./structured-mailbox-pointer-host')
|
||||
|
||||
function runningTurn(): AgentJournalRenderItem {
|
||||
return {
|
||||
itemId: 'lifecycle-1',
|
||||
revision: 1,
|
||||
body: { kind: 'status', text: 'working', turnLifecycle: { turnId: 'turn-1', state: 'running' } }
|
||||
} as unknown as AgentJournalRenderItem
|
||||
}
|
||||
|
||||
function transcript(count: number): AgentJournalRenderItem[] {
|
||||
return Array.from(
|
||||
{ length: count },
|
||||
(_unused, index) =>
|
||||
({
|
||||
itemId: `tool-${index}`,
|
||||
revision: 1,
|
||||
body: { kind: 'tool-call', name: 'Bash', input: {}, state: 'completed' }
|
||||
}) as unknown as AgentJournalRenderItem
|
||||
)
|
||||
}
|
||||
|
||||
const NOTICE_SOURCE: AgentMessageSource = {
|
||||
kind: 'agent',
|
||||
senders: [],
|
||||
@@ -54,19 +32,6 @@ describe('structured mailbox pointer host', () => {
|
||||
hostRef.current = null
|
||||
})
|
||||
|
||||
it('reads the gate facts from the FULL timeline, never a bounded tail', async () => {
|
||||
// Read the full timeline: a busy turn's lifecycle item may be far from the tail, and false idle can interrupt it.
|
||||
const items = [runningTurn(), ...transcript(500)]
|
||||
hostRef.current = {
|
||||
journalCurrentRead: () => ({ items, submissions: [] }),
|
||||
currentWork: () => null
|
||||
}
|
||||
expect(await readStructuredSessionGateFacts('s1')).toEqual({
|
||||
turnRunning: true,
|
||||
awaitingHuman: false
|
||||
})
|
||||
})
|
||||
|
||||
it("passes on the chat host's own answer, never deciding it here", async () => {
|
||||
const answer = { kind: 'rejected', cancelled: false, recovered: true }
|
||||
const sendAnswer = vi.fn(async () => answer)
|
||||
|
||||
+30
-29
@@ -5,19 +5,17 @@ import { AGENT_SESSION_NOT_ATTACHED } from '../../../../native-chat/agent-sessio
|
||||
import { getStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry'
|
||||
import type { StructuredMailboxPointerHost } from './structured-mailbox-pointer-host-contract'
|
||||
import type { StructuredSendAnswer as StructuredMailSendState } from '../../../../native-chat/agent-session-wire/delivery/structured-agent-session-queued-send-answer'
|
||||
import type { AgentJournalSnapshot } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { structuredAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/structured-agent-session-mutation'
|
||||
import { mintAgentSessionOperationId } from './structured-pointer-operation-id'
|
||||
import {
|
||||
structuredSessionGateFacts,
|
||||
type StructuredSessionGateFacts
|
||||
} from './structured-session-pointer-delivery'
|
||||
import type { StructuredSessionGateFacts } from './structured-session-pointer-delivery'
|
||||
import {
|
||||
sendAgentTurn,
|
||||
type StructuredSessionTurnOutcome
|
||||
} from '../../turn-delivery/send-agent-turn'
|
||||
import { subscribeForRedrive } from './structured-session-journal-redrive'
|
||||
import type { AgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-store'
|
||||
import type { JournalPublication } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-conversations'
|
||||
import { readAgentJournalTurn } from '../../../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import { isAgentSessionContextClear } from '../../../../../shared/agent-session/agent-session-context-clear'
|
||||
|
||||
/** Names the dispatch a nudge belongs to on the operation row it writes. */
|
||||
export function structuredPointerCallerKey(dispatchId: string): string {
|
||||
@@ -29,27 +27,19 @@ export function structuredSessionPointerCallerKey(sessionId: string): string {
|
||||
return `trusted-local:orchestration:session:${sessionId}`
|
||||
}
|
||||
|
||||
/** Use the full reduced timeline: a busy turn's revised lifecycle item can lie outside any tail page. */
|
||||
/** Current-work selects the live turn and actionable prompts in one reader snapshot. */
|
||||
export async function readStructuredSessionGateFacts(
|
||||
sessionId: string
|
||||
): Promise<StructuredSessionGateFacts | null> {
|
||||
const snapshot = await readSessionJournal(sessionId)
|
||||
if (!snapshot) {
|
||||
return null
|
||||
}
|
||||
// The host's projection of current work: an agent that ended is idle, whatever its rows say.
|
||||
const work = await getStructuredAgentSessionHost()?.currentWork(sessionId)
|
||||
return structuredSessionGateFacts(snapshot.items, work?.scope)
|
||||
}
|
||||
|
||||
async function readSessionJournal(sessionId: string): Promise<AgentJournalSnapshot | null> {
|
||||
const host = getStructuredAgentSessionHost()
|
||||
if (!host) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
// Opens a conversation the idle sweep closed; that starts no agent.
|
||||
return await host.journalCurrentRead(sessionId)
|
||||
const work = await host.currentWorkAtRest(sessionId)
|
||||
return work
|
||||
? { turnRunning: work.activeTurnId() !== null, awaitingHuman: work.hasActionablePrompt() }
|
||||
: null
|
||||
} catch (error) {
|
||||
// Not attached is a retain reason, not a failure; anything else is still unreadable.
|
||||
if ((error as Error)?.message !== AGENT_SESSION_NOT_ATTACHED.code) {
|
||||
@@ -121,19 +111,30 @@ export function createStructuredMailboxPointerHost(): StructuredMailboxPointerHo
|
||||
|
||||
watchJournal(sessionId, onActivity) {
|
||||
const host = getStructuredAgentSessionHost()
|
||||
let seen: string | undefined
|
||||
let source: object | null = null
|
||||
// Only what mail waits on: a card handed over, deleted or edited (each moves the queue's
|
||||
// revision without adding a card, so a new card, the lane's own included, changes nothing),
|
||||
// handoffs settling, an accepted turn, a /clear, a new item. A streamed token changes none.
|
||||
const relevant = (journal: AgentSessionJournal) => {
|
||||
const order = journal.inputOrder
|
||||
const state = journal.queuedMessages.inputState()
|
||||
const cleared = state.queuePauseMarks.cleared?.sequence
|
||||
const changes = state.queue.revision - state.queue.cards.size
|
||||
const key = `${state.epoch}:${changes}:${order.unsettledSubmissions().length}:${order.links.version()}:${order.links.acceptedHandover()}:${cleared}:${state.items.size}`
|
||||
const changed = key !== seen
|
||||
seen = key
|
||||
return changed
|
||||
const relevant = (publication: JournalPublication) => {
|
||||
const replaced = publication.source !== source
|
||||
source = publication.source
|
||||
const commit = publication.commit
|
||||
if (!commit) {
|
||||
return replaced && source !== null
|
||||
}
|
||||
const cards = commit.publication?.cards ?? []
|
||||
const changedInput =
|
||||
commit.inputChanged &&
|
||||
(cards.length === 0 ||
|
||||
cards.some((card) => card.revision > 0 || card.state !== 'waiting'))
|
||||
return (
|
||||
replaced ||
|
||||
changedInput ||
|
||||
commit.publication?.items.some(
|
||||
(item) => readAgentJournalTurn(item.body) || isAgentSessionContextClear(item.body)
|
||||
) === true ||
|
||||
commit.items.some((item) => item.deleted || item.revision === 0)
|
||||
)
|
||||
}
|
||||
return host ? subscribeForRedrive(host, sessionId, onActivity, relevant) : () => {}
|
||||
},
|
||||
|
||||
+11
-9
@@ -1,6 +1,6 @@
|
||||
import type { StructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-host'
|
||||
import { createKeyedTrailingEdgeCoalescer } from '../../../client/events/keyed-trailing-edge-coalescer'
|
||||
import type { AgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-store'
|
||||
import type { JournalPublication } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-conversations'
|
||||
|
||||
/** Coalesce streaming batches until quiet; settled turns stop emitting, so the final nudge still lands promptly. */
|
||||
const REDRIVE_FLUSH_MS = 300
|
||||
@@ -15,23 +15,25 @@ export function subscribeForRedrive(
|
||||
sessionId: string,
|
||||
onJournalActivity: (sessionId: string) => void,
|
||||
/** Whether a publication changed anything the subscriber acts on. */
|
||||
relevant: (journal: AgentSessionJournal) => boolean
|
||||
relevant: (publication: JournalPublication) => boolean
|
||||
): () => void {
|
||||
const coalescer = createKeyedTrailingEdgeCoalescer(onJournalActivity, {
|
||||
flushMs: REDRIVE_FLUSH_MS,
|
||||
maxWaitMs: REDRIVE_MAX_WAIT_MS
|
||||
})
|
||||
try {
|
||||
const unsubscribe = host.observeJournalPublications(
|
||||
sessionId,
|
||||
(journal) => {
|
||||
if (relevant(journal)) {
|
||||
let seeded = false
|
||||
const unsubscribe = host.observeConversationPublications(sessionId, {
|
||||
next: (publication) => {
|
||||
const changed = relevant(publication)
|
||||
if (seeded && changed) {
|
||||
coalescer.schedule(sessionId)
|
||||
}
|
||||
seeded = true
|
||||
},
|
||||
// The journal as it is now is the baseline: only a later change wakes the subscriber.
|
||||
(journal) => journal && relevant(journal)
|
||||
)
|
||||
error: (error) =>
|
||||
console.warn('[orchestration] structured session redrive failed', sessionId, error)
|
||||
})
|
||||
// Discard pending redrive on settlement so it cannot nudge a session no dispatch owns.
|
||||
return () => {
|
||||
coalescer.dispose()
|
||||
|
||||
Reference in New Issue
Block a user