mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 03:45:08 +00:00
Write native chat queue cards as named domain SQL commands
Queue insert, edit, hold, withdraw and move now select the addressed current card rows, apply the existing queue policy and copy-replace card versions in the caller's writer transaction, with one sequence and replay event per producing command. Order is a typed position column with message-id ties; replaced versions stay only while a submission attempt names them, and withdraw/edit retire their edit leases in the same transaction.
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
import type { SqliteRow } from '../../sqlite/sqlite-statement'
|
||||
import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { agentSessionSendBodyFingerprint } from '../../../shared/agent-session/requests/structured-agent-session-send-mutation'
|
||||
import { structuredAgentSessionCommandTurnIdentity } from '../../../shared/agent-session/view/structured-agent-session-command-turn-identity'
|
||||
import type { QueuedMessageRow, QueuedMessageState } from './queued-messages/queued-message-table'
|
||||
|
||||
type Target = { sessionId: string; epoch: string }
|
||||
|
||||
/** A current card with the version key a replacement must address. */
|
||||
export type JournalDomainCard = {
|
||||
card: QueuedMessageRow
|
||||
version: { sequence: number; index: number }
|
||||
}
|
||||
|
||||
export const SELECT_JOURNAL_DOMAIN_CARD = `SELECT message_id, version_sequence, version_index,
|
||||
state, position, payload_json FROM journal_card_versions`
|
||||
|
||||
export function readJournalDomainCard(sessionId: string, row: SqliteRow): JournalDomainCard {
|
||||
const card: QueuedMessageRow = JSON.parse(String(row.payload_json))
|
||||
const position = row.position === null ? card.position : Number(row.position)
|
||||
return {
|
||||
card: {
|
||||
...card,
|
||||
messageId: String(row.message_id),
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the state column is only ever written from a QueuedMessageRow state.
|
||||
state: String(row.state) as QueuedMessageState,
|
||||
position,
|
||||
fingerprint: agentSessionSendBodyFingerprint(sessionId, card.body)
|
||||
},
|
||||
version: { sequence: Number(row.version_sequence), index: Number(row.version_index) }
|
||||
}
|
||||
}
|
||||
|
||||
export function journalDomainCurrentCard(
|
||||
db: Database.Database,
|
||||
target: Target,
|
||||
messageId: string
|
||||
): JournalDomainCard | null {
|
||||
const row = db
|
||||
.prepare(
|
||||
`${SELECT_JOURNAL_DOMAIN_CARD} WHERE session_id=? AND epoch=? AND message_id=? AND current=1`
|
||||
)
|
||||
.get(target.sessionId, target.epoch, messageId)
|
||||
return row ? readJournalDomainCard(target.sessionId, row) : null
|
||||
}
|
||||
|
||||
function commandTurnItemId(card: QueuedMessageRow): string | null {
|
||||
return card.state === 'returned' && card.body.command && card.consumedAs !== null
|
||||
? agentJournalItemKey(structuredAgentSessionCommandTurnIdentity(card.consumedAs))
|
||||
: null
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy-replaces the addressed current version with `card` at (sequence, 0). The replaced version
|
||||
* stays only while a submission attempt names it as its source; it is never rewritten.
|
||||
*/
|
||||
export function writeJournalDomainCardVersion(
|
||||
db: Database.Database,
|
||||
target: Target,
|
||||
prior: JournalDomainCard | null,
|
||||
card: QueuedMessageRow,
|
||||
sequence: number
|
||||
): void {
|
||||
const prefix = [target.sessionId, target.epoch] as const
|
||||
if (prior) {
|
||||
if (prior.card.messageId !== card.messageId || prior.version.sequence >= sequence) {
|
||||
throw new Error('journal card version must follow its addressed prior version')
|
||||
}
|
||||
const key = [card.messageId, prior.version.sequence, prior.version.index] as const
|
||||
const replaced = db
|
||||
.prepare(`UPDATE journal_card_versions SET current=0 WHERE session_id=? AND epoch=?
|
||||
AND message_id=? AND version_sequence=? AND version_index=? AND current=1`)
|
||||
.run(...prefix, ...key)
|
||||
if (replaced.changes !== 1) {
|
||||
throw new Error('journal card version was already replaced')
|
||||
}
|
||||
db.prepare(`DELETE FROM journal_card_versions WHERE session_id=? AND epoch=?
|
||||
AND message_id=? AND version_sequence=? AND version_index=?
|
||||
AND NOT EXISTS(SELECT 1 FROM journal_submission_attempts AS attempt
|
||||
WHERE attempt.session_id=? AND attempt.epoch=? AND attempt.source_card_sequence=?
|
||||
AND attempt.source_card_index=? AND json_extract(attempt.payload_json,'$.queuedMessageId')=?)`).run(
|
||||
...prefix,
|
||||
...key,
|
||||
...prefix,
|
||||
prior.version.sequence,
|
||||
prior.version.index,
|
||||
card.messageId
|
||||
)
|
||||
}
|
||||
const { fingerprint: _derived, ...payload } = card
|
||||
db.prepare(`INSERT INTO journal_card_versions(session_id,epoch,message_id,version_sequence,
|
||||
version_index,current,state,command_turn_item_id,payload_json,position)
|
||||
VALUES(?,?,?,?,0,1,?,?,?,?)`).run(
|
||||
...prefix,
|
||||
card.messageId,
|
||||
sequence,
|
||||
card.state,
|
||||
commandTurnItemId(card),
|
||||
JSON.stringify(payload),
|
||||
card.position
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
import type { AgentJournalCursor } from '../../../shared/agent-session/journal/agent-session-journal-identity'
|
||||
import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { readAgentSessionExecutionOptions } from '../../../shared/agent-session/options/agent-session-execution-options'
|
||||
import type {
|
||||
AgentSessionQueuedMessageMoveResult,
|
||||
AgentSessionQueuedMessageUpdateResult
|
||||
} from '../../../shared/agent-session/requests/agent-session-queued-message-wire'
|
||||
import { agentSessionSendBodyFingerprint } from '../../../shared/agent-session/requests/structured-agent-session-send-mutation'
|
||||
import { claimAgentSessionAttachmentsInTransaction } from '../agent-session-attachments/agent-session-attachment-claims'
|
||||
import { applyJournalDomainEditLease } from './journal-domain-edit-leases'
|
||||
import {
|
||||
journalDomainCurrentCard,
|
||||
readJournalDomainCard,
|
||||
SELECT_JOURNAL_DOMAIN_CARD,
|
||||
writeJournalDomainCardVersion,
|
||||
type JournalDomainCard
|
||||
} from './journal-domain-card-versions'
|
||||
import { appendJournalSqlEvent } from './journal-sql-event-tail'
|
||||
import type { JournalSqlQueueWrite } from './journal-sql-queued-messages'
|
||||
import { queuedMessageMovePlan } from './queued-messages/queued-message-move'
|
||||
import {
|
||||
isUnsettledQueuedMessage,
|
||||
type QueuedMessageRow
|
||||
} from './queued-messages/queued-message-table'
|
||||
import { queuedMessageUpdateDecision } from './queued-messages/queued-message-update'
|
||||
|
||||
type Target = { sessionId: string; epoch: string }
|
||||
|
||||
type QueueInsert = Extract<JournalSqlQueueWrite, { kind: 'queue-insert' }>
|
||||
|
||||
/** The host's admission also names delivery and attendance, which every saved card keeps. */
|
||||
export type JournalDomainQueueOperation =
|
||||
| Exclude<JournalSqlQueueWrite, QueueInsert>
|
||||
| {
|
||||
kind: 'queue-insert'
|
||||
input: QueueInsert['input'] & { deliveryMode?: 'queue' | 'steer'; unattended?: boolean }
|
||||
}
|
||||
|
||||
export type JournalDomainQueueResult =
|
||||
| { kind: 'queue-insert'; card: QueuedMessageRow }
|
||||
| { kind: 'queue-update'; update: AgentSessionQueuedMessageUpdateResult }
|
||||
| { kind: 'queue-hold' }
|
||||
| { kind: 'queue-withdraw'; cards: QueuedMessageRow[] }
|
||||
| { kind: 'queue-move'; move: AgentSessionQueuedMessageMoveResult }
|
||||
|
||||
export type JournalDomainQueueCommit = {
|
||||
cursor: AgentJournalCursor
|
||||
result: JournalDomainQueueResult
|
||||
cards: QueuedMessageRow[]
|
||||
inputChanged: boolean
|
||||
/** Present only when this command retired edit leases. */
|
||||
editDeadline?: number | null
|
||||
/** Uploads this card now references; the host releases their goal inverse after COMMIT. */
|
||||
referencedUploads?: string[]
|
||||
}
|
||||
|
||||
type Change = { prior: JournalDomainCard | null; card: QueuedMessageRow }
|
||||
|
||||
/** Runs only on the owning writer connection, inside its command transaction or SAVEPOINT. */
|
||||
export function applyJournalDomainQueueCommand(
|
||||
db: Database.Database,
|
||||
stateDirectory: string,
|
||||
target: Target,
|
||||
operation: JournalDomainQueueOperation,
|
||||
savedAt: number
|
||||
): JournalDomainQueueCommit {
|
||||
if (!db.isTransaction) {
|
||||
throw new Error('journal queue command requires its writer transaction')
|
||||
}
|
||||
const head = db
|
||||
.prepare('SELECT last_sequence FROM journal_chat_state WHERE session_id=? AND epoch=?')
|
||||
.get(target.sessionId, target.epoch)
|
||||
if (!head) {
|
||||
throw new Error('journal queue command targets a retired chat epoch')
|
||||
}
|
||||
const cursor = { epoch: target.epoch, sequence: Number(head.last_sequence) }
|
||||
const current = (messageId: string) => journalDomainCurrentCard(db, target, messageId)
|
||||
const claim = (
|
||||
body: AgentJournalMessageItem,
|
||||
required: boolean,
|
||||
previous?: AgentJournalMessageItem
|
||||
) => [
|
||||
...claimAgentSessionAttachmentsInTransaction(db, {
|
||||
stateDirectory,
|
||||
sessionId: target.sessionId,
|
||||
body,
|
||||
required,
|
||||
...(previous ? { previous } : {}),
|
||||
now: savedAt
|
||||
}).referenced
|
||||
]
|
||||
let result: JournalDomainQueueResult
|
||||
let changes: Change[] = []
|
||||
let retire: string[] = []
|
||||
let referencedUploads: string[] | undefined
|
||||
switch (operation.kind) {
|
||||
case 'queue-insert': {
|
||||
const { input } = operation
|
||||
const existing = current(input.messageId)
|
||||
// An existing ID is duplicate admission of the same accepted card, never new queue work.
|
||||
if (existing) {
|
||||
result = { kind: 'queue-insert', card: existing.card }
|
||||
break
|
||||
}
|
||||
referencedUploads = claim(input.body, input.requireAttachments === true)
|
||||
const last = db
|
||||
.prepare(`SELECT MAX(position) AS position FROM journal_card_versions
|
||||
WHERE session_id=? AND epoch=? AND current=1`)
|
||||
.get(target.sessionId, target.epoch)
|
||||
const options = readAgentSessionExecutionOptions(input.options)
|
||||
const card: QueuedMessageRow = {
|
||||
messageId: input.messageId,
|
||||
position: Math.max(0, Number(last?.position ?? 0)) + 1,
|
||||
body: input.body,
|
||||
fingerprint: agentSessionSendBodyFingerprint(target.sessionId, input.body),
|
||||
state: 'waiting',
|
||||
holdReason: input.holdReason ?? null,
|
||||
returnedReason: null,
|
||||
returnedRejection: null,
|
||||
consumedAs: null,
|
||||
queuedAt: cursor,
|
||||
...(options ? { options } : {}),
|
||||
...(input.deliveryMode !== undefined ? { deliveryMode: input.deliveryMode } : {}),
|
||||
...(input.unattended !== undefined ? { unattended: input.unattended } : {})
|
||||
}
|
||||
changes = [{ prior: null, card }]
|
||||
result = { kind: 'queue-insert', card }
|
||||
break
|
||||
}
|
||||
case 'queue-update': {
|
||||
const { input } = operation
|
||||
const prior = current(input.messageId)
|
||||
const decision = queuedMessageUpdateDecision(prior?.card ?? null, target.sessionId, input)
|
||||
// Any answer ends the edit that held this card, as the edit-lease owner does today.
|
||||
retire = [input.messageId]
|
||||
if (decision.status !== 'ready') {
|
||||
result = { kind: 'queue-update', update: decision }
|
||||
break
|
||||
}
|
||||
referencedUploads = claim(decision.body, true, decision.previous)
|
||||
changes = [
|
||||
{ prior, card: { ...prior!.card, body: decision.body, fingerprint: decision.fingerprint } }
|
||||
]
|
||||
result = {
|
||||
kind: 'queue-update',
|
||||
update: {
|
||||
status: 'updated',
|
||||
messageId: input.messageId,
|
||||
fingerprint: decision.fingerprint
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'queue-hold':
|
||||
changes = addressed(operation.messageIds, current).flatMap((prior) =>
|
||||
prior.card.state === 'waiting' && prior.card.holdReason !== operation.reason
|
||||
? [{ prior, card: { ...prior.card, holdReason: operation.reason } }]
|
||||
: []
|
||||
)
|
||||
result = { kind: 'queue-hold' }
|
||||
break
|
||||
case 'queue-withdraw':
|
||||
changes = addressed(operation.messageIds, current).flatMap((prior) =>
|
||||
isUnsettledQueuedMessage(prior.card)
|
||||
? [{ prior, card: { ...prior.card, state: 'withdrawn' as const, holdReason: null } }]
|
||||
: []
|
||||
)
|
||||
retire = changes.map(({ card }) => card.messageId)
|
||||
result = { kind: 'queue-withdraw', cards: changes.map(({ card }) => card) }
|
||||
break
|
||||
case 'queue-move': {
|
||||
// Only a move reads the ordered unsettled set; dispatched cards keep their reserved slots.
|
||||
const unsettled = db
|
||||
.prepare(`${SELECT_JOURNAL_DOMAIN_CARD} WHERE session_id=? AND epoch=? AND current=1
|
||||
AND state IN ('waiting','returned') ORDER BY position, message_id`)
|
||||
.all(target.sessionId, target.epoch)
|
||||
.map((row) => readJournalDomainCard(target.sessionId, row))
|
||||
const plan = queuedMessageMovePlan(
|
||||
unsettled.map(({ card }) => card),
|
||||
operation.input
|
||||
)
|
||||
changes = plan.changes.flatMap(({ messageId, change }) => {
|
||||
const prior = unsettled.find(({ card }) => card.messageId === messageId)
|
||||
return prior && change?.op === 'moved'
|
||||
? [{ prior, card: { ...prior.card, position: change.position } }]
|
||||
: []
|
||||
})
|
||||
result = { kind: 'queue-move', move: plan.result }
|
||||
break
|
||||
}
|
||||
}
|
||||
const commit: JournalDomainQueueCommit = {
|
||||
cursor,
|
||||
result,
|
||||
cards: changes.map(({ card }) => card),
|
||||
inputChanged: changes.length > 0,
|
||||
...(referencedUploads?.length ? { referencedUploads } : {})
|
||||
}
|
||||
let leasesChanged = false
|
||||
let editDeadline: number | null = null
|
||||
for (const messageId of retire) {
|
||||
const retired = applyJournalDomainEditLease(
|
||||
db,
|
||||
target,
|
||||
'',
|
||||
{ kind: 'retire-card', messageId },
|
||||
savedAt
|
||||
)
|
||||
leasesChanged ||= retired.changed
|
||||
editDeadline = retired.nextDeadline
|
||||
}
|
||||
if (leasesChanged) {
|
||||
commit.editDeadline = editDeadline
|
||||
}
|
||||
if (changes.length === 0) {
|
||||
return commit
|
||||
}
|
||||
const sequence = cursor.sequence + 1
|
||||
for (const { prior, card } of changes) {
|
||||
writeJournalDomainCardVersion(db, target, prior, card, sequence)
|
||||
}
|
||||
db.prepare('UPDATE journal_chat_state SET last_sequence=? WHERE session_id=? AND epoch=?').run(
|
||||
sequence,
|
||||
target.sessionId,
|
||||
target.epoch
|
||||
)
|
||||
appendJournalSqlEvent(db, target, sequence, savedAt, {
|
||||
items: [],
|
||||
submissions: [],
|
||||
cards: commit.cards.map((card) => card.messageId)
|
||||
})
|
||||
commit.cursor = { epoch: target.epoch, sequence }
|
||||
return commit
|
||||
}
|
||||
|
||||
/** Each addressed card at most once, in the caller's order. */
|
||||
function addressed(
|
||||
messageIds: readonly string[],
|
||||
current: (messageId: string) => JournalDomainCard | null
|
||||
): JournalDomainCard[] {
|
||||
return [...new Set(messageIds)].flatMap((messageId) => {
|
||||
const card = current(messageId)
|
||||
return card ? [card] : []
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
|
||||
/**
|
||||
* Queue order is a typed column beside the card body, never its version key. Ties keep today's
|
||||
* message-id order, which no edit, move or handover changes, so no separate admission column.
|
||||
*/
|
||||
const JOURNAL_DOMAIN_QUEUE_SCHEMA = `
|
||||
ALTER TABLE journal_card_versions ADD COLUMN position REAL;
|
||||
UPDATE journal_card_versions SET position=json_extract(payload_json,'$.position');
|
||||
CREATE INDEX journal_card_order ON journal_card_versions(session_id, epoch, position, message_id)
|
||||
WHERE current=1 AND state IN ('waiting','returned');
|
||||
CREATE INDEX journal_card_last_position ON journal_card_versions(session_id, epoch, position)
|
||||
WHERE current=1;
|
||||
CREATE INDEX journal_submission_source_card ON journal_submission_attempts(session_id, epoch, source_card_sequence, source_card_index)
|
||||
WHERE source_card_sequence IS NOT NULL;
|
||||
`
|
||||
|
||||
/** Runs once inside the caller's migration transaction; existing card bodies are kept as saved. */
|
||||
export function migrateJournalDomainQueueSchema(db: Database.Database): void {
|
||||
if (!db.isTransaction) {
|
||||
throw new Error('journal queue schema requires its migration transaction')
|
||||
}
|
||||
const installed = db
|
||||
.prepare(`SELECT 1 FROM pragma_table_info('journal_card_versions') WHERE name='position'`)
|
||||
.get()
|
||||
if (!installed) {
|
||||
db.exec(JOURNAL_DOMAIN_QUEUE_SCHEMA)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { agentSessionSendBodyFingerprint } from '../../../shared/agent-session/requests/structured-agent-session-send-mutation'
|
||||
import {
|
||||
ensureAgentSessionAttachmentClaimTables,
|
||||
isAgentSessionAttachmentExpiredError,
|
||||
markUnclaimedUploadForSweep
|
||||
} from '../agent-session-attachments/agent-session-attachment-claims'
|
||||
import { agentSessionAttachmentStoreRoot } from '../agent-session-attachments/agent-session-attachment-references'
|
||||
import { migrateJournalDomainSchema } from './journal-domain-schema'
|
||||
import { migrateJournalDomainQueueSchema } from './journal-domain-queue-schema'
|
||||
import { applyJournalDomainEditLease } from './journal-domain-edit-leases'
|
||||
import {
|
||||
applyJournalDomainQueueCommand,
|
||||
type JournalDomainQueueOperation
|
||||
} from './journal-domain-queue-command'
|
||||
import type { QueuedMessageRow } from './queued-messages/queued-message-table'
|
||||
|
||||
const target = { sessionId: 'chat', epoch: 'epoch' }
|
||||
const now = 1_800_000_000_000
|
||||
const UPLOAD_A = '0b6f8a52-4a3e-4c4e-9a59-1d5d1f2b8c01'
|
||||
const UPLOAD_B = '7c2d9e10-3f4a-4b5c-8d6e-2f1a0b9c8d02'
|
||||
const cleanups: (() => void)[] = []
|
||||
|
||||
const text = (value: string): AgentJournalMessageItem => ({
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: value }]
|
||||
})
|
||||
|
||||
function fixture() {
|
||||
const db = new Database(':memory:')
|
||||
const stateDirectory = mkdtempSync(join(tmpdir(), 'orca-domain-queue-'))
|
||||
cleanups.push(() => {
|
||||
db.close()
|
||||
rmSync(stateDirectory, { recursive: true, force: true })
|
||||
})
|
||||
migrateJournalDomainSchema(db)
|
||||
ensureAgentSessionAttachmentClaimTables(db)
|
||||
db.exec('BEGIN IMMEDIATE')
|
||||
migrateJournalDomainQueueSchema(db)
|
||||
db.exec('COMMIT')
|
||||
db.prepare(`INSERT INTO journal_chat_state(session_id,epoch,last_sequence,highest_fence)
|
||||
VALUES('chat','epoch',10,1)`).run()
|
||||
const seed = (
|
||||
messageId: string,
|
||||
position: number,
|
||||
fields: Partial<QueuedMessageRow> = {},
|
||||
version = 1
|
||||
) => {
|
||||
const card = {
|
||||
messageId,
|
||||
position,
|
||||
body: text(messageId),
|
||||
state: 'waiting',
|
||||
holdReason: null,
|
||||
returnedReason: null,
|
||||
returnedRejection: null,
|
||||
consumedAs: null,
|
||||
queuedAt: { epoch: 'epoch', sequence: 1 },
|
||||
...fields
|
||||
}
|
||||
db.prepare(`INSERT INTO journal_card_versions(session_id,epoch,message_id,version_sequence,
|
||||
version_index,current,state,payload_json,position) VALUES('chat','epoch',?,?,0,1,?,?,?)`).run(
|
||||
messageId,
|
||||
version,
|
||||
card.state,
|
||||
JSON.stringify(card),
|
||||
position
|
||||
)
|
||||
}
|
||||
const run = (operation: JournalDomainQueueOperation) => {
|
||||
db.exec('BEGIN IMMEDIATE')
|
||||
try {
|
||||
const commit = applyJournalDomainQueueCommand(db, stateDirectory, target, operation, now)
|
||||
db.exec('COMMIT')
|
||||
return commit
|
||||
} catch (error) {
|
||||
db.exec('ROLLBACK')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
const lease = (messageId: string, body = text(messageId)) => {
|
||||
db.exec('BEGIN IMMEDIATE')
|
||||
applyJournalDomainEditLease(
|
||||
db,
|
||||
target,
|
||||
'handle',
|
||||
{
|
||||
kind: 'acquire',
|
||||
callerKey: 'desktop',
|
||||
editId: `edit-${messageId}`,
|
||||
messageId,
|
||||
fingerprint: agentSessionSendBodyFingerprint('chat', body)
|
||||
},
|
||||
now
|
||||
)
|
||||
db.exec('COMMIT')
|
||||
}
|
||||
const leases = () =>
|
||||
db
|
||||
.prepare('SELECT message_id FROM journal_edit_leases ORDER BY message_id')
|
||||
.all()
|
||||
.map((row) => row.message_id)
|
||||
const head = () =>
|
||||
Number(db.prepare('SELECT last_sequence FROM journal_chat_state').get()!.last_sequence)
|
||||
const events = () =>
|
||||
db
|
||||
.prepare('SELECT sequence, changes_json FROM journal_events ORDER BY sequence')
|
||||
.all()
|
||||
.map((row) => [row.sequence, JSON.parse(String(row.changes_json)).cards])
|
||||
const versions = (messageId: string) =>
|
||||
db
|
||||
.prepare(`SELECT version_sequence, current, state, position, payload_json FROM journal_card_versions
|
||||
WHERE message_id=? ORDER BY version_sequence`)
|
||||
.all(messageId)
|
||||
.map((row) => {
|
||||
const payload = JSON.parse(String(row.payload_json))
|
||||
return [row.version_sequence, row.current, row.state, row.position, payload.body.blocks]
|
||||
})
|
||||
const order = () =>
|
||||
db
|
||||
.prepare(`SELECT message_id, position FROM journal_card_versions WHERE current=1
|
||||
ORDER BY position, message_id`)
|
||||
.all()
|
||||
.map((row) => [row.message_id, row.position])
|
||||
return { db, stateDirectory, seed, run, lease, leases, head, events, versions, order }
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0)) {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('admits a card once and keeps a replaced version only while an attempt names it', () => {
|
||||
const queue = fixture()
|
||||
queue.seed('earlier', 4, { state: 'withdrawn' })
|
||||
const first = queue.run({
|
||||
kind: 'queue-insert',
|
||||
input: { messageId: 'card', body: text('first'), deliveryMode: 'queue', unattended: false }
|
||||
})
|
||||
expect(first.cursor).toEqual({ epoch: 'epoch', sequence: 11 })
|
||||
expect(first.result).toMatchObject({
|
||||
kind: 'queue-insert',
|
||||
card: { position: 5, state: 'waiting', queuedAt: { epoch: 'epoch', sequence: 10 } }
|
||||
})
|
||||
const duplicate = queue.run({
|
||||
kind: 'queue-insert',
|
||||
input: { messageId: 'card', body: text('second') }
|
||||
})
|
||||
expect(duplicate).toMatchObject({
|
||||
cursor: { epoch: 'epoch', sequence: 11 },
|
||||
cards: [],
|
||||
inputChanged: false,
|
||||
result: { card: { body: text('first'), deliveryMode: 'queue', unattended: false } }
|
||||
})
|
||||
expect(queue.events()).toEqual([[11, ['card']]])
|
||||
|
||||
queue.db
|
||||
.prepare(`INSERT INTO journal_submission_attempts(session_id,epoch,message_id,attempt_sequence,
|
||||
attempt_index,current,item_id,ordinal,submitted_at,fingerprint,dispatch_state,source_card_sequence,
|
||||
source_card_index,payload_json) VALUES('chat','epoch','send',12,0,1,'item',12,1,'f','pending',11,0,?)`)
|
||||
.run(JSON.stringify({ clientMessageId: 'send', queuedMessageId: 'card' }))
|
||||
const edit = (expected: string, value: string) =>
|
||||
queue.run({
|
||||
kind: 'queue-update',
|
||||
input: { messageId: 'card', expectedBodyFingerprint: expected, text: value }
|
||||
})
|
||||
edit(agentSessionSendBodyFingerprint('chat', text('first')), 'edited once')
|
||||
edit(agentSessionSendBodyFingerprint('chat', text('edited once')), 'edited twice')
|
||||
expect(queue.versions('card')).toEqual([
|
||||
[11, 0, 'waiting', 5, [{ type: 'text', text: 'first' }]],
|
||||
[13, 1, 'waiting', 5, [{ type: 'text', text: 'edited twice' }]]
|
||||
])
|
||||
})
|
||||
|
||||
it('answers a stale or repeated edit without a version and refuses a swept new upload atomically', () => {
|
||||
const queue = fixture()
|
||||
const root = agentSessionAttachmentStoreRoot(queue.stateDirectory)
|
||||
const image = (uploadId: string) => ({
|
||||
type: 'image-ref' as const,
|
||||
path: join(root, uploadId, 'shot.png')
|
||||
})
|
||||
const body: AgentJournalMessageItem = {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'look' }, image(UPLOAD_A)]
|
||||
}
|
||||
queue.seed('card', 1, { body })
|
||||
queue.db.exec('BEGIN IMMEDIATE')
|
||||
markUnclaimedUploadForSweep(queue.db, UPLOAD_A, now)
|
||||
markUnclaimedUploadForSweep(queue.db, UPLOAD_B, now)
|
||||
queue.db.exec('COMMIT')
|
||||
const original = agentSessionSendBodyFingerprint('chat', body)
|
||||
const update = (expected: string, value: string, images?: ReturnType<typeof image>[]) =>
|
||||
queue.run({
|
||||
kind: 'queue-update',
|
||||
input: {
|
||||
messageId: 'card',
|
||||
expectedBodyFingerprint: expected,
|
||||
text: value,
|
||||
...(images ? { images } : {})
|
||||
}
|
||||
})
|
||||
|
||||
expect(update('someone-else', 'mine').result).toEqual({
|
||||
kind: 'queue-update',
|
||||
update: { status: 'changed', messageId: 'card' }
|
||||
})
|
||||
// The kept image is not newly referenced, so its sweep cannot block a text fix.
|
||||
const fixed = update(original, 'look again')
|
||||
expect(fixed.result).toMatchObject({ update: { status: 'updated' } })
|
||||
const edited = agentSessionSendBodyFingerprint('chat', {
|
||||
...body,
|
||||
blocks: [{ type: 'text', text: 'look again' }, image(UPLOAD_A)]
|
||||
})
|
||||
// A lost reply retried with the old expectation reconciles to the applied edit.
|
||||
expect(update(original, 'look again').result).toEqual({
|
||||
kind: 'queue-update',
|
||||
update: { status: 'unchanged', messageId: 'card', fingerprint: edited }
|
||||
})
|
||||
expect(queue.head()).toBe(11)
|
||||
|
||||
queue.lease('card', { ...body, blocks: [{ type: 'text', text: 'look again' }, image(UPLOAD_A)] })
|
||||
let refusal: unknown
|
||||
try {
|
||||
update(edited, 'with another', [image(UPLOAD_A), image(UPLOAD_B)])
|
||||
} catch (error) {
|
||||
refusal = error
|
||||
}
|
||||
expect(isAgentSessionAttachmentExpiredError(refusal)).toBe(true)
|
||||
expect(queue.head()).toBe(11)
|
||||
expect(queue.versions('card').filter(([, current]) => current === 1)).toEqual([
|
||||
[11, 1, 'waiting', 1, [{ type: 'text', text: 'look again' }, image(UPLOAD_A)]]
|
||||
])
|
||||
expect(queue.leases()).toEqual(['card'])
|
||||
expect(queue.db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all()).toEqual([
|
||||
{ upload_id: UPLOAD_A }
|
||||
])
|
||||
})
|
||||
|
||||
it('moves among unsettled cards only, keeping dispatched slots and id ties', () => {
|
||||
const queue = fixture()
|
||||
queue.seed('a', 1)
|
||||
queue.seed('b', 2, { state: 'dispatched', consumedAs: 'send-b' })
|
||||
queue.seed('c', 3, { state: 'returned', returnedReason: 'refused' })
|
||||
queue.seed('y', 4)
|
||||
queue.seed('x', 4)
|
||||
queue.lease('a')
|
||||
|
||||
const moved = queue.run({
|
||||
kind: 'queue-move',
|
||||
input: { messageId: 'x', beforeMessageId: 'a' }
|
||||
})
|
||||
expect(moved.result).toEqual({ kind: 'queue-move', move: { messageId: 'x', status: 'moved' } })
|
||||
expect(queue.order()).toEqual([
|
||||
['x', 1],
|
||||
['b', 2],
|
||||
['a', 3],
|
||||
['c', 4],
|
||||
['y', 4]
|
||||
])
|
||||
expect(queue.events()).toEqual([[11, ['x', 'a', 'c']]])
|
||||
expect(queue.leases()).toEqual(['a'])
|
||||
expect(moved.editDeadline).toBeUndefined()
|
||||
|
||||
const stale = queue.run({ kind: 'queue-move', input: { messageId: 'b', beforeMessageId: 'a' } })
|
||||
expect(stale.result).toEqual({ kind: 'queue-move', move: { messageId: 'b', status: 'gone' } })
|
||||
expect(queue.head()).toBe(11)
|
||||
})
|
||||
|
||||
it('holds waiting cards and withdraws unsettled ones, ending only invalidated edit leases', () => {
|
||||
const queue = fixture()
|
||||
queue.seed('a', 1)
|
||||
queue.seed('b', 2, { state: 'dispatched', consumedAs: 'send-b' })
|
||||
queue.seed('c', 3, { state: 'returned' })
|
||||
queue.lease('a')
|
||||
queue.lease('c')
|
||||
|
||||
const held = queue.run({ kind: 'queue-hold', messageIds: ['a', 'b', 'a'], reason: 'send_failed' })
|
||||
expect(held.cards.map((card) => [card.messageId, card.holdReason])).toEqual([
|
||||
['a', 'send_failed']
|
||||
])
|
||||
expect(queue.leases()).toEqual(['a', 'c'])
|
||||
const again = queue.run({ kind: 'queue-hold', messageIds: ['a'], reason: 'send_failed' })
|
||||
expect(again).toMatchObject({ cursor: { sequence: 11 }, cards: [], inputChanged: false })
|
||||
|
||||
const withdrawn = queue.run({ kind: 'queue-withdraw', messageIds: ['b', 'c', 'missing'] })
|
||||
expect(withdrawn.result).toMatchObject({
|
||||
kind: 'queue-withdraw',
|
||||
cards: [{ messageId: 'c', state: 'withdrawn', holdReason: null }]
|
||||
})
|
||||
expect(withdrawn.editDeadline).toBe(now + 2 * 60_000)
|
||||
expect(queue.leases()).toEqual(['a'])
|
||||
expect(queue.events()).toEqual([
|
||||
[11, ['a']],
|
||||
[12, ['c']]
|
||||
])
|
||||
expect(queue.versions('b')).toEqual([[1, 1, 'dispatched', 2, [{ type: 'text', text: 'b' }]]])
|
||||
})
|
||||
Reference in New Issue
Block a user