mirror of
https://github.com/stablyai/orca.git
synced 2026-09-30 16:02:56 +00:00
fix(native-chat): turn facts come from the turn record, and /compact is a message the chat sends (#23059)
* refactor(native-chat): remove the unused terminal handoff No client ever called agentSession.requestHandoff or mounted the handoff chrome. Delete the handoff coordinator, the terminal-owner runtime, the proof write path and the unmounted UI. Keep agentSession.handoffStatus, which released desktop clients read for worktree activation, and let records an older build left mid handoff reconcile through the ordinary restart and recovery paths. * fix(native-chat): never let the pre-stop snapshot hold a chat's stop Eviction now drains delivered events before quit's resume-offer snapshot. An unbounded wait there sits ahead of the provider stop, so a sink whose journal write stalls kept the child running until the step deadline aborted the eviction. The offer is advisory: bound the drain and stop the child regardless. Co-Authored-By: Claude <noreply@anthropic.com> * refactor(native-chat): drop helpers only the terminal handoff called `claudeAuthEnvCarriedForward`, `isPathWithinDirectory` and `queryWindowsProcessRowsFresh` lost their last caller with the handoff. The fresh-scan tests now go through `queryWindowsProcessDescendants({ fresh: true })`, the teardown path that still depends on that contract. Co-Authored-By: Claude <noreply@anthropic.com> * docs(native-chat): stop citing the removed handoff in lifecycle comments Six comments still named the handoff coordinator, a handoff suspend, or a terminal-owned session as live participants in the flows they describe. Co-Authored-By: Claude <noreply@anthropic.com> * test(native-chat): type the stalled snapshot drain without a cast Co-Authored-By: Claude <noreply@anthropic.com> * test(native-chat): pin that a start dead before proving owes no settlement The removed restart handoff test pinned this branch; nothing else did. Co-Authored-By: Claude <noreply@anthropic.com> * fix(native-chat): keep the owner-status read behind an in-flight attach The handoff removal dropped the per-session queue from `handoffStatus`, so a read landing mid-start reported the reservation (no owner) instead of the settled chat owner, and shipped desktop clients blocked worktree activation on it. The read is queued again, as it was before the removal. Co-Authored-By: Claude <noreply@anthropic.com> * refactor(terminal): remove the agent-session PTY write gate The gate only refused a write when a PTY had been bound to a chat session, and the only code that ever bound one was the terminal handoff this branch removes. With it gone, every admit/readmit returned "admitted" unconditionally, so the checks on the renderer write path, the runtime controller backstop, terminal.send, agent prompts, preview input and orchestration pointers, the refusal fields on terminal.send and worker-start receipts, the plugin and CLI refusal copy, and the adopted-pane orchestration routing could no longer run. Ordinary writes take the same path in the same order as before. Co-Authored-By: Claude <noreply@anthropic.com> * refactor(native-chat): drop the transcript helpers only the handoff called appendLegacyTranscriptMessages fed the terminal transcript catch-up and proveClaudeTranscriptBranch backed the terminal owner's exit proof. Both lost their last caller with the handoff. Their tests now go through the live entry points instead: the roster bounds through the legacy import, the pinned-read and growth tests through the ancestry replay the history window uses, and the marker rules through the string proof in their own file rather than the session-file resolver's. Co-Authored-By: Claude <noreply@anthropic.com> * fix(native-chat): stop calling a starting chat "mid-handoff" A send refused because the chat's owner is not settled showed "The session is mid-handoff (<stage>)." in the composer. With the handoff gone, the stages that reach it are a chat that is still starting, or one whose previous agent process has not yet been confirmed stopped. The message now says which of the two it is. The refusal code is unchanged. Co-Authored-By: Claude <noreply@anthropic.com> * test(native-chat): type the stand-in roster decoder without a cast Co-Authored-By: Claude <noreply@anthropic.com> * refactor(codex): name the pinned rollout lookup for what it does With the terminal handoff gone, the module named codex-tui-rollout-proof holds only the pinned rollout lookup that structured Codex launches use to resume a thread, so the name described code that no longer exists. Rename the module and its options type. Also drop a mobile allowlist assertion that pinned the removed agentSession.requestHandoff method, which no longer exists to allow. * refactor(native-chat): type the owner-status reply as the host sends it The handoffStatus reply type still listed the terminal handoff's fields and states (terminal placement, host label, proof retry, queued and waiting phases, the to-terminal direction). No host writes them any more and the only client reader parses the reply as unknown, so they described nothing. The reply on the wire is unchanged. * refactor(native-chat): normalize terminal-handoff lease values once at decode Nothing in this build writes a terminal owner (`runtimeKind: 'tui'`) or the handoff's `preparing` / `old-owner-stopped` stages, but the in-memory types still admitted them, so readers across the host kept branches for values no path produces and the compiler could not point at them. The store now validates the on-disk shape, which still accepts those values so an older record is not quarantined, and maps them once while parsing: - `preparing` and `old-owner-stopped` become `recovering` - a `tui` lease becomes `native`; when it records a process it also becomes `conflicted`, the claim every build probes but never stops. A plain native owner would be stopped by restart recovery, here and in older builds. Revisions are taken over the normalized state on both sides of every compare, and the mapped record reaches disk with the store's first transaction, the same way the tab-id backfill does. The in-memory types narrow to what this build writes, and the branches that existed only for the removed values go. Structured-worker identity keeps its verdict for a former terminal owner by refusing a conflicted claim rather than a non-native kind. * refactor(native-chat): stop threading the owner kind through a reservation A reservation only ever names a native owner now, so the request no longer carries a kind and the reserved lease records `native` directly. The attach params keep `runtimeKind`: agentSession.ensure and create accept it, and the operation fingerprint stored in the ledger covers it. * test(native-chat): pin the legacy-lease rewrite with a transaction that changes nothing else Hiding a tab also committed the visibility index, so the no-op transaction wrote the file even when its open-time revision was wrong. Committing the index first leaves the pending rewrite as the only reason to write. * fix(native-chat): name a chat write by its target, not the owner generation A write carried the fence of the last frame the pane read, and the host refused it unless that fence was still current. An idle release and the restart after it each move the fence, and the release publishes nothing, so a send after a release was refused "Expected runtime fence 1; the session is at 3", and a Stop queued behind a cold start was refused as stale. Every write already names what it acts on: a send its conversation, a cancel its turn, a prompt answer its item revision, a rewind its epoch; an option is last-writer-wins. So admission stops comparing the client's fence, and the rebase that papered over one restart (admitAtResumedFence, resumedFromFence) goes with it. The writer-lease check stays, and so does the attach's compare-and-swap. Frames now stamp the fence read when each frame is sent instead of a copy each subscriber kept, which went stale on the same release. * fix(native-chat): every journal append reaches the chats that are open A journal write and its delivery to open readers were two calls, and some writers made only the first. A failed start whose lease could not be handed back, a provider revision with no frame behind it, and eviction's settlement were all journaled without reaching an open chat. A journal handle now reports every durable change, and the host's session map binds that report to the session's readers when the handle is set. Writers no longer publish what they append; the per-writer publish calls are deleted. * test(native-chat): an epoch replacement reaches the open chat * test(native-chat): each row reaches an open chat once, and a live handle enters only through the map * test(native-chat): give the legacy-lease store test a tab id so the backfill cannot supply its rewrite The seeded record had no surface tab id, so the next open backfilled one and that rewrite alone made the no-op transaction write. The test passed with the legacy-lease rewrite signal removed. * test(worktree-activation): restore the OMP surfaced-agent resume test The handoff removal deleted it alongside the terminal-owner tests, but it covers the surfaced-PTY block that still guards resume, including an agent whose ownership is unknown. * perf(native-chat): a publish behind a delivered commit reads nothing Each commit now delivers itself, so the publish a provider frame still sends afterwards found every reader caught up but still read rows and rebuilt the timeline for each one. A caught-up reader now skips the read. * test(native-chat): state why the teardown test's fake journal is safe to cast * docs(native-chat): say mutation admission checks only the writer lease * docs(native-chat): drop the send rebase from comments that still described it * fix(native-chat): a message is accepted, then delivered A send to a chat with no running agent restarted the agent inside the send call, before the message was recorded, so the client waited for the whole start and a failed restart refused the message. Claude held prompts sent during startup, and those could settle as "unconfirmed". A send is now accepted inside the session's serialized queue: one ledger row and one submission row marked handoverRecorded, published, answered pending. A per-session delivery loop exists while a message is queued. It starts the agent through the same serialized attach a hold uses, waits outside the queue for a Claude child to prove its start, and hands the oldest queued message over as its own serialized step, writing dispatch{pending} before the adapter call. A start it needed and did not get writes one error-tone row and rejects every queued message with the same words; a start Stop cancelled writes none. Settlement follows from the rows. A queued message is provably unwritten, so a close, an eviction or an exit rejects it. A handed-over message stays in doubt. A queued row at or below the sequence a handle found when it opened was left by an earlier process and is rejected at open, with no latch. Stop withdraws queued messages with no writer lease and no fence. An attach failure keeps the conversation open, and the attach adopts its journal. Owed work counts the loop and queued rows. A compaction or rewind found prepared when a conversation opens was started under a child this process no longer has, so the open settles it rather than leaving it to refuse every send until a view attaches. The open cursor is scoped to its epoch, because sequences restart when an epoch is replaced. Deleted: restart-before-admission, recordFailedRestart, the fence rebase, Claude's startup gate, the attach's forget on failure and its own crash boundary. Clients without agent-session.accepted-send.v1 get their reply held until the handover; the desktop and paired desktop lists advertise it. * fix(native-chat): settle queued messages only for the child that ended A child that proved its start and then exited before its message was handed over left the message queued: the exit settlement returned early when nothing else was in flight. Delivery then started another child for it, and a child that died the same way started another, without end and without a row. A retried settlement for an earlier generation, run by the attach that delivery started, did the opposite: with that generation's turn unfinished it rejected the message queued for the child being attached. The settlement now takes the rejection for queued messages from its caller. The unexpected exit and the eviction pass one, and it applies even with no other work in flight; the retry for an earlier generation passes none. * fix(native-chat): an adoption that fails to import keeps the conversation open The attach now writes into the conversation's own open journal, but a failed transcript import still closed it as if it were the attach's provisional one. The conversation stayed indexed with a closed journal, so every later send answered "could not be recorded" and every attach failed again until the app restarted. The import now closes only a journal the attach opened for itself. * perf(native-chat): the recovering open reads the journal once Every conversation open now goes through the recovering open, including the read restore of every chat at startup, which used to replay its journal once. The recovering open replayed it twice: once to probe it and again inside the open. The probe is now handed to the open as its load. * fix(native-chat): an attach that fails after indexing its child leaves no child behind A failed attach now keeps the conversation open, but a failure after `onAttached` indexed the child (the rewind or compaction recovery, or the attach's own success record) left that entry claiming a child the failure path had already released. The next send found the phantom, skipped the start, and wrote at a fence the journal had moved past, so the message stayed queued for good. The entry now drops the released child and its event sink, and follows the record's fence, as a failure before indexing already did. * fix(native-chat): a withdrawn message shows no error, and a rejection outlasts the send's answer The error strip for a message the host accepted and then did not deliver matched the entry before the outbox reconciled, so a Stop's withdrawal, which the reconcile drops, showed "Orca could not send your message" with nothing to retry. It now reads the reconciled entry. A rejection the journal records before the send's own pending answer lands is final as well: that answer no longer puts the entry back to dispatching with no Retry. * fix(orchestration): a structured worker whose agent outlasts the preamble wait is left unknown, not torn down The preamble waits for its submission to be delivered while the worker's agent starts. When that wait ran out it threw operation_unknown, and the failed-start teardown then closed the session, which rejected the very preamble the host was about to deliver. It now reports a turn start nobody observed yet: the worker is start-unknown with its session kept, the host delivers the preamble when the agent starts, and the worker's report settles the dispatch as for any unobserved start. The receipt no longer suggests reading a screen a structured worker lacks. * fix(native-chat): a message rejected while its chat was closed reads as not sent A remount reads an entry it left dispatching as unconfirmed. When the journal had rejected it meanwhile, as a failed start or a quit now does, the reconcile left it unconfirmed: it blocked every later message behind a Retry and no reason, and the delivery probe, seeing the journal already answered, never ran. The reconcile now settles it as rejected like a dispatching one. * test(orchestration): name why the readiness settlement fakes are cast * fix(native-chat): keep each pane's own fence on frames so a failed restart is not resent * docs(native-chat): drop the fence from the admission the send effects run behind * docs(native-chat): give the fence move on release the reason that still holds * docs(native-chat): stop citing a write fence check in launch and mailbox comments Three places still gave the removed fence check as a reason: the launch replay said admission puts the ledger ahead of the fence, the launch surface said a send must name the lease it was admitted against, and the direct-mailbox path said the lease fence decides whether delivery is safe. Admission now checks only the writer lease. * refactor(native-chat): the provider child is its own record A conversation now outlives any number of provider children, so the child is one record on the conversation's entry instead of five loose fields beside its journal. It is written in one place: indexed only once an attach has fully succeeded, and ended through one function that an exit, a failed re-attach, a Stop and an eviction all share, matched on the child's generation and fence. - A failed attach writes no child, so there is nothing to unwind: the field unwind and the fence patch after it are gone. - Conversation writes read the record's fence, the way mutation admission already does; a child's own writes use its fence. The four stored-fence patches, and the settlement retry's overwrite of the conversation's fence, are gone. - The owed wind-down is its own tombstone, carrying the child it is owed for, and is no longer dropped when an attach replaced the whole entry. - Stop on a child still proving its start stops only the child: its lease goes back and the chat is told it is idle, but the journal, the holders and the readers stay. Close is that stop plus the conversation's close. - The settlement retry uses the conversation's own journal, opened through the host's one open. * fix(native-chat): the delivery loop alone settles a message its start or child failed A queued message was settled by whichever path happened to end the child first: the loop, the unexpected exit, eviction's work settlement, the open's leftover rule, and the startup branch that rejected every pending row. That gave two failure rows with different tones for one start, a loop that could hand over to a different child than the one it waited on, and a Claude start that died while starting reading unlike every other failed start. - The loop remembers the child it waited on. At handover, if that child is gone or replaced, it reads how it ended: a Stop continues; anything else writes one failure row and rejects every queued message with the same words, then stops. A child still starting whose start the adapter says did not land fails the same way. The exit, eviction and the settlement retry only settle the handed-over and legacy rows of the child that ended. - One failure row, always an error, keyed by the start. A start a view began that dies with nothing queued writes the same row through the same builder, so a second report revises it. - The open no longer rejects leftovers; the loop's first step does, and the open wakes it. - `awaitStarted` answers why a start did not land, so the row says it even when the loop sees the failure before the exit is processed. - Quit closes every conversation the way closing a chat does: what is still queued is rejected as closed, with or without a child, and a start the loop already has in flight is waited for so the child it produces is stopped rather than left behind. * refactor(native-chat): a stopped child ends on the one reading of its stop The eviction step reads a stop's result through `stopAgentSessionProviderRoot` and hands that verdict to the child's ending, so the host never forms a second view of whether the root is gone. Every ending carries it: a stop's comes from that reading, an exit's root is gone by definition, and a failed re-attach passes what its release saw. The end-of-child record can therefore also carry a stop whose root was not seen to go, which nothing ends on yet. * feat(native-chat): the host says it accepts a send before any agent has it The host now lists agent-session.accepted-send.v1 among its own runtime capabilities, the same string capable clients already send. A client can then tell a host that answers a send at acceptance, and admits a Stop with no writer before a turn starts, from an older one that still restarts the agent inside the send. Additive: an older client ignores a capability it does not know. * refactor(native-chat): an attach never opens a journal of its own The attach adopts the conversation's open journal, which outlives it, so it no longer opens one for a direct caller either. That leaves nothing for a failed adopted import to close, and the flag that told the two cases apart is gone. Tests that attach without a host open the conversation the way a host does. * fix(native-chat): a moved fence resends nothing on a host that accepts first The outbox treated any fence change as a new owner: it dropped the answer of a send in flight, queued that send to go out again under the same id, and unblocked a refused head. On an older host that is how a send the restart refused, unrecorded, gets another try. On a host that records every send before it starts an agent, a fence moves because that start ran, so the same rule resent into every failed start. With a fence stamped on every frame, that became a loop. The outbox now reacts to a fence change only when the host has not advertised that it accepts a send before any agent has it. On such a host, only a Retry or a new send goes out, and a failed start reaches the client as a rejected message it keeps with its Retry. Against an older host, or before one has answered, the outbox behaves as it did. Desktop and paired web share this hook. * refactor(native-chat): a child's end says whether the user or the host stopped it The end-of-child record's cause now tells a user's Stop from the host stopping the child for a cause of its own: `user-stop` and `host-stop` replace `stop`. The delivery loop goes on after a user's Stop, as before, and fails the start it was waiting on after a host stop, with the one error row and every queued message rejected, in the stop's reason when it gave one. The reason stays description only. Stop passes `user-stop`; nothing passes `host-stop` yet. * fix(native-chat): a chat whose only work is a queued message is not offered for resume A message accepted while the agent was starting counts as working in the chat, and quit rejects it as never sent. The teardown snapshot read the same working rule, so a relaunch offered to resume a chat whose agent never had the message. The snapshot now reads only what was handed over. * fix(native-chat): the conversation outlives its agent Opening a chat no longer starts its agent. A conversation is reached through one host accessor that opens its journal at rest, and a send is what starts the agent, through the delivery loop. One idle sweep, every five minutes, stops an agent that has been quiet for thirty minutes and owes no work, then drops an open journal handle that is only a cache. Its record, tab, status row and readers stay. - hold and release are no-ops; hold still builds the host for shipped mobile builds. - The holders, the holds, the release clock and the exit respawn are deleted. - Options, the model list, the goal and the context meter answer at rest; a model pick at rest is recorded as intent for the next start. - Compact, rewind, clear and goal changes start the agent first. A send does too when a rewind is still in doubt after the conversation opens. - Orchestration routes mail and group addresses on ownership (the record plus the chat tab), not on whether the process runs. An open dispatch keeps its worker running. - The restart continuation is a send; Resume all holds each slot until the message is handed over or rejected. - A read error never replaces a loaded transcript, and shows the host's own words. * test(native-chat): type the queued-message fixtures in the resume-offer tests * fix(native-chat): a start that dies while a message waits on it is that message's failed start Opening a chat's tab starts an agent for the view, and a send accepted meanwhile waits on it. When that start died, its exit wrote the start's error row and left the message queued, so the delivery loop started a second agent into the same failure and wrote a second row. A child's end now records where the conversation's journal stood, and the loop settles a message accepted before a failed start ended with that start: one row, under its key, and no second start. A message sent after the failure still gets a fresh start. * fix(native-chat): a request that failed reads as failed A structured chat whose only message the agent's start refused read as a green finish, and a cancelled structured turn did too: the host published a verdict only for turn records, and structured rows carried no `interrupted`. The host projection now reads the session's latest request: its turn's outcome, or `failure` for a send the agent or its start refused. A send that was withdrawn, or left undelivered by a restart or a close, fails nobody and makes nothing listable. The ingest publishes `interrupted` as the hook lanes do, and every reader decodes the verdict through one accessor, so a failure reads Failed on the dot, the rollups, history and `worktree ps`, behaves like a cancellation in every clean-finish policy, and notifies as "failed". * docs(native-chat): say what an attach's open conversation and unconfirmed ids are now * test(native-chat): a verdict change republishes the mobile status projection * refactor(native-chat): the store's retention trigger keeps its flag compare A verdict change always moves the completion clock the same check already reads, so a second verdict compare there caught nothing new. * test(native-chat): a user message the provider journaled keeps its session listed * test(native-chat): pin what a failed start settles, and what a resume offer names A view's child that dies while a sent message waits settles that message only when it died starting and no child has taken its place: a proven child's crash, or a second start since, gets the message delivered. The resume offer names the handed-over message, never a newer one still queued. * test(native-chat): the failed-start pins fail on what the message became, not on a timeout * fix(native-chat): a restart offer ends when the chat's agent starts again The offer used to end only when the chat's newest user message changed, because opening a chat started its agent and that start could not be told apart from real activity. Opening a chat starts nothing now, so the host reads the fact it already publishes: a chat's status row goes from not host-owned to host-owned exactly when its agent is started. At that edge the offer and any failure record for the chat are withdrawn, unless the start is a resume action's own (its continuation is the oldest undelivered message). A continuation and a message racing to be first are decided at acceptance: the continuation is refused, quietly and with nothing filed, when any other message was accepted since the restart. A failed continuation start leaves the offer retryable, and each resume action sends its own message id. Deleted: the newest-user-message comparison, its journal reader, the continuation filter, and the failure ledger's own "answered by the chat" check. The marker still carries its message id for one release, so the previous build can read it. * fix(runtime): end a transcript stream when its client unsubscribes Desktop: the IPC subscription controller was dropped as soon as the streaming handler returned, which for most streams is right after it binds. A later runtime:unsubscribe then found nothing to abort, so the host kept the subscriber and derived and sent every publish to a channel no one listened to. The controller now lives until the renderer unsubscribes, resubscribes the same id, or goes away. Mobile: disposing an agentSession.subscribe stream now sends agentSession.unsubscribe with the stream's frame id, so the host ends that subscriber and leaves a sibling stream on the same socket running. The direct path now passes the frame id the relay path already passed. * fix(native-chat): a late provider-session update keeps a failed recovery record failed A provider-session heartbeat that rewrites a completed recovery record kept its interrupted flag but dropped the outcome it was copied with, so a live failed checkpoint read as a clean finish until the next status write. * test(orchestration): the preamble's host stub is typed, not cast The preamble send now takes only what it reads of the host, the send, the settlement wait and the record's fence, so its test builds that host with real types instead of `as never`. * test(native-chat): the terminal-bell check asserts the renamed verdict field The bell notification test still checked for agentInterrupted, which no longer exists, so it could not catch a verdict leaking into a bell dispatch. * fix(native-chat): a failed turn ranks like a completion for attention Attention readers (completion time, Smart Sort, sticky retention, Cmd+J Recent) now demote only a turn the user stopped. A failure is news the user has not seen, so it keeps its completion time, ranks in the Done class, stays retained after its pane goes away, and a retained failure reads failed in the worktree rollup instead of done. Clean-finish policy (hibernation, pane ownership, the value moment) still treats a failure like a stop. The retention trigger compares verdicts again: success -> failure no longer moves the completion clock. * fix(native-chat): one fact ends a restart offer: the chat moved on since the restart The offer is live while no other message has been accepted in the chat since the restart and its agent has not proved a start since. The offer list, the resume's reservation check and the continuation's acceptance check all read that one fact, so a message whose start then failed withdraws the offer too, and a stale click finds nothing to act on. The fact is read off the conversation's open handle, which the restart closed, so it is retired durably whenever it may have changed: a message accepted, a start proven. A close and reopen within the same run therefore cannot bring the offer back. A continuation rejected before it reached the agent does not count, so a retry after a failed start still runs. Deleted: the quit-time gate on withdrawal, which changed nothing because the withdrawal and the quit's own offer write share one queue; the per-action "withdrawn" flag and the separate acceptance check it paired with. * test(native-chat): an older build reads the restart offer this build records The offer lives in a file the previous release reads after a downgrade. Pin that against the pinned release's own capsule, and run the lane when the marker or the capsule changes. * fix(native-chat): read a restart offer against where the journal stood when it was taken "Since the restart" was read off the conversation's open handle, which the idle sweep closes: after a reopen, a message the user had already sent looked older than the handle and the withdrawn offer came back. The offer now records the journal position (epoch and sequence) at the moment it is taken, and a message accepted after that position, or a journal on another epoch, means the chat moved on. That is derived from the journal, so it holds across any number of closes and reopens. An older build's offer has no position; only a start withdraws it. Because the message half is now durable, the offer is no longer rewritten in the recovery file on every accepted message; a proven start still writes it, since only the host that saw the start knows of it. * test(native-chat): wait for the listing's retire write before reading the recovery file * refactor(native-chat): every journal row states which turn it belongs to Rows gain a turn scope stated by the write that creates them: the open root turn, or the conversation. A queued message takes its scope from its handover. Rows stored before scopes existed are placed on replay by the root turn open when they were created, so no persisted state is needed for them. Rewind keeps each retained row's scope and producer, so a subagent's row stays its own. * fix(native-chat): keep the terminal-backed chat's read error over its local echoes Messages winning over a read error is right for the structured chat, whose read retries and whose messages came from the transcript. The terminal-backed view assembles its list from local echoes too (a launch prompt, a pending send), so a failed read there showed only those bubbles and no error. Only the structured pane now keeps messages over an error. * fix(native-chat): a start retries the exit settlement a failed journal write left owed An agent exit whose journal settlement write failed releases the lease latched until a retry lands. Reopening the chat used to be that retry; with reveal now only opening the journal, nothing retried it before the next app launch, and every send was refused. The start the send needs now runs the retry first, where the attach would. * fix(native-chat): a failed main agent reads failed while its subagents still work The verdict is now read from the main agent's own state, not the folded row: a main agent that is done and failed has a verdict even while its subagents keep the row working. Without mainAgent (history, worktree ps, older hosts) the old combined-done rule stands. Display marks the verdict through agentVerdictDisplayMark: a failure outranks every combined state on the agent's dot, label, tab badge, dashboard and activity rows; a stop marks only a done row, so a successful or stopped main agent with live subagents still reads working. Subagent rows keep their own state. The worktree card, terminal tab and Cmd+J rollups share one pane fold and rank a pending question, then failed, then working, monitoring, interrupted and done. worktree ps publishes the main agent's outcome on a working row, and the mobile mirror reads it. The store's change check, the paired-client mirror's equality and its epoch now see a verdict change on a working row, which otherwise moves no state or clock and left the worktree card reading working. Clean-finish policy is unchanged: a working row is never hibernated and has no completion time. * perf(native-chat): answer the owner check without opening the chat Worktree activation calls agentSession.handoffStatus for every chat tab in the worktree, and the answer comes from the session record alone. Reaching it through the accessor opened each resting chat's journal (a full read, the crash-boundary write and a restored status publish), then kept it open for the idle window. It now checks the record and the adapter's support, as before this series, and opens nothing. * fix(native-chat): a read waiting on the session lock opens nothing once quit began The accessor checked for quit before queueing the open, so a read queued behind a session task ran its open after teardown had begun and indexed a journal no teardown step would close. The check now runs at the open itself. * test(native-chat): pin stated turn scopes, the upcast of unscoped rows, and rewind attribution * fix(native-chat): /compact is a message the chat sends, run as a turn of its own The conversation command RPC now accepts /compact into the queue like any send and answers once it is handed over. The delivery loop opens the command's own turn, starts the provider on it, and waits for the provider's end off the session's queue, so messages typed meanwhile are held and delivered after it, even when it fails. It settles by re-reading the journal: a child that died meanwhile already wrote the verdict. Stop ends the command at once. The 180 s completion window, the unconfirmed row and the recovery of an older build's compaction record are gone; that record no longer gates anything. On Codex the provider turn the command opens is claimed into the command's turn. * fix(native-chat): read a failed resume's chat before calling it retryable Whether a failed resume is retryable is the offer's own rule: the chat has not moved on since the restart, read from its journal. The failure list read it only for a chat already open, so once the idle sweep closed a chat the user had moved on in, its failure showed Retry again, and the click did nothing. The list now opens the failed chats first, as the offer list does. * test(native-chat): type the provider event sink the settlement test reaches for * docs(native-chat): the worktree ps outcome comment no longer claims old hosts send it The field is new: an old host sends no outcome at all, so a reader falls back to interrupted. The removed clause said old hosts send it on done rows, which never shipped. * fix(native-chat): say the structured read keeps trying only where it does The structured pane's "Orca keeps trying to load it" line never showed: the view state filled in an untranslated fallback whenever the read error had no text, and the empty state prefers any message. The view state now leaves the message out, so the structured pane shows that line and the terminal-backed pane its own translated one. Mobile's structured lane does not resubscribe after an error frame, so it no longer makes the claim. * fix(native-chat): rows group under the turn their record names, not the one above them Each row's turn is the turn its stated scope names, anchored on the entry that opened it, or on the turn itself when the provider opened it unasked. So /compact groups its own rows and the previous turn is untouched, a message typed into a running turn joins it, and a provider-resumed turn folds under its own Worked-for. A row reporting how a turn ended, an error or the compaction separator, never folds. Desktop and mobile read the same keys; a host that states no scope keeps today's positional grouping. * test(native-chat): await the send's settlement instead of polling for the start The at-rest send tests polled for the provider start with vi.waitFor's one-second default, which a loaded machine outran. They now await the host's own settlement of the message. * docs(native-chat): the status-store listing rule names provider-journaled user messages * fix(native-chat): a restart offer resumes any time after the quit, and knows its own continuations The continuation's message id was dated by the quit, and the ledger refuses a new id dated more than a day back, so Resume or Retry a day after quitting was always refused (on main too). It is now dated by the resume action. Telling a rejected continuation from the user's own message read the operation ledger, whose rows expire after about a day; after that a failed resume stopped being retryable. The offer now records the continuation each action sends on its own capsule entry, bounded to the newest 16, so the ids end with the offer. The ledger read is deleted. * fix(native-chat): a /compact is not a request the sidebar, notifications or restart resume report The sidebar's prompt, preview, verdict and instant, the turn-completion feed, and the restart-resume marker read past a conversation command and its turn to the last real request, so a /compact neither notifies nor re-dates the row, and a command in flight is never offered as work to resume. An older client shown a command's turn in the legacy form names the session's own agent. * fix(orchestration): route no mail to a structured worker its orchestration released A structured worker is routed on ownership, and a resting worker's lease is released, so ownership held while its chat tab stayed listed. A worker the coordinator abandoned and then released, found at rest by the release, therefore still took peer mail and @worktree: broadcasts, and each one restarted its agent. Routing now also reads the orchestration's own resource row: once it is released, direct mail, group addressing and worker-show's addressable answer drop the worker, as they would a terminal worker whose terminal closed. The chat tab stays, and nothing new is stored. * fix(native-chat): a failed retry names the user's prompt, not Orca's continuation A resume's continuation is written to the chat before its start, so after a failed attempt the chat's newest user message is that rejected continuation. A second failure then showed Orca's own restart text as the chat's prompt. A retry now keeps the prompt its first failure named. * test(native-chat): pin what a conversation command's admission refuses at rest and at handover * test(native-chat): tests merged from the base state which turn their rows belong to * fix(native-chat): a refused send notifies failed through the completion feed The host's completion feed followed only the newest turn, so a send the agent or its start refused, which creates no turn, read Failed on its row but sent no notification. The feed now follows the session's latest request, read from the projection the status feed already makes for the commit: a turn keeps its id, a refused send is named by its journal item key. It announces only while the session is idle, as the row reports a verdict, so queued sends refused one commit at a time notify once, and a withdrawn send falls back to a request already announced. * fix(orchestration): read the released row optionally, as the authority does worker-show's observation called the row lookup directly, which a runtime double without it threw on and failed the structured tab-retirement release. * chore(native-chat): one import per module and no unexplained casts in the turn-scope changes * test(claude): pin which turn a Claude row joins, including a subagent's after the turn ends * fix(native-chat): the status bar drops a restart offer the chat moved on from The renderer re-read the host's restart offer only when a failed chat showed activity, so after a message withdrew a pending offer the host answered no chats while the status bar kept counting one, and clicking it opened nothing. The same watch now covers pending offers: a status change in an offered chat asks the host again, once. * fix(native-chat): a refused steer is read from the turn its handover named The latest-request reader decided whether a refused send had joined a running turn by comparing host clocks: its handover time against the previous turn's end. The handover row now states the turn it delivered into, so the reader reads that instead and the clock comparison goes. A journal written before handover rows stated a turn is scoped on replay from the turn open when each row was written, which can differ from the clock reading only when a send and a turn's end share a millisecond. * fix(mobile): the native-chat controller contract carries the turn journal The controller and overlay already pass nativeChatTurnJournal, but the contract type never declared it, so mobile failed to typecheck. * fix(native-chat): the live turn is the running turn, not the newest user row A turn the provider opened on its own (a background wake, a resumed turn) anchors on its own record, but the list still treated the newest user row as the live turn. While such a turn ran, the settled user turn before it lost its duration and the running turn's own rows were drawn as settled, so its tool calls lost their live state. nativeChatTurnMembership now answers both questions from the turn record: each row's turn, and the live turn (the running root turn's anchor, else the newest user row, which is also all an unscoped host has). Desktop and mobile key liveness, the timing clock and the live status's row on it. * test(native-chat): a turn the provider opened keeps its own clock Pins that the local turn clock follows the live turn, so a wake after a settled turn does not restart that turn's clock when no host durations are recorded. * fix(native-chat): a running turn no message opened draws its status on no row Its live status belongs to the transcript-tail indicator alone. Once it settles, its duration draws at its first row as before; a running turn a message opened still draws on that message. * fix(native-chat): every copy of a row carries the main agent's own status History entries, sleep records and `worktree ps` rows carried a flattened top-level `outcome`, copied under different gates and without the main agent's clock. They now carry `mainAgent` (state, outcome, stateStartedAt), the type the live row already persists and sends, and every copy site takes it with `interrupted` through one function, `agentVerdictFields`. - The accessor reads `mainAgent` then the legacy flag; the mobile mirror matches it line for line. - Sleep records admit `mainAgent` with `normalizeMainAgentStatusField`, so a malformed value drops the field, never the record. - Mobile dates a main agent that failed under live subagents by its own clock, as desktop does, and its row equality compares `mainAgent`. - The activity feed reads a history entry's own `mainAgent` instead of rebuilding one; the sync key and history equality compare it. * test(native-chat): pin the worktree ps verdict across host and phone versions Pairs the real v1.4.212 host and phone row reader with this build: an old phone reads a new host's rows by `interrupted`, a new phone reads an old host's rows (no `mainAgent`) the same way, and a new phone reads a failure under live subagents as Failed, dated by `mainAgent.stateStartedAt`. The release checkout now carries the phone's self-contained row reader, and the lane runs when the `worktree ps` row producers change. * test(mobile): name the parity table's row for its role * test(native-chat): a roster of idle or finished children does not keep an agent awake The sweep reads owed background work through the shared child-work liveness that upstream's release clock adopted; a child that went idle or finished is not work the agent still owes. * fix(native-chat): a request that settles while the user is asked something notifies once The completion edge waited for an idle session, and a pending prompt (including a subagent's approval) is not idle. Structured chat has no other attention producer, so a main turn that finished while a subagent waited on the user sent nothing until the prompt was answered. The edge now waits only on owed work (a running turn or an unanswered send), which the projection reports even beneath a pending prompt. A request that settles with a prompt pending announces once; the renderer words it "needs input" from the host status mirror's `attention`, and answering the prompt keeps the same request identity, so it does not announce again. The wire shape is unchanged. * fix(orchestration): a task dispatched into a resting structured worker keeps it running The sweep's open-dispatch check read only the worker-start dispatch that owns the worker's terminal resource, so a task later dispatched to the same worker (orchestration dispatch --to, which writes a dispatch with no worker row) did not count: after thirty quiet minutes the worker was stopped while that task was open, and its coordinator read exited. Any unsettled dispatch addressed to the worker's process incarnation now counts, derived from the existing rows. * fix(native-chat): a command's wait ends when its child does The delivery loop waited for a /compact only on the adapter's compaction tracker, which learns of the child's end only on some exit paths: a Codex exit or close, and a Claude close, never reach it. The wait then never ended, so nothing queued behind the command was delivered again, Stop had no child to answer through, and the tracker's leftover entry refused the next /compact. Every way a child ends passes endProviderChild, so the host now offers a per-child end signal there. The loop races the tracker against it (the dead-generation settlement has already written the command's verdict), and on that end asks every adapter to release the command, so a later command runs and no later provider turn is claimed into the dead one. The adapters' own exit-time releases were unreachable (Codex) or covered one path of several (Claude), and are removed. The Codex RPC test harness moves to its own module so the exit can be driven through the real adapter's connection callback. * fix(native-chat): keep refusing sends during a command on an older host An older host's controller still refuses a send while a conversation command runs, so dropping the client's block turned every message typed during /compact into a 'not sent' row with Retry there. The block stays for hosts that do not run the command as a send-path turn, and goes only for those that do. The signal is one the client already holds: a host that runs /compact on the send path states a turn scope on every journal row it writes, the same fact turn membership uses to tell it from an older host. Both now read it from one predicate. On an empty conversation, or one whose rows all predate the upgrade, the signal is absent until the command's own entry streams in, so that brief window keeps the old local refusal; no capability or wire field is added. * docs(native-chat): comments stop describing the hold this PR removed Eight comments still justified orderings and teardown choices by a viewer or dispatch hold that pinned the provider child. Nothing holds any more; the orderings stand for the binding's redrive subscription and parked mail, and a chat's agent runs from a send until the idle sweep rests it. Comment-only. * fix(native-chat): the completion says when the user is being asked A request that settles while a prompt waits on the user was worded "needs input" from the renderer's status-feed mirror. Remote clients receive the status and completion streams over separate sockets, so they can arrive in either order and the wording could be wrong both ways. The host already knows at emit time, so the completion now carries an optional `awaitingUser: true` in that case and omits it otherwise. The renderer words the notification from that field alone and no longer reads the status mirror. Old clients ignore the field and word by outcome; old hosts never send it. * fix(native-chat): a restart offer keeps the start its own continuation made Whose start ended an offer was decided at read time, from whether the offer's continuation was still the queued message. Once the provider refused that continuation, the child it had started read as someone else's start, so the offer ended and its failure showed no Retry. The delivery loop now records which queued message a start is for on the in-memory child, and the child's end carries it; the offer counts a start as its own when that message is one of its continuations. * fix(native-chat): a rewound turn still names the message that opened it A Codex rewind rebuilds the epoch without submissions, so each sent message survives only under its provider key. The kept turn records still named the submission key, so each turn anchored on itself and its rows grouped apart from the message that opened it. The rewind now renames the turn's opener along with the message. * fix(native-chat): Stop ends only the command it names Stop on a command turn abandoned whatever compaction the session had pending, so a late Stop for an earlier /compact cancelled the one running now. The tracker now ends a command only when the Stop names its turn, and the cancel reply reports whether it did. * fix(native-chat): an agent gets a full idle window after its owed work ends The sweep measured quiet only from the last journal row, so once a subagent, command, monitor or dispatch that had outlived the window ended, the agent was stopped at the next tick. A child can read done before the lead's wake-up turn writes anything, and stopping in that gap loses the wake-up. The sweep now counts owed work it observes as activity, which gives the agent the full window afterwards, as the release clock it replaced did. * test(claude): the options-read fixture runs a live child The fixture marked its conversation running with a hasProviderChild field the session type does not have, so the read took the at-rest path and refused a session with no record. It now carries a child, which is what the read checks. * test(native-chat): host tests reach its collaborators through a typed seam The rest-test rig and three test files read the host's private members with Reflect.get and cast the result. The host now exposes one test-only accessor, collaboratorsForTests(), and the subscribers class a subscriberCountForTests() beside its existing retainedActivityCountForTests(), so the tests are checked against the real types and the casts are gone. * fix(worktree-status): a departed agent's failure yields to live work on the worktree card A retained failed agent has no expiry, so ranking it with a live failure pinned the card to Failed over other panes' live work. It now ranks below working, monitoring and permission, and above every finished outcome. * refactor(orchestration): one owner answers a structured worker's custody Routing, group addressing, worker-show and the idle sweep each composed their own reading of whether orchestration still holds a structured worker, so each new obligation or retirement state had to be added to every reader. structured-worker-custody now derives both answers from the worker-terminal list state coordinators see in worker-list: addressable is owned and not released, and owed work is an active custody or an unsettled task dispatched to the same incarnation. The owner's state is read through the remote dispatch attachment too, as the terminal transfer lookup already does. Behaviour is unchanged; a settled worker awaiting its coordinator still rests. * refactor(orchestration): owed work is an open dispatch on the worker's incarnation A supervised worker's own dispatch context stays open exactly while the worker is active, so the separate active-custody branch only repeated it. Owed work is now one fact, which also states the policy that a worker awaiting its coordinator's decision may rest, and both custody decisions are written once at the top of the module. * docs(agent-status): a departed agent's failure ranks below live work on the worktree card * fix(native-chat): a restart offer knows its continuations by a tag in their id The offer recorded each continuation id in a list on its capsule entry, capped at 16, and a running action's id in memory. Both could disagree with the journal: past the cap an old rejected continuation read as the chat moving on, and a crash during a retry restored the failure's older entry, which lacked the retry's id. Each continuation id now carries a tag derived from the offer (its teardown and chat), then the action's own part, so any continuation of this offer, queued or rejected, is recognised from the journal row and the marker alone. The persisted list, its cap and the in-memory action map are deleted; the agent-start withdrawal keeps an offer whose own continuation the start was for, read against the stored marker. * test(runtime): the legacy-worker reveal test judges its stale snapshot inside the wait The tui-idle probe reads through readTerminal, which now awaits the structured worker check before the PTY read, so the probe's snapshot request starts a microtask later. vi.waitFor missed it on its first check and polled again at 50 ms, the same moment the wait's own 50 ms timeout fired. The stale snapshot then resolved after the wait had already timed out, so the test passed without judging it, and the rejection landed before any handler was attached. Vitest reported that as an unhandled error and failed the shard. Polling every 1 ms sees the request within a few ms, so the snapshot is judged while the wait is still pending. * fix(native-chat): a message held behind /compact is drawn where it was handed over A message typed while /compact runs was drawn above the compaction's result, between itself and its own answer. The reducer kept every item at the sequence and timestamp of the row that created it, and a queued message is created at acceptance, long before the command it waits behind writes its result. The phone orders by that sequence and the desktop by that timestamp, so both put the message first. A queued message now takes its position from its handover row, the same row that already states its turn scope. Everything the agent did before the handover, a command it waited behind included, draws above it. This holds for every held message, not only /compact's, and needs no client change: every client, older builds included, reads the position the host publishes. A live batch already carries the item when its dispatch row lands, and history pages cut the reduced timeline by sequence, so paging stays contiguous. * fix(native-chat): a phone's send during /compact answers without waiting out the compaction A client that predates accepted-send replies, which is every phone build, has its send reply held until the host hands the message over. A message sent during /compact is not handed over until the compaction ends, so the phone's 15 s request timeout fired first and showed the message as unconfirmed. That wait now also ends once the message is queued behind a running command. This is read from the journal's running turn and needs no new state. Every other wait still ends at the handover: behind a starting child or an ordinary turn, and for restart resume, the command front door and orchestration, which keep the plain handover point. * perf(native-chat): a rewind places provider items with one pass over the merged rows A Codex rewind gives each provider item the old epoch never held the turn record for its provider turn. It found that record by scanning every merged row, restoring each row's body, once per provider item. That is quadratic, and it runs on the host's main thread up to the journal's 10,000-row cap, twice per rewind. A rewind record written before rows carried their scope holds no scope for any provider item, so it paid the full cost. The merge now indexes turn records by provider turn id once, keeping the first match as the scan did, and each provider item looks its record up. * fix(native-chat): a view never restarts a chat whose last start failed A Claude chat whose CLI exits during startup left one red row per start, and every time a view bound to it (the chat opening right after its create died, or the user switching back to it) the hold started the CLI again, so the same launch-failure row repeated. Only a send retries a failed start now, the same rule provider-exit recovery already applied; the rule lives in one predicate the hold, exit recovery and the delivery loop share. * fix(native-chat): a message waiting behind /compact is drawn after it until it is sent A message sent while /compact runs is placed where it was handed over. It was still drawn where it was accepted until then. /compact writes its result one step before the handover, so for that step the waiting message sat above the compaction's separator. A message the host accepted but has not handed over is not part of the conversation yet, so both clients now draw it after everything the agent has done. The shared projection moves it to the end, which is the order the phone draws. The desktop ranks it with the other not-yet-sent rows, after the streaming preview. At handover it takes its place from its handover row, which is also after the separator, so it never appears above the compaction it waited for. * fix(native-chat): the idle sweep reads owed work every tick Owed work counted as activity, but the sweep read it only once the idle window had elapsed, so it refreshed the clock at most once a window. Work that ended just before the next read left the agent to be stopped at that read, moments after the work ended, which is the gap the refresh was meant to cover. The sweep now reads owed work on every tick for a started agent, so the window always runs from the last tick that saw work owed. * fix(native-chat): a continuation handed to the agent stays sent The offer read its own continuation as not reaching the agent while its dispatch was pending, which also covered one already handed over and still unanswered. When the wait for that answer ended first, the failure it filed read as retryable, and a retry sent a second continuation to an agent that may have acted on the first. Only a continuation still queued, or rejected, is now read as unsent. * test(native-chat): start the child the loop waits on with an attach, not a second view A view no longer starts a child whose last start failed, so the R2 case that waits on a child started since the failure now gets that child from a client attach, the one non-send starter left. * fix(native-chat): settle a gone generation's turn wherever a conversation opens A send that opens a chat this process had not read yet (after a crash, from a phone or the CLI) went through the delivery open, which never settled what the dead generation left running; only the read restore and a successful acquire did. When the send's start then failed, the turn stayed running for every reader. The settlement now runs in the one journal open, at the crash boundary, for every opener except an acquisition, which settles from the evidence it read before its reserve; the read restore's separate step is gone. * test(native-chat): prove the next child's start settles the turn an earlier child left The R1 case lost its only settlement assertion when the latch it checked was deleted. It now seeds the running turn the earlier child left and asserts it ends at the exit's receipt, with the exit's row, before the message is handed to the new child. * test(native-chat): count a failed start's rows by row, not by text Comparing the set of texts passed when two different rows carried the same words, which is the duplicate the test exists to catch. * test(cross-version): load the phone row readers without mobile's toolchain Vite transforms a file against its nearest tsconfig, and mobile/tsconfig.json extends expo/tsconfig.base.json, which the root-only cross-version lane never installs. The worktree ps verdict suite imported the current phone row reader from mobile/ directly, so CI failed with TSConfckParseError before any test ran. The harness now imports a copy of the working-tree reader placed under the checkout cache, where the root tsconfig applies, as it already does for the release checkout's copy. Both readers are still the real files. * test(cross-version): keep the checkout path-guard message and justify the copy import's cast * fix(native-chat): a command ends only by its own provider answer or its child's end Stop no longer settles a conversation command. It interrupts it like any turn, and when the provider cannot take that (Codex has not opened the command's turn yet, or Claude refuses the interrupt) it stops the child, whose dead-generation settlement writes the verdict. The pending command now lives on the provider child's own session instead of an adapter-wide map keyed by session, so it dies with the child and nothing has to release it. Claude's /compact is sent under a uuid the slot records, and only a root result naming that input (or naming none) ends it; its outcome is read with the ordinary result reading, so a stopped /compact is a cancellation. * fix(native-chat): a command's settle answers its message before ending its turn The two writes are not one batch. Writing the message's answer first means a crash between them leaves a running command turn, which the stale-turn sweep already settles, instead of an ended turn whose message reads as in flight forever. The settle now writes only while the command turn is still running. * fix(native-chat): "Worked for" counts from the handover, not the send A message held behind /compact, or behind a cold start, used to count the wait as the agent's work, although its row is drawn at the handover. Every handed-over submission's turn, the command's own included, now starts at the handover row's instant, falling back to the send time for a host that recorded none. * test(native-chat): give the failed-start and stale-turn waits a loaded runner's budget * test(native-chat): the interrupted create's own retry continues again The merge of main's lease-latch fix replaced that test's retry of the interrupted create, under its own operation id, with a fresh start whose result nothing read. That fresh start passes with the released-reservation continuation deleted, so the case the fix exists for went untested. The retry and its assertion are main's again. * docs(native-chat): three comments that still had views starting agents A start with nothing queued now comes from a command, goal change or rewind; an interrupted compaction left alone would refuse every send, so no agent would ever start to finish it; and a current host raises the unattached read refusal only once quit began, with the attach window belonging to an older host. * test(native-chat): pin the open's and the send's start and row counts, however the view binds Opening a fresh chat whose starts fail makes one start and one row, with two views bound before or after the create's child died; one send makes one more of each. * fix(native-chat): a second Stop on a command ends its child; one compaction verdict for every provider A Stop's note now names itself in its key, so a later Stop on a command still running reads, from the journal, that the provider was already asked and never answered, and stops the child instead of interrupting again. Nothing is held in memory for it. Adds the rule both translators will read a compaction's end by: only a compaction the provider reported is a success; none after Orca's interrupt is a cancellation; anything else is a failure. A real Claude capture, pinned as a fixture, is why: a stopped /compact ends in the same success result as a finished one. * test(native-chat): a reader's open settles the turn a failed exit settlement left running An exit whose settlement write failed leaves its turn running in the open journal. PR 1's open now settles it, and this pins the two reads that reach it here: a reader reopening a chat the idle sweep closed, and a read that opens the chat before the restart restore reaches it. * test(native-chat): the view-start test's starting window outlasts two subscriptions on a loaded runner A subscription reads the conversation before it returns, so under load the two views took longer than the create child's 300 ms start, which then exited before the test checked that it had not. The child now takes a second to fail. * fix(native-chat): settle a gone generation's turn at every open but an acquisition's The journal open skipped the settlement whenever the lease read reserved or live, to leave an acquisition's own open to the acquisition. But a lease a crashed process left in recovery also reads live, until the next acquire resolves it. A send that opened such a chat, from a phone or the CLI after a crash on a host that could not prove the old owner gone, skipped the settlement; when its start then failed, the dead turn stayed running for every reader. The acquisition now says it is the opener, and every other open settles, whatever the lease still claims. * test(native-chat): hold the create's start open until the views bind The "view binds while the create is still starting" case gave the create a 300 ms head start and asserted the views bound before it died. On a loaded runner the holds took longer, the create's exit landed first, and the case failed its own precondition. The create's initialize now waits on a gate the test releases once the views are bound. * refactor(native-chat): the provider's translator ends a command's turn; the loop holds no command state A conversation command is now a turn of the provider child's own journal pipeline. The adapter-wide tracker, its promise and the loop's settle step are gone. - Codex: the translator claims the provider turn that carries the command, scopes its rows to the command's turn, and writes the command's end in the same batch that settles that turn. Codex's own compaction marker is the success row. - Claude: the command's turn is the translator's open turn until the result that answers the /compact input ends it. The command's own frames, such as the continuation summary, its echo and "Compaction canceled.", draw nothing. - Both read the end with the one compaction rule: success needs the provider's report of the compaction; none after Orca's interrupt is a cancellation. - The message resolves at the provider's receipt, as any send does: the Codex ack, or the Claude slash-command waiter on its result. The host writes a command's end only when the provider never took it. - The delivery loop stops while a command's turn runs, and every journal commit re-wakes it through the session's serialize, so an end that lands while a step decides to stop is never lost. A child that ends first is settled with it. * test(native-chat): pin a command's end to real /compact frames and to each path it threads The captured /compact frames drive the Claude translator's command turn: a finished compaction ends as a success with only the separator drawn; a stopped one ends as a cancellation with no failure row, and the next send answers in its own turn; a result naming another input ends nothing. The command's end is checked at each point the ordinary result path threads through: the reopen latch after a failure, the settling of a child still working, the context facts the result reports, and the provider's own error row. On the host: a message held behind a command is handed over when the command ends just as the loop stops for it, a refused command settles as a failure and the loop moves on, and a Claude child that exits mid-command settles the command and hands what waited to a fresh child. * test(native-chat): tests merged from the base state which turn their rows belong to * refactor(native-chat): drop the child-end waiter nothing waits on A command no longer waits for its child here: its turn ends from the provider's frames or from that child's settlement, and the delivery loop is woken by the commit. The waiter and its test were left from the earlier shape. * fix(native-chat): a command holds the queue only while its child runs it The delivery loop stopped whenever the journal showed a command's turn running. When the command's child ended and its settlement could not be written, that turn stayed running with no child to end it, and the loop's gate kept it from ever starting the next child, which is what settles a gone generation's leftovers. Every later send was held for good, and Stop had no child to end. The gate now holds only while the conversation has a child: with none, the command belongs to a gone generation, and the loop's start settles it like any turn a dead child left running. * fix(native-chat): a Claude /compact succeeds only on its compaction boundary The command's evidence counted Claude's `compact_result: 'success'` status as the compaction done. That status comes before the boundary that replaces the history, so a Stop landing between the two read as a finished compaction even though no boundary was ever written. Only the boundary now counts, as the rule for both providers states; the capture's finished compaction carries one, so it still reads as a success. * fix(native-chat): a Claude child's exit says why the turn it ended stopped When a Claude child exited mid-/compact, the command showed "Worked for 0s" and no reason. The child's translator ends its open turn the moment the exit is reported, stamped with the exit's instant, so by the time the exit settlement ran nothing was running. The settlement recognises a turn the exit already ended by that same instant, but the Claude lifecycle event dropped it on the way to the host, which then used its own clock, matched nothing, and wrote no row. When the clocks did agree, the row was scoped to the running turn, of which there was none, so it landed outside the turn it explained. The exit's instant now reaches the host, and the exit row belongs to the turn the exit ended: still running, or ended by the translator at that instant. * fix(native-chat): a message waiting behind /compact draws below its live activity A message sent while /compact runs waits on the host until the command ends. Both clients moved it to the end of the transcript rows, but the running turn's live activity line ("Compacting the conversation") draws after every row, so the waiting message sat between the command and its own live status. A row that is queued, and not what the live turn is for, now draws after that live activity: on desktop outside the transcript window, below the activity line; on the phone in the list footer, below the live status. A message whose own start is pending still draws above the activity that start reports. * fix(native-chat): only a running command holds a message below its live activity A message is accepted, then handed over a moment later, and in between it reads as waiting. Every message waiting behind a live turn drew below that turn's activity line, so an ordinary message sent while the agent was working crossed below "Thinking" and jumped back up once it was handed over, on desktop and phone. Only a conversation command's turn holds the queue on the host. A message now waits below the live activity only while the running turn is one a command opened, read from the entry that opened it. The phone test also typechecks, which the mobile test ratchet requires. * test(codex): the claim test names its notification params as a record * test(native-chat): a read that reaches a crashed chat before the startup reconcile settles its turn On desktop the chat on screen at relaunch reads before startup reconciles the leases, while the dead process's lease still reads live. The open settles the turn it left running anyway, and the restore that follows finds it settled. * refactor(native-chat): drop the composer's second error formatter After the merge with main, every chat write in the composer path reports its failure as a typed outcome worded by the refusal-notice table, so the send's catch sees only a local throw. The {code, message} formatter this branch added for it has no payload left to format, and its claim to be the one way a chat words a failure is no longer true. The composer send is main's again. * test(native-chat): pin the reason on a message rejected while its chat was closed The reopen test checked only that the message reads as not sent; it now also checks the Retry row carries the host's reason. * docs(native-chat): drop the removed dispatch hold from six comments A worker's session no longer takes a dispatch hold, and no release clock rests a chat by visibility; the agent-launch comments, the abandon test, the teardown test and the refusal census still said so. * test(native-chat): rest the owner-status chat through the idle sweep, not a hold The activation-gate test from #22808 put its chat at rest by holding and releasing it, and passed the release-clock grace. This branch deleted both, so the case threw before it reached its assertions. It now moves the host's clock past the idle window and lets the sweep stop the agent and close the conversation, then asserts the same owner answer and activation gate. * fix(native-chat): show the structured pane's retrying line when a read fails The read transport always hands the pane the host's words, so the error state's "Orca keeps trying to load it" line, which showed only when there were none, was never seen: the pane showed the host's text twice, as its subtitle and on the status line under it. The structured pane now always says its read keeps retrying, and the host's text stays on the status line. The terminal-backed chat is unchanged. * fix(native-chat): a send the provider never received after a restart has no verdict Restart reconciliation rejects a crash-stranded send that is absent from a trustworthy provider history with reason 'not_delivered'. Nobody failed that send, but the verdict allowlist did not name it, so after a crash the chat read Failed, was listed, and could notify "failed". Give the reason a shared constant (persisted value unchanged), add it to the no-verdict set, and treat it as an internal marker so the Retry row no longer shows the raw string. * fix(native-chat): a failed Codex compaction's late completion writes no turn of its own Codex ends a failed turn with an error and then still completes it as failed. The error settled the compaction and released its claim on the provider turn, so the completion read that turn as an ordinary one and wrote a stray record. The claim now lasts until the completion, which adds nothing to a command the error already ended. * test(native-chat): the mid-command exit case resumes its next child as a real one does The case's fake started every child as a newly created thread with the same generation. The store refuses a created link once the conversation has a thread, so the next child's start failed and wrote its own error row, which landed before or after the case read the journal. The next child now resumes the thread under its own generation, and the case reads the journal once the waiting message is delivered, which also proves the loop moved on. * test(native-chat): wait for a send's background start before the refusal oracle removes its store An accepted send wakes the delivery loop, which starts the agent in the background. The oracle's teardown disposed the loop but did not wait for that start, so its lease write could create a temp file in the store directory while the directory was being removed, failing the test with ENOTEMPTY about one run in four. The teardown now drains tracked starts before it closes the journals. * fix(native-chat): a start a message waited on gets one failure row, the delivery loop's When a queued message's start failed, two writers could report it under the same row: the delivery loop, when the adapter settled the start without proving it, and the exit settlement, when the child's exit landed. The last one won, so the chat's row could name a different cause than the one the message was rejected with, or be written twice. The exit settlement now writes the start's row only when no message is queued and the loop has not already recorded that start. A start for a command, goal change or rewind, with nothing queued, still gets its row from the exit. * fix(native-chat): a /compact whose start failed says to run /compact again The failure-words context named only /clear as a command to retry, so a /compact whose agent failed to start read "Send your message to try again." on its row, its rejected message and the command reply. The context now carries any conversation command; the host derives it from the oldest message still waiting on the provider, which is the one a failed start fails first, and the /compact reply names it directly. * fix(native-chat): a Codex /compact ends only on its turn's completion, below Codex's own error row Since only turn/completed ends a Codex turn, Codex's turn-ending `error` is a row inside the still-open command turn, and the failed completion that follows it is the command's end: completed, outcome failure, at the completion's receipt time. The command's own "Compaction failed" row was written on that completion too, so a failed /compact read its reason twice. The command turn now notes when Codex's turn-ending error for the turn it carries was written as a row, and its end then adds no second row. A retried stream error ends nothing and is not counted. The flag that let the error end the command and kept the claim until the completion is gone with the error-driven end. A test replays the captured failed compaction from the real app-server through a claimed command turn. * test(native-chat): main's crash-turn test states its row's turn, and a dead /compact settles on its recorded exit Two tests the main merge brought together: - The crash-turn test from #23456 writes a turn record through the event sink without options; every row here states its turn scope, and a turn record's is the thread. - The /compact whose exit settlement could not be written no longer stays running until the next start: main now settles an open chat from the exit it recorded, so the command reads interrupted before the next message, which is then delivered. * test(native-chat): main's new journal tests state each row's turn The crash-turn, stale-turn and sink-queue tests main added wrote rows without a turn scope, which every item write now states. Rows written inside a running turn name that turn; the sink-queue batch and a send handed over with no live turn name the thread. * fix(native-chat): draw a queued turn's message after the earlier turn's rows A message sent while A runs is written to the journal when it is sent. When the provider queues it (Claude answers it after A), A's remaining rows - its last tool run and its answer - are written after that message, and the message's own turn opens only after them. Grouping put those rows in A's turn, but the transcript still drew them in journal order, below B's bubble and bar, where A's answer read as B's reply. This is the residual #23671 left open. A message that opened a turn now draws after the earlier turns' rows the journal wrote after it, just before its own turn's rows (nativeChatTurnDrawOrder, returned by nativeChatTurnMembership as drawOrder). Desktop and mobile both draw in that order. A steer, and a message that has opened no turn yet, stay where they were written. It applies on hosts that state turn scopes and, through journal order, on older ones. * test(native-chat): run #23026's Stop tests against #23059's command turns Two of #23026's tests call APIs #23059 changed, and failed after the merge: - codex-structured-conversation-stop: a compaction now goes through adapter.compact with the command run the host wrote (#23059), not a bare turn id, and answers with the provider's receipt. With the command claimed, a Stop that names no turn while the compaction's provider turn has not opened still interrupts nothing. - main-agent-working-agreement: a provider row states its turn scope (#23059's appendItem contract); the retry and subagent rows are conversation-scoped. * fix(native-chat): typecheck main's Stop and restore-grouping code against #23059 A Stop's compaction interrupt reads the narrowed requested turn, and the restore-grouping test states whether each row reports its turn's outcome. --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -76,8 +76,7 @@ export function MobileNativeChatOverlay({
|
||||
turnIndicator={controller.nativeChatTurnIndicator}
|
||||
workingStartedAt={controller.nativeChatWorkingStartedAt}
|
||||
settledTurns={controller.nativeChatSettledTurns}
|
||||
activeTurnOpenedBy={controller.nativeChatActiveTurnOpenedBy}
|
||||
turnKeysByItemId={controller.nativeChatTurnKeysByItemId}
|
||||
turnJournal={controller.nativeChatTurnJournal}
|
||||
streaming={streaming}
|
||||
onStop={controller.handleNativeChatStop}
|
||||
ask={controller.nativeChatAsk}
|
||||
|
||||
@@ -21,8 +21,10 @@ import type {
|
||||
NativeChatLiveTurnIndicator,
|
||||
NativeChatSettledTurns
|
||||
} from '../../../src/shared/native-chat-turn-status'
|
||||
import type { NativeChatTurnJournal } from '../../../src/shared/native-chat-turn-membership'
|
||||
import { colors } from '../theme/mobile-theme'
|
||||
import { styles } from './mobile-native-chat-view-styles'
|
||||
import { mobileNativeChatListFooter } from './mobile-native-chat-list-footer'
|
||||
import {
|
||||
buildMobileNativeChatTransientData,
|
||||
mobileNativeChatEmptyState,
|
||||
@@ -66,10 +68,8 @@ type Props = {
|
||||
/** Structured lane: host-recorded turn timing feeding the per-turn status rows. */
|
||||
workingStartedAt?: number | null
|
||||
settledTurns?: NativeChatSettledTurns | null
|
||||
/** Structured lane: the key the host says anchors the running turn's bar. */
|
||||
activeTurnOpenedBy?: string | null
|
||||
/** Structured lane: host-attributed turn ownership per journal item id. */
|
||||
turnKeysByItemId?: ReadonlyMap<string, string> | null
|
||||
/** Structured lane: the journal that places each row in its turn. */
|
||||
turnJournal?: NativeChatTurnJournal | null
|
||||
/** Interrupt the agent mid-turn (shown as a Stop button on the working bar). */
|
||||
/** Interrupt a provider turn. */
|
||||
onStop?: () => void
|
||||
@@ -155,8 +155,7 @@ export function MobileNativeChatView({
|
||||
turnIndicator = null,
|
||||
workingStartedAt,
|
||||
settledTurns,
|
||||
activeTurnOpenedBy = null,
|
||||
turnKeysByItemId = null,
|
||||
turnJournal = null,
|
||||
onStop,
|
||||
streaming,
|
||||
hasMore,
|
||||
@@ -276,8 +275,7 @@ export function MobileNativeChatView({
|
||||
isWorking: agentWorking === true,
|
||||
workingStartedAt,
|
||||
settledTurns,
|
||||
activeTurnOpenedBy,
|
||||
turnKeysByItemId,
|
||||
turnJournal,
|
||||
thinking: turnIndicator?.thinking === true,
|
||||
activityText: turnIndicator?.activityText ?? null,
|
||||
scopeKey: sendSurfaceId
|
||||
@@ -301,6 +299,14 @@ export function MobileNativeChatView({
|
||||
[toolsExpanded, fontScale, onOpenFile, structuredActivityUi, subagentLabels, turns]
|
||||
)
|
||||
|
||||
const liveStatus =
|
||||
structuredActivityUi && agentWorking && !hasPendingStructuredInteraction && turns.active ? (
|
||||
<MobileNativeChatTurnActivity
|
||||
thinking={turns.active.thinking}
|
||||
activityText={turns.activeActivityText}
|
||||
/>
|
||||
) : null
|
||||
|
||||
const emptyState = mobileNativeChatEmptyState(status, agent ?? null, error)
|
||||
const showLoading = status === 'loading' && messages.length === 0
|
||||
|
||||
@@ -317,7 +323,7 @@ export function MobileNativeChatView({
|
||||
<GestureDetector gesture={pinchGesture}>
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={data}
|
||||
data={turns.listMessages}
|
||||
keyExtractor={(item) => item.id}
|
||||
renderItem={renderItem}
|
||||
contentContainerStyle={styles.listContent}
|
||||
@@ -347,17 +353,11 @@ export function MobileNativeChatView({
|
||||
</Pressable>
|
||||
) : null
|
||||
}
|
||||
ListFooterComponent={
|
||||
structuredActivityUi &&
|
||||
agentWorking &&
|
||||
!hasPendingStructuredInteraction &&
|
||||
turns.active ? (
|
||||
<MobileNativeChatTurnActivity
|
||||
thinking={turns.active.thinking}
|
||||
activityText={turns.activeActivityText}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
ListFooterComponent={mobileNativeChatListFooter(
|
||||
liveStatus,
|
||||
turns.waitingRows,
|
||||
renderItem
|
||||
)}
|
||||
ListEmptyComponent={
|
||||
emptyState ? (
|
||||
<View style={styles.center}>
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import type { AgentJournalRenderItem } from '../../../src/shared/agent-session-journal-types'
|
||||
import type { NativeChatMessage } from '../../../src/shared/native-chat-types'
|
||||
import { MobileNativeChatView } from './MobileNativeChatView'
|
||||
|
||||
vi.mock('react-native', async () => {
|
||||
const React = await import('react')
|
||||
return {
|
||||
ActivityIndicator: 'ActivityIndicator',
|
||||
FlatList: React.forwardRef((props, ref) => {
|
||||
React.useImperativeHandle(ref, () => ({ scrollToEnd: vi.fn(), scrollToOffset: vi.fn() }), [])
|
||||
return React.createElement('FlatList', props)
|
||||
}),
|
||||
Pressable: 'Pressable',
|
||||
StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
|
||||
Text: 'Text',
|
||||
View: 'View'
|
||||
}
|
||||
})
|
||||
vi.mock('react-native-safe-area-context', () => ({
|
||||
useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
|
||||
}))
|
||||
vi.mock('react-native-gesture-handler', () => {
|
||||
const chain = { runOnJS: () => chain, onStart: () => chain, onUpdate: () => chain }
|
||||
return {
|
||||
Gesture: { Simultaneous: () => ({}), Native: () => ({}), Pinch: () => chain },
|
||||
GestureDetector: 'GestureDetector',
|
||||
GestureHandlerRootView: 'GestureHandlerRootView'
|
||||
}
|
||||
})
|
||||
vi.mock('lucide-react-native', () => ({
|
||||
ArrowDown: 'ArrowDown',
|
||||
ChevronsDownUp: 'ChevronsDownUp',
|
||||
ChevronsUpDown: 'ChevronsUpDown',
|
||||
Square: 'Square'
|
||||
}))
|
||||
vi.mock('./MobileNativeChatMessage', () => ({ MobileNativeChatMessage: 'ChatMessage' }))
|
||||
vi.mock('./MobileNativeChatTurnStatus', () => ({ MobileNativeChatTurnActivity: 'LiveStatus' }))
|
||||
vi.mock('./MobileNativeChatComposer', () => ({ MobileNativeChatComposer: 'Composer' }))
|
||||
vi.mock('./MobileNativeChatAsk', () => ({ MobileNativeChatAsk: 'ChatAsk' }))
|
||||
vi.mock('./MobileNativeChatPermission', () => ({ MobileNativeChatPermission: 'ChatPermission' }))
|
||||
vi.mock('./MobileNativeChatQuestion', () => ({ MobileNativeChatQuestion: 'ChatQuestion' }))
|
||||
vi.mock('./MobileAgentWorkingIndicator', () => ({
|
||||
MobileAgentWorkingIndicator: 'WorkingIndicator'
|
||||
}))
|
||||
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
afterEach(() => {
|
||||
act(() => renderer?.unmount())
|
||||
renderer = null
|
||||
})
|
||||
|
||||
function user(id: string, text: string, queued = false): NativeChatMessage {
|
||||
return {
|
||||
id,
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text }],
|
||||
timestamp: 1,
|
||||
source: 'hook',
|
||||
...(queued ? { queued: true as const } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function row(itemId: string, sequence: number, body: AgentJournalRenderItem['body']) {
|
||||
return {
|
||||
itemId,
|
||||
revision: 0,
|
||||
sequence,
|
||||
observedAt: sequence,
|
||||
turnScope: { kind: 'thread' as const },
|
||||
body
|
||||
}
|
||||
}
|
||||
|
||||
function renderView(
|
||||
folded: NativeChatMessage[],
|
||||
items: AgentJournalRenderItem[]
|
||||
): { listed: string[]; footer: string[] } {
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(MobileNativeChatView, {
|
||||
messages: [],
|
||||
folded,
|
||||
status: 'ready',
|
||||
streaming: null,
|
||||
onSend: vi.fn().mockResolvedValue(true),
|
||||
sendSurfaceId: 'tab-a',
|
||||
getSendCompletionGeneration: () => 0,
|
||||
getComposerEditGeneration: () => 0,
|
||||
pending: [],
|
||||
composerText: '',
|
||||
onComposerTextChange: vi.fn(),
|
||||
structuredActivityUi: true,
|
||||
agentWorking: true,
|
||||
turnJournal: { items, submissions: [] }
|
||||
})
|
||||
)
|
||||
})
|
||||
const list = renderer!.root.find((node) => String(node.type) === 'FlatList')
|
||||
let footer: ReactTestRenderer | null = null
|
||||
act(() => {
|
||||
footer = create(list.props.ListFooterComponent)
|
||||
})
|
||||
const drawn = footer!.root
|
||||
.findAll((node) => String(node.type) === 'LiveStatus' || String(node.type) === 'ChatMessage')
|
||||
.map((node) => (String(node.type) === 'LiveStatus' ? 'status' : node.props.message.id))
|
||||
act(() => footer!.unmount())
|
||||
return {
|
||||
listed: list.props.data.map((message: NativeChatMessage) => message.id),
|
||||
footer: drawn
|
||||
}
|
||||
}
|
||||
|
||||
it('draws a message waiting behind a running /compact after the live status, not in the list', () => {
|
||||
const drawn = renderView(
|
||||
[user('compact', '/compact'), user('held', 'Say DONE', true)],
|
||||
[
|
||||
row('compact', 1, {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: '/compact' }],
|
||||
command: { name: 'compact' }
|
||||
}),
|
||||
row('command-turn', 2, {
|
||||
kind: 'turn',
|
||||
turnId: 'compact:1',
|
||||
state: 'running',
|
||||
userItemId: 'compact',
|
||||
startedAt: 1
|
||||
}),
|
||||
row('held', 3, {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'Say DONE' }]
|
||||
})
|
||||
]
|
||||
)
|
||||
|
||||
expect(drawn).toEqual({ listed: ['compact'], footer: ['status', 'held'] })
|
||||
})
|
||||
|
||||
it('keeps a steer on its way into an ordinary running turn in the list, above the live status', () => {
|
||||
const drawn = renderView(
|
||||
[user('ask', 'List three fruits'), user('steer', 'Make it four', true)],
|
||||
[
|
||||
row('ask', 1, {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'List three fruits' }]
|
||||
}),
|
||||
row('turn', 2, {
|
||||
kind: 'turn',
|
||||
turnId: 'turn-1',
|
||||
state: 'running',
|
||||
userItemId: 'ask',
|
||||
startedAt: 1
|
||||
}),
|
||||
row('steer', 3, {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'Make it four' }]
|
||||
})
|
||||
]
|
||||
)
|
||||
|
||||
expect(drawn).toEqual({ listed: ['ask', 'steer'], footer: ['status'] })
|
||||
})
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
NativeChatLiveTurnIndicator,
|
||||
NativeChatSettledTurns
|
||||
} from '../../../src/shared/native-chat-turn-status'
|
||||
import type { NativeChatTurnJournal } from '../../../src/shared/native-chat-turn-membership'
|
||||
import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send'
|
||||
import type { MobileNativeChatPendingMessage } from './use-mobile-native-chat-drafts'
|
||||
import type { useMobileNativeChatSession } from './use-mobile-native-chat-session'
|
||||
@@ -37,10 +38,8 @@ export type MobileNativeChatController = {
|
||||
/** Structured lane: host-recorded turn timing for the per-turn status rows. */
|
||||
nativeChatWorkingStartedAt: number | null
|
||||
nativeChatSettledTurns: NativeChatSettledTurns | null
|
||||
/** Structured lane: the user message the host says opened the running turn. */
|
||||
nativeChatActiveTurnOpenedBy: string | null
|
||||
/** Structured lane: the turn that owns each journal item's row. */
|
||||
nativeChatTurnKeysByItemId: ReadonlyMap<string, string> | null
|
||||
/** Structured lane: the journal that places each transcript row in its turn. */
|
||||
nativeChatTurnJournal: NativeChatTurnJournal | null
|
||||
nativeChatCanStop: boolean
|
||||
nativeChatStreamingText?: string
|
||||
/** Agent mid-turn, regardless of whether chat is the visible view. */
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Fragment, type ReactElement } from 'react'
|
||||
import type { NativeChatMessage } from '../../../src/shared/native-chat-types'
|
||||
|
||||
type MobileNativeChatListRow = { item: NativeChatMessage; index: number }
|
||||
|
||||
/** The live turn's status, then the messages waiting behind that turn, drawn below it. */
|
||||
export function mobileNativeChatListFooter(
|
||||
liveStatus: ReactElement | null,
|
||||
waitingRows: readonly MobileNativeChatListRow[],
|
||||
renderRow: (row: MobileNativeChatListRow) => ReactElement
|
||||
): ReactElement | null {
|
||||
if (waitingRows.length === 0) {
|
||||
return liveStatus
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{liveStatus}
|
||||
{waitingRows.map((row) => (
|
||||
<Fragment key={row.item.id}>{renderRow(row)}</Fragment>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -288,10 +288,7 @@ export function useMobileNativeChatController(args: {
|
||||
nativeChatTurnIndicator: activeChatStructured ? structuredNativeChat.turnIndicator : null,
|
||||
nativeChatWorkingStartedAt: activeChatStructured ? structuredNativeChat.workingStartedAt : null,
|
||||
nativeChatSettledTurns: activeChatStructured ? structuredNativeChat.settledTurns : null,
|
||||
nativeChatActiveTurnOpenedBy: activeChatStructured
|
||||
? structuredNativeChat.activeTurnOpenedBy
|
||||
: null,
|
||||
nativeChatTurnKeysByItemId: activeChatStructured ? structuredNativeChat.turnKeysByItemId : null,
|
||||
nativeChatTurnJournal: activeChatStructured ? structuredNativeChat.turnJournal : null,
|
||||
nativeChatCanStop: activeChatStructured
|
||||
? structuredNativeChat.turnId !== null
|
||||
: nativeChatAgentWorking,
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalRenderItem,
|
||||
AgentJournalTurnScope
|
||||
} from '../../../src/shared/agent-session-journal-types'
|
||||
import type { NativeChatMessage } from '../../../src/shared/native-chat-types'
|
||||
import type { NativeChatTurnJournal } from '../../../src/shared/native-chat-turn-membership'
|
||||
import type { NativeChatSettledTurns } from '../../../src/shared/native-chat-turn-status'
|
||||
import { useMobileNativeChatTurnDisclosure } from './use-mobile-native-chat-turn-disclosure'
|
||||
|
||||
@@ -20,18 +26,16 @@ function Harness({
|
||||
enabled,
|
||||
isWorking = true,
|
||||
settledTurns,
|
||||
turnJournal,
|
||||
workingStartedAt,
|
||||
activeTurnOpenedBy,
|
||||
turnKeysByItemId,
|
||||
scopeKey = 'host\0worktree\0tab-a'
|
||||
}: {
|
||||
messages: readonly NativeChatMessage[]
|
||||
enabled: boolean
|
||||
isWorking?: boolean
|
||||
settledTurns?: NativeChatSettledTurns
|
||||
turnJournal?: NativeChatTurnJournal
|
||||
workingStartedAt?: number | null
|
||||
activeTurnOpenedBy?: string | null
|
||||
turnKeysByItemId?: ReadonlyMap<string, string> | null
|
||||
scopeKey?: string
|
||||
}): React.JSX.Element {
|
||||
const disclosure = useMobileNativeChatTurnDisclosure({
|
||||
@@ -39,9 +43,8 @@ function Harness({
|
||||
enabled,
|
||||
isWorking,
|
||||
settledTurns,
|
||||
turnJournal,
|
||||
workingStartedAt,
|
||||
activeTurnOpenedBy,
|
||||
turnKeysByItemId,
|
||||
scopeKey
|
||||
})
|
||||
return createElement('result', { disclosure })
|
||||
@@ -211,199 +214,432 @@ describe('useMobileNativeChatTurnDisclosure', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the live bar under the prompt that opened the running turn, not a mid-turn send', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const tool: NativeChatMessage = {
|
||||
id: 'tool-a',
|
||||
role: 'assistant',
|
||||
blocks: [
|
||||
{ type: 'tool-call', name: 'Bash', input: { command: 'sleep 15' }, state: 'running' }
|
||||
],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
describe('keeps the live bar under the prompt that opened the running turn, not a mid-turn send', () => {
|
||||
const tool: NativeChatMessage = {
|
||||
id: 'tool-a',
|
||||
role: 'assistant',
|
||||
blocks: [
|
||||
{ type: 'tool-call', name: 'Bash', input: { command: 'sleep 15' }, state: 'running' }
|
||||
],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
}
|
||||
const messages = [userMessage('A'), tool, userMessage('B')]
|
||||
const user = (
|
||||
id: string,
|
||||
sequence: number,
|
||||
turnScope?: AgentJournalTurnScope
|
||||
): AgentJournalRenderItem => ({
|
||||
itemId: id,
|
||||
revision: 0,
|
||||
sequence,
|
||||
observedAt: sequence,
|
||||
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: id }] },
|
||||
...(turnScope ? { turnScope } : {})
|
||||
})
|
||||
const turn = (
|
||||
turnId: string,
|
||||
sequence: number,
|
||||
state: 'running' | 'interrupted',
|
||||
userItemId: string,
|
||||
turnScope?: AgentJournalTurnScope
|
||||
): AgentJournalRenderItem => ({
|
||||
itemId: turnId,
|
||||
revision: 0,
|
||||
sequence,
|
||||
observedAt: sequence,
|
||||
body: { kind: 'turn', turnId, state, userItemId },
|
||||
...(turnScope ? { turnScope } : {})
|
||||
})
|
||||
const toolItem = (
|
||||
sequence: number,
|
||||
turnScope?: AgentJournalTurnScope
|
||||
): AgentJournalRenderItem => ({
|
||||
itemId: 'tool-a',
|
||||
revision: 0,
|
||||
sequence,
|
||||
observedAt: sequence,
|
||||
body: {
|
||||
kind: 'tool-call',
|
||||
name: 'Bash',
|
||||
input: { command: 'sleep 15' },
|
||||
state: 'running'
|
||||
},
|
||||
...(turnScope ? { turnScope } : {})
|
||||
})
|
||||
const rows = () => {
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
return messages.map((message, index) => disclosure.resolveRow(index, message))
|
||||
}
|
||||
const render = (props: Parameters<typeof Harness>[0]) =>
|
||||
act(() => {
|
||||
if (renderer) {
|
||||
renderer.update(createElement(Harness, props))
|
||||
} else {
|
||||
renderer = create(createElement(Harness, props))
|
||||
}
|
||||
})
|
||||
|
||||
it("on a host that states each row's turn, the steered message and the work are one live turn", () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const t1 = { kind: 'turn', turnItemId: 't1' } as const
|
||||
const thread = { kind: 'thread' } as const
|
||||
// B was handed over while A's turn runs, so the host scopes it to that turn.
|
||||
const whileA = [
|
||||
user('A', 1, thread),
|
||||
turn('t1', 2, 'running', 'A', thread),
|
||||
toolItem(3, t1),
|
||||
user('B', 4, t1)
|
||||
]
|
||||
render({
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 5_000,
|
||||
turnJournal: { items: whileA, submissions: [] }
|
||||
})
|
||||
let [rowA, rowTool, rowB] = rows()
|
||||
expect(rowA.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: null })
|
||||
expect(rowB.turnStatus).toBeNull()
|
||||
expect([rowA, rowTool, rowB].map((row) => row.activeTurnIsWorking)).toEqual([
|
||||
true,
|
||||
true,
|
||||
true
|
||||
])
|
||||
|
||||
// B's own turn opens: A takes the host's settled duration, B counts from A's end.
|
||||
const whileB = [
|
||||
user('A', 1, thread),
|
||||
turn('t1', 2, 'interrupted', 'A', thread),
|
||||
toolItem(3, t1),
|
||||
user('B', 4, t1),
|
||||
turn('t2', 5, 'running', 'B', thread)
|
||||
]
|
||||
render({
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 22_000,
|
||||
settledTurns: new Map([['A', { startedAt: 5_000, workedSeconds: 17 }]]),
|
||||
turnJournal: { items: whileB, submissions: [] }
|
||||
})
|
||||
;[rowA, rowTool, rowB] = rows()
|
||||
expect(rowA.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: 17 })
|
||||
expect(rowB.turnStatus).toEqual({ startedAt: 22_000, thinking: false, workedSeconds: null })
|
||||
expect(rowB.activeTurnIsWorking).toBe(true)
|
||||
expect(rowTool.activeTurnIsWorking).toBe(false)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
const messages = [userMessage('A'), tool, userMessage('B')]
|
||||
const rows = () => {
|
||||
})
|
||||
|
||||
it('on a host that states no turn, the bar and liveness follow the running record by journal order', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const whileA = [user('A', 1), turn('t1', 2, 'running', 'A'), toolItem(3), user('B', 4)]
|
||||
render({
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 5_000,
|
||||
turnJournal: { items: whileA, submissions: [] }
|
||||
})
|
||||
let [rowA, rowTool, rowB] = rows()
|
||||
expect(rowA.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: null })
|
||||
expect(rowB.turnStatus).toBeNull()
|
||||
// Liveness follows the owning turn: A's tool row stays live while B waits.
|
||||
expect(rowTool.activeTurnIsWorking).toBe(true)
|
||||
expect(rowB.activeTurnIsWorking).toBe(false)
|
||||
|
||||
const whileB = [
|
||||
user('A', 1),
|
||||
turn('t1', 2, 'interrupted', 'A'),
|
||||
toolItem(3),
|
||||
user('B', 4),
|
||||
turn('t2', 5, 'running', 'B')
|
||||
]
|
||||
render({
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 22_000,
|
||||
settledTurns: new Map([['A', { startedAt: 5_000, workedSeconds: 17 }]]),
|
||||
turnJournal: { items: whileB, submissions: [] }
|
||||
})
|
||||
;[rowA, , rowB] = rows()
|
||||
expect(rowA.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: 17 })
|
||||
expect(rowB.turnStatus).toEqual({ startedAt: 22_000, thinking: false, workedSeconds: null })
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
/** A journal of `entries` in order, each naming the turn it belongs to (null for none). With
|
||||
* `statesScope` false the rows carry no scope, as an older host writes them. */
|
||||
function journalOf(
|
||||
entries: readonly [itemId: string, body: AgentJournalItemBody, turnItemId: string | null][],
|
||||
statesScope: boolean
|
||||
): NativeChatTurnJournal {
|
||||
return {
|
||||
items: entries.map(([itemId, body, turnItemId], index) => ({
|
||||
itemId,
|
||||
revision: 0,
|
||||
sequence: index + 1,
|
||||
observedAt: index + 1,
|
||||
body,
|
||||
...(statesScope
|
||||
? {
|
||||
turnScope: turnItemId
|
||||
? { kind: 'turn' as const, turnItemId }
|
||||
: { kind: 'thread' as const }
|
||||
}
|
||||
: {})
|
||||
})),
|
||||
submissions: []
|
||||
}
|
||||
}
|
||||
const said = (role: 'user' | 'assistant'): AgentJournalItemBody => ({
|
||||
kind: 'message',
|
||||
role,
|
||||
blocks: []
|
||||
})
|
||||
const record = (
|
||||
turnId: string,
|
||||
state: 'running' | 'completed',
|
||||
userItemId: string
|
||||
): AgentJournalItemBody => ({ kind: 'turn', turnId, state, userItemId })
|
||||
const hosts = [
|
||||
['states each row’s turn', true],
|
||||
['states no scope', false]
|
||||
] as const
|
||||
|
||||
it.each(hosts)(
|
||||
"keeps a running turn's rows live across a mid-turn send the host folded in, on a host that %s",
|
||||
(_host, statesScope) => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const tool = (id: string): NativeChatMessage => ({
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [
|
||||
{ type: 'tool-call', name: 'Bash', input: { command: 'sleep 15' }, state: 'running' }
|
||||
],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
})
|
||||
// The #23621 shape: B lands mid-turn and the tool rows after it are still A's.
|
||||
const messages = [userMessage('A'), tool('t1'), userMessage('B'), tool('t2')]
|
||||
const turnJournal = journalOf(
|
||||
[
|
||||
['A', said('user'), null],
|
||||
['tA', record('tA', 'running', 'A'), null],
|
||||
['t1', said('assistant'), 'tA'],
|
||||
['B', said('user'), 'tA'],
|
||||
['t2', said('assistant'), 'tA']
|
||||
],
|
||||
statesScope
|
||||
)
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 5_000,
|
||||
turnJournal
|
||||
})
|
||||
)
|
||||
})
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
return messages.map((message, index) => disclosure.resolveRow(index, message))
|
||||
const [rowA, rowT1, rowB, rowT2] = messages.map((message, index) =>
|
||||
disclosure.resolveRow(index, message)
|
||||
)
|
||||
expect(rowA.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: null })
|
||||
// The steered bubble shares A's turn but never carries a bar of its own.
|
||||
expect(rowB.turnStatus).toBeNull()
|
||||
expect(rowT1.activeTurnIsWorking).toBe(true)
|
||||
expect(rowT2.activeTurnIsWorking).toBe(true)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
// B was sent while A's turn runs; the host still names A as the running turn's opener.
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 5_000,
|
||||
activeTurnOpenedBy: 'A'
|
||||
})
|
||||
)
|
||||
})
|
||||
let [rowA, rowTool, rowB] = rows()
|
||||
expect(rowA.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: null })
|
||||
expect(rowB.turnStatus).toBeNull()
|
||||
// Liveness follows the owning turn: A's tool row stays live while B waits.
|
||||
expect(rowTool.activeTurnIsWorking).toBe(true)
|
||||
expect(rowB.activeTurnIsWorking).toBe(false)
|
||||
|
||||
// B's own turn opens: A takes the host's settled duration, B counts from A's end.
|
||||
act(() => {
|
||||
renderer?.update(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 22_000,
|
||||
settledTurns: new Map([['A', { startedAt: 5_000, workedSeconds: 17 }]]),
|
||||
activeTurnOpenedBy: 'B'
|
||||
})
|
||||
)
|
||||
})
|
||||
;[rowA, , rowB] = rows()
|
||||
expect(rowA.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: 17 })
|
||||
expect(rowB.turnStatus).toEqual({ startedAt: 22_000, thinking: false, workedSeconds: null })
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
it("keeps a running turn's rows live across a mid-turn send the host folded in", () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const tool = (id: string): NativeChatMessage => ({
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [
|
||||
{ type: 'tool-call', name: 'Bash', input: { command: 'sleep 15' }, state: 'running' }
|
||||
],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
})
|
||||
// The #23621 shape: B lands mid-turn and the tool rows after it are still A's.
|
||||
const messages = [userMessage('A'), tool('t1'), userMessage('B'), tool('t2')]
|
||||
const owned = new Map([
|
||||
['A', 'A'],
|
||||
['t1', 'A'],
|
||||
['B', 'A'],
|
||||
['t2', 'A']
|
||||
])
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 5_000,
|
||||
activeTurnOpenedBy: 'A',
|
||||
turnKeysByItemId: owned
|
||||
})
|
||||
it.each(hosts)(
|
||||
"anchors a provider-opened turn's bar above its first row, on a host that %s",
|
||||
(_host, statesScope) => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const woke: NativeChatMessage = {
|
||||
id: 'woke',
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text: 'Woke up.' }],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
}
|
||||
const messages = [userMessage('u1'), woke]
|
||||
const turnJournal = journalOf(
|
||||
[
|
||||
['u1', said('user'), null],
|
||||
['wake', record('wake', 'completed', 'claude:wake'), null],
|
||||
['woke', said('assistant'), 'wake']
|
||||
],
|
||||
statesScope
|
||||
)
|
||||
})
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
const [rowA, rowT1, rowB, rowT2] = messages.map((message, index) =>
|
||||
disclosure.resolveRow(index, message)
|
||||
)
|
||||
expect(rowA.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: null })
|
||||
// The steered bubble shares A's turn but never carries a bar of its own.
|
||||
expect(rowB.turnStatus).toBeNull()
|
||||
expect(rowT1.activeTurnIsWorking).toBe(true)
|
||||
expect(rowT2.activeTurnIsWorking).toBe(true)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it("anchors a provider-opened turn's bar above its first row", () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const woke: NativeChatMessage = {
|
||||
id: 'woke',
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text: 'Woke up.' }],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
isWorking: false,
|
||||
settledTurns: new Map([['wake', { startedAt: 5_000, workedSeconds: 9 }]]),
|
||||
turnJournal
|
||||
})
|
||||
)
|
||||
})
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
const [rowU1, rowWoke] = messages.map((message, index) =>
|
||||
disclosure.resolveRow(index, message)
|
||||
)
|
||||
expect(rowU1.turnStatus).toBeNull()
|
||||
expect(rowWoke.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: 9 })
|
||||
expect(rowWoke.turnStatusAbove).toBe(true)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
const messages = [userMessage('u1'), woke]
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
isWorking: false,
|
||||
settledTurns: new Map([['wake', { startedAt: 5_000, workedSeconds: 9 }]]),
|
||||
turnKeysByItemId: new Map([
|
||||
['u1', 'u1'],
|
||||
['woke', 'wake']
|
||||
])
|
||||
})
|
||||
)
|
||||
})
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
const [rowU1, rowWoke] = messages.map((message, index) =>
|
||||
disclosure.resolveRow(index, message)
|
||||
)
|
||||
expect(rowU1.turnStatus).toBeNull()
|
||||
expect(rowWoke.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: 9 })
|
||||
expect(rowWoke.turnStatusAbove).toBe(true)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
it("never hands a provider-opened turn's clock to a message sent during it", () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const row = (id: string): NativeChatMessage => ({
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text: id }],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
})
|
||||
// A wake turn runs; B is sent during it and folded in, so B opened nothing.
|
||||
const messages = [row('w1'), userMessage('B'), row('w2')]
|
||||
const owned = new Map([
|
||||
['w1', 'wake'],
|
||||
['B', 'wake'],
|
||||
['w2', 'wake']
|
||||
])
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 5_000,
|
||||
activeTurnOpenedBy: 'wake',
|
||||
turnKeysByItemId: owned,
|
||||
settledTurns: new Map([['wake', null]])
|
||||
})
|
||||
it.each(hosts)(
|
||||
"never hands a provider-opened turn's clock to a message sent during it, on a host that %s",
|
||||
(_host, statesScope) => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(10_000)
|
||||
const row = (id: string): NativeChatMessage => ({
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text: id }],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
})
|
||||
// A wake turn runs; B is sent during it and folded in, so B opened nothing.
|
||||
const messages = [row('w1'), userMessage('B'), row('w2')]
|
||||
const journal = (state: 'running' | 'completed') =>
|
||||
journalOf(
|
||||
[
|
||||
['wake', record('wake', state, 'claude:wake'), null],
|
||||
['w1', said('assistant'), 'wake'],
|
||||
['B', said('user'), 'wake'],
|
||||
['w2', said('assistant'), 'wake']
|
||||
],
|
||||
statesScope
|
||||
)
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 5_000,
|
||||
turnJournal: journal('running'),
|
||||
settledTurns: new Map([['wake', null]])
|
||||
})
|
||||
)
|
||||
})
|
||||
// The wake turn settles: the host no longer names a running turn.
|
||||
vi.setSystemTime(20_000)
|
||||
act(() => {
|
||||
renderer!.update(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
isWorking: false,
|
||||
workingStartedAt: null,
|
||||
turnJournal: journal('completed'),
|
||||
settledTurns: new Map([['wake', { startedAt: 5_000, workedSeconds: 15 }]])
|
||||
})
|
||||
)
|
||||
})
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
const [rowW1, rowB] = messages.map((message, index) =>
|
||||
disclosure.resolveRow(index, message)
|
||||
)
|
||||
})
|
||||
// The wake turn settles: the host no longer names a running turn.
|
||||
vi.setSystemTime(20_000)
|
||||
act(() => {
|
||||
renderer!.update(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
isWorking: false,
|
||||
workingStartedAt: null,
|
||||
activeTurnOpenedBy: null,
|
||||
turnKeysByItemId: owned,
|
||||
settledTurns: new Map([['wake', { startedAt: 5_000, workedSeconds: 15 }]])
|
||||
})
|
||||
)
|
||||
})
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
const [rowW1, rowB] = messages.map((message, index) => disclosure.resolveRow(index, message))
|
||||
expect(rowW1.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: 15 })
|
||||
expect(rowB.turnStatus).toBeNull()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
expect(rowW1.turnStatus).toEqual({ startedAt: 5_000, thinking: false, workedSeconds: 15 })
|
||||
expect(rowB.turnStatus).toBeNull()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
// Claude runs A; B is sent mid-turn and Claude answers it after A. The journal writes B when it
|
||||
// is sent, so A's remaining tool run and its answer follow B there, and B's turn opens after them.
|
||||
it.each(hosts)(
|
||||
"draws A's remaining rows under A's bar, then B's bubble and turn, on a host that %s",
|
||||
(_host, statesScope) => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(30_000)
|
||||
const message = (id: string, role: 'user' | 'assistant'): NativeChatMessage => ({
|
||||
id,
|
||||
role,
|
||||
blocks: [{ type: 'text', text: id }],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
})
|
||||
const messages = [
|
||||
message('A', 'user'),
|
||||
message('a-tool-1', 'assistant'),
|
||||
message('B', 'user'),
|
||||
message('a-tool-2', 'assistant'),
|
||||
message('FIRST DONE', 'assistant'),
|
||||
message('b-answer', 'assistant')
|
||||
]
|
||||
const turnJournal = journalOf(
|
||||
[
|
||||
['A', said('user'), null],
|
||||
['tA', record('tA', 'completed', 'A'), null],
|
||||
['a-tool-1', said('assistant'), 'tA'],
|
||||
// Handed over while A runs, so the host scopes it to A's turn until its own opens.
|
||||
['B', said('user'), 'tA'],
|
||||
['a-tool-2', said('assistant'), 'tA'],
|
||||
['FIRST DONE', said('assistant'), 'tA'],
|
||||
['tB', record('tB', 'running', 'B'), null],
|
||||
['b-answer', said('assistant'), 'tB']
|
||||
],
|
||||
statesScope
|
||||
)
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
workingStartedAt: 29_000,
|
||||
settledTurns: new Map([['A', { startedAt: 5_000, workedSeconds: 17 }]]),
|
||||
turnJournal
|
||||
})
|
||||
)
|
||||
})
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
const list: NativeChatMessage[] = disclosure.listMessages
|
||||
const drawn = list.map((entry, index) => {
|
||||
const row = disclosure.resolveRow(index, entry)
|
||||
return [entry.id, row.turnStatus?.workedSeconds, row.activeTurnIsWorking]
|
||||
})
|
||||
expect(drawn).toEqual([
|
||||
['A', 17, false],
|
||||
['a-tool-1', undefined, false],
|
||||
['a-tool-2', undefined, false],
|
||||
['FIRST DONE', undefined, false],
|
||||
['B', null, true],
|
||||
['b-answer', undefined, true]
|
||||
])
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps at most the latest 128 turns expanded', () => {
|
||||
vi.useFakeTimers()
|
||||
@@ -439,4 +675,47 @@ describe('useMobileNativeChatTurnDisclosure', () => {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a turn the provider opened live while it runs, and the turn before it settled', () => {
|
||||
let sequence = 0
|
||||
const entry = (
|
||||
itemId: string,
|
||||
body: AgentJournalItemBody,
|
||||
turnScope: AgentJournalTurnScope = { kind: 'thread' }
|
||||
): AgentJournalRenderItem => {
|
||||
sequence += 1
|
||||
return { itemId, revision: 0, sequence, observedAt: sequence, body, turnScope }
|
||||
}
|
||||
const said = (itemId: string, turnItemId: string) =>
|
||||
entry(
|
||||
itemId,
|
||||
{ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: itemId }] },
|
||||
{ kind: 'turn', turnItemId }
|
||||
)
|
||||
const items = [
|
||||
entry('u1', { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'go' }] }),
|
||||
entry('t1', { kind: 'turn', turnId: 't1', state: 'completed', userItemId: 'u1' }),
|
||||
said('a1', 't1'),
|
||||
entry('wake', { kind: 'turn', turnId: 'wake', state: 'running', userItemId: 'claude:wake' }),
|
||||
said('wake-note', 'wake')
|
||||
]
|
||||
const messages: NativeChatMessage[] = ['u1', 'a1', 'wake-note'].map((id, index) => ({
|
||||
...userMessage(id),
|
||||
role: index === 0 ? 'user' : 'assistant'
|
||||
}))
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(Harness, {
|
||||
messages,
|
||||
enabled: true,
|
||||
settledTurns: new Map([['u1', { startedAt: 500, workedSeconds: 4 }]]),
|
||||
turnJournal: { items, submissions: [] }
|
||||
})
|
||||
)
|
||||
})
|
||||
const disclosure = renderer!.root.findByType('result').props.disclosure
|
||||
const rows = messages.map((message, index) => disclosure.resolveRow(index, message))
|
||||
expect(rows.map((row) => row.activeTurnIsWorking)).toEqual([false, false, true])
|
||||
expect(rows[0].turnStatus?.workedSeconds).toBe(4)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import type { NativeChatMessage } from '../../../src/shared/native-chat-types'
|
||||
import { NATIVE_CHAT_UNANCHORED_TURN_KEY } from '../../../src/shared/native-chat-turn-status'
|
||||
import type { NativeChatSettledTurns } from '../../../src/shared/native-chat-turn-status'
|
||||
import {
|
||||
nativeChatRowTurnKeys,
|
||||
nativeChatSelfAnchoredTurnRows
|
||||
nativeChatMessagesWaitingBehindLiveTurn,
|
||||
nativeChatTurnMembership,
|
||||
type NativeChatTurnJournal
|
||||
} from '../../../src/shared/native-chat-turn-membership'
|
||||
import {
|
||||
nativeChatRowsInDrawOrder,
|
||||
nativeChatTurnBarRows
|
||||
} from '../../../src/shared/native-chat-turn-grouping'
|
||||
import {
|
||||
useMobileNativeChatTurnStatus,
|
||||
@@ -12,8 +16,7 @@ import {
|
||||
} from './use-mobile-native-chat-turn-status'
|
||||
|
||||
const EMPTY_TURN_IDS: ReadonlySet<string> = new Set()
|
||||
const EMPTY_TURN_KEYS: readonly undefined[] = []
|
||||
const EMPTY_TURN_ANCHORS: ReadonlyMap<string, number> = new Map()
|
||||
const NO_TURN_KEYS: readonly undefined[] = []
|
||||
const MAX_EXPANDED_TURNS = 128
|
||||
|
||||
export type MobileNativeChatTurnRow = {
|
||||
@@ -35,8 +38,7 @@ export function useMobileNativeChatTurnDisclosure({
|
||||
isWorking,
|
||||
workingStartedAt,
|
||||
settledTurns,
|
||||
activeTurnOpenedBy = null,
|
||||
turnKeysByItemId = null,
|
||||
turnJournal = null,
|
||||
thinking = false,
|
||||
activityText = null,
|
||||
scopeKey
|
||||
@@ -47,11 +49,8 @@ export function useMobileNativeChatTurnDisclosure({
|
||||
workingStartedAt?: number | null
|
||||
/** Host-recorded durations; they outrank whatever this client observed. */
|
||||
settledTurns?: NativeChatSettledTurns | null
|
||||
/** The key the host says anchors the running turn's bar; absent, the latest user message. */
|
||||
activeTurnOpenedBy?: string | null
|
||||
/** Host-attributed turn ownership per journal item id; unnamed rows keep
|
||||
* positional preceding-user grouping. */
|
||||
turnKeysByItemId?: ReadonlyMap<string, string> | null
|
||||
/** The journal that places each row in its turn; absent groups rows by position. */
|
||||
turnJournal?: NativeChatTurnJournal | null
|
||||
/** Whether the turn is reasoning right now, derived from its journal content. */
|
||||
thinking?: boolean
|
||||
/** What the provider says the live turn is doing; outranks the other labels. */
|
||||
@@ -64,15 +63,43 @@ export function useMobileNativeChatTurnDisclosure({
|
||||
activeActivityText: string | null
|
||||
onToggleTurn: (turnKey: string) => void
|
||||
resolveRow: (index: number, message: NativeChatMessage) => MobileNativeChatTurnRow
|
||||
/** The list's rows, in the order they draw, less those waiting behind the live turn. */
|
||||
listMessages: readonly NativeChatMessage[]
|
||||
/** Rows waiting behind the live turn, drawn after its live status. */
|
||||
waitingRows: readonly { item: NativeChatMessage; index: number }[]
|
||||
} {
|
||||
// Resolve each row's turn, which turn is live, and the order the rows draw in, once: from the
|
||||
// turn record when the host states scopes, else by journal order.
|
||||
const { rows, turnKeys, liveTurnKey } = useMemo(() => {
|
||||
if (!enabled) {
|
||||
return { rows: messages, turnKeys: NO_TURN_KEYS, liveTurnKey: undefined }
|
||||
}
|
||||
const membership = nativeChatTurnMembership(messages, turnJournal)
|
||||
return {
|
||||
rows: nativeChatRowsInDrawOrder(messages, membership.drawOrder),
|
||||
turnKeys: nativeChatRowsInDrawOrder(membership.turnKeys, membership.drawOrder),
|
||||
liveTurnKey: membership.liveTurnKey
|
||||
}
|
||||
}, [enabled, messages, turnJournal])
|
||||
// A message waiting behind the live turn draws after that turn's live status, not in the list.
|
||||
const waiting = useMemo(() => {
|
||||
const ids = enabled ? nativeChatMessagesWaitingBehindLiveTurn(rows, turnJournal?.items) : null
|
||||
if (!ids?.size) {
|
||||
return { listMessages: rows, waitingRows: [], indexById: null }
|
||||
}
|
||||
return {
|
||||
listMessages: rows.filter((message) => !ids.has(message.id)),
|
||||
waitingRows: rows.flatMap((item, index) => (ids.has(item.id) ? [{ item, index }] : [])),
|
||||
indexById: new Map(rows.map((message, index) => [message.id, index]))
|
||||
}
|
||||
}, [enabled, rows, turnJournal])
|
||||
const turnStatuses = useMobileNativeChatTurnStatus({
|
||||
messages,
|
||||
turnKeys,
|
||||
liveTurnKey,
|
||||
enabled,
|
||||
isWorking,
|
||||
workingStartedAt,
|
||||
settledTurns,
|
||||
activeTurnOpenedBy,
|
||||
turnKeysByItemId,
|
||||
thinking,
|
||||
scopeKey
|
||||
})
|
||||
@@ -100,59 +127,43 @@ export function useMobileNativeChatTurnDisclosure({
|
||||
},
|
||||
[scopeKey]
|
||||
)
|
||||
// Resolve each row's owning turn once — a findLast per row is quadratic on a
|
||||
// long transcript.
|
||||
const turnKeys = useMemo(
|
||||
() => (enabled ? nativeChatRowTurnKeys(messages, turnKeysByItemId) : EMPTY_TURN_KEYS),
|
||||
[enabled, messages, turnKeysByItemId]
|
||||
)
|
||||
// A turn with no user bubble (provider-opened) anchors its bar at its first row.
|
||||
const selfAnchors = useMemo(
|
||||
() => (enabled ? nativeChatSelfAnchoredTurnRows(messages, turnKeys) : EMPTY_TURN_ANCHORS),
|
||||
[enabled, messages, turnKeys]
|
||||
)
|
||||
const bars = useMemo(() => nativeChatTurnBarRows(rows, turnKeys), [rows, turnKeys])
|
||||
|
||||
const { active, activeTurnKey, completedByTurn } = turnStatuses
|
||||
const activeActivityText = enabled && isWorking ? (activityText ?? null) : null
|
||||
const resolveRow = useCallback(
|
||||
(index: number, message: NativeChatMessage): MobileNativeChatTurnRow => {
|
||||
(listIndex: number, message: NativeChatMessage): MobileNativeChatTurnRow => {
|
||||
const index = waiting.indexById?.get(message.id) ?? listIndex
|
||||
const turnKey = turnKeys[index]
|
||||
const anchorsTurnHere = turnKey !== undefined && selfAnchors.get(turnKey) === index
|
||||
// The live turn's bar carries its running clock; it settles in place. Only
|
||||
// the bubble that opened a turn carries its bar: a message the provider
|
||||
// folded into a running turn shares the turn's key but not its bar.
|
||||
const turnStatus = !enabled
|
||||
? null
|
||||
: message.role === 'user' && message.id === activeTurnKey
|
||||
? active
|
||||
: message.role === 'user' && turnKey === message.id
|
||||
? (completedByTurn[turnKey] ?? null)
|
||||
: anchorsTurnHere
|
||||
? turnKey === activeTurnKey
|
||||
? (active ?? completedByTurn[turnKey] ?? null)
|
||||
: (completedByTurn[turnKey] ?? null)
|
||||
: null
|
||||
const bar = turnKey === undefined ? undefined : bars.get(turnKey)
|
||||
// A turn's bar draws at its first row; the live turn's carries its running clock and settles
|
||||
// in place. A message folded into a turn (a steer) carries none.
|
||||
const turnStatus =
|
||||
enabled && turnKey !== undefined && bar?.index === index
|
||||
? turnKey === activeTurnKey
|
||||
? active
|
||||
: (completedByTurn[turnKey] ?? null)
|
||||
: null
|
||||
return {
|
||||
turnStatus,
|
||||
...(anchorsTurnHere && turnStatus !== null ? { turnStatusAbove: true } : {}),
|
||||
...(bar?.above === true && turnStatus !== null ? { turnStatusAbove: true } : {}),
|
||||
turnExpanded: turnKey ? expandedTurnIds.has(turnKey) : false,
|
||||
// Why: the key travels and the row calls one stable handler with it. A
|
||||
// closure per row would be a new identity every render of a streaming
|
||||
// transcript, defeating the row's memo; caching one per turn would mean
|
||||
// writing a ref during render, which react-freeze can discard.
|
||||
turnKey: turnKey && turnStatus?.workedSeconds != null ? turnKey : undefined,
|
||||
// Liveness is the owning turn's, not the newest prompt's: a running turn's
|
||||
// rows stay live while a newer message waits behind it.
|
||||
activeTurnIsWorking:
|
||||
enabled &&
|
||||
isWorking &&
|
||||
(turnKey === activeTurnKey ||
|
||||
(turnKey === undefined && activeTurnKey === NATIVE_CHAT_UNANCHORED_TURN_KEY))
|
||||
// Liveness is the live turn's rows, not the newest prompt's: a running turn's rows stay live
|
||||
// while a newer message waits behind it. With no user boundary at all, the session's
|
||||
// working state stays authoritative.
|
||||
activeTurnIsWorking: enabled && isWorking && turnKey === liveTurnKey
|
||||
}
|
||||
},
|
||||
[
|
||||
turnKeys,
|
||||
selfAnchors,
|
||||
waiting,
|
||||
bars,
|
||||
liveTurnKey,
|
||||
enabled,
|
||||
activeTurnKey,
|
||||
active,
|
||||
@@ -167,6 +178,8 @@ export function useMobileNativeChatTurnDisclosure({
|
||||
activeActivityText,
|
||||
/** Stable for a given chat scope, so it never disturbs a row's memo. */
|
||||
onToggleTurn: toggleExpandedTurn,
|
||||
resolveRow
|
||||
resolveRow,
|
||||
listMessages: waiting.listMessages,
|
||||
waitingRows: waiting.waitingRows
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { NativeChatMessage } from '../../../src/shared/native-chat-types'
|
||||
import {
|
||||
NATIVE_CHAT_UNANCHORED_TURN_KEY,
|
||||
reduceNativeChatTurnTiming,
|
||||
selectNativeChatActiveTurnKey,
|
||||
selectNativeChatTurnStatuses,
|
||||
type NativeChatSettledTurns,
|
||||
type NativeChatTurnStatus,
|
||||
@@ -22,27 +20,24 @@ type ScopedTurnTiming = {
|
||||
/** Per-turn "Thinking / Working for N / Worked for N" timing, on the same shared
|
||||
* state machine the desktop renderer uses so the two surfaces stamp turns alike. */
|
||||
export function useMobileNativeChatTurnStatus({
|
||||
messages,
|
||||
turnKeys,
|
||||
liveTurnKey,
|
||||
enabled,
|
||||
isWorking,
|
||||
workingStartedAt,
|
||||
settledTurns,
|
||||
activeTurnOpenedBy = null,
|
||||
turnKeysByItemId = null,
|
||||
thinking = false,
|
||||
scopeKey
|
||||
}: {
|
||||
messages: readonly NativeChatMessage[]
|
||||
/** Each row's turn, as `nativeChatTurnMembership` places it. */
|
||||
turnKeys: readonly (string | undefined)[]
|
||||
/** The live turn, whose bar carries the running clock (`nativeChatTurnMembership`). */
|
||||
liveTurnKey: string | undefined
|
||||
enabled: boolean
|
||||
isWorking: boolean
|
||||
workingStartedAt?: number | null
|
||||
/** Host-recorded durations; they outrank whatever this client observed. */
|
||||
settledTurns?: NativeChatSettledTurns | null
|
||||
/** The user message the host says opened the running turn; absent, the latest one. */
|
||||
activeTurnOpenedBy?: string | null
|
||||
/** Host-attributed turn ownership; a turn keyed to its own record is still in
|
||||
* the transcript, so its clock is not an echo to hand to the next prompt. */
|
||||
turnKeysByItemId?: ReadonlyMap<string, string> | null
|
||||
/** Whether the turn is reasoning right now, derived from its journal content. */
|
||||
thinking?: boolean
|
||||
/** Host/worktree/tab identity. Timings never carry across chat surfaces. */
|
||||
@@ -52,9 +47,7 @@ export function useMobileNativeChatTurnStatus({
|
||||
completedByTurn: Readonly<Record<string, NativeChatTurnStatus>>
|
||||
activeTurnKey: string
|
||||
} {
|
||||
const activeTurnKey = enabled
|
||||
? selectNativeChatActiveTurnKey(messages, activeTurnOpenedBy)
|
||||
: NATIVE_CHAT_UNANCHORED_TURN_KEY
|
||||
const activeTurnKey = (enabled ? liveTurnKey : undefined) ?? NATIVE_CHAT_UNANCHORED_TURN_KEY
|
||||
const [scopedTiming, setScopedTiming] = useState<ScopedTurnTiming>(() => ({
|
||||
scopeKey,
|
||||
timingByTurn: {}
|
||||
@@ -73,12 +66,7 @@ export function useMobileNativeChatTurnStatus({
|
||||
if (!enabled) {
|
||||
return
|
||||
}
|
||||
const validTurnKeys = new Set(
|
||||
messages.filter((message) => message.role === 'user').map((message) => message.id)
|
||||
)
|
||||
for (const turnKey of turnKeysByItemId?.values() ?? []) {
|
||||
validTurnKeys.add(turnKey)
|
||||
}
|
||||
const validTurnKeys = new Set(turnKeys.filter((turnKey) => turnKey !== undefined))
|
||||
const previousActiveTurnKey =
|
||||
previousActiveTurn.current?.scopeKey === scopeKey
|
||||
? previousActiveTurn.current.turnKey
|
||||
@@ -99,7 +87,7 @@ export function useMobileNativeChatTurnStatus({
|
||||
? current
|
||||
: { scopeKey, timingByTurn: nextTiming }
|
||||
})
|
||||
}, [activeTurnKey, enabled, isWorking, messages, scopeKey, turnKeysByItemId, workingStartedAt])
|
||||
}, [activeTurnKey, enabled, isWorking, scopeKey, turnKeys, workingStartedAt])
|
||||
|
||||
// Why: the selection rebuilds its status objects on every call, and a streaming
|
||||
// turn re-renders ~20x/s. Without this, every settled turn's row gets fresh
|
||||
|
||||
@@ -86,7 +86,8 @@ describe('useMobileStructuredAgentTurnTiming', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(CLIENT_NOW)
|
||||
const items = [
|
||||
user('u1', 1),
|
||||
// The acknowledged send: its entry's key is the submission's, not the provider's.
|
||||
user('orca:first', 1),
|
||||
lifecycle(
|
||||
't1',
|
||||
2,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
AgentJournalSubmission
|
||||
} from '../../../src/shared/agent-session-journal-types'
|
||||
import type { NativeChatSettledTurns } from '../../../src/shared/native-chat-turn-status'
|
||||
import type { NativeChatTurnJournal } from '../../../src/shared/native-chat-turn-membership'
|
||||
import type { StructuredAgentHostClock } from '../../../src/shared/structured-agent-session-reducer'
|
||||
import { selectStructuredAgentTurnBars } from '../../../src/shared/structured-agent-session-turn-timing'
|
||||
import {
|
||||
@@ -12,10 +13,8 @@ import {
|
||||
} from '../../../src/shared/structured-agent-turn-clock-anchor'
|
||||
|
||||
/** Host-recorded turn timing for the structured lane: settled durations straight
|
||||
* off the journal, the transcript key that owns the running turn's bar, each
|
||||
* row's owning turn, and a
|
||||
* skew-free start for the live counter whose host-to-local conversion is latched
|
||||
* once per turn. */
|
||||
* off the journal, and a skew-free start for the live counter whose host-to-local
|
||||
* conversion is latched once per turn. */
|
||||
export function useMobileStructuredAgentTurnTiming(
|
||||
{
|
||||
items,
|
||||
@@ -29,14 +28,15 @@ export function useMobileStructuredAgentTurnTiming(
|
||||
turnId: string | null
|
||||
): {
|
||||
settledTurns: NativeChatSettledTurns
|
||||
/** What places each transcript row in its turn; the same read desktop makes. */
|
||||
turnJournal: NativeChatTurnJournal
|
||||
workingStartedAt: number | null
|
||||
activeTurnOpenedBy: string | null
|
||||
turnKeysByItemId: ReadonlyMap<string, string>
|
||||
} {
|
||||
const { settledTurns, runningTiming, activeTurnOpenedBy, turnKeysByItemId } = useMemo(
|
||||
const { settledTurns, runningTiming } = useMemo(
|
||||
() => selectStructuredAgentTurnBars(items, submissions, turnId),
|
||||
[items, submissions, turnId]
|
||||
)
|
||||
const turnJournal = useMemo(() => ({ items, submissions }), [items, submissions])
|
||||
const [latch, setLatch] = useState<StructuredAgentTurnClockLatch | null>(null)
|
||||
// Stamp during render (React's derive-from-props pattern) so the first paint of
|
||||
// a new turn already counts from the right instant.
|
||||
@@ -50,10 +50,5 @@ export function useMobileStructuredAgentTurnTiming(
|
||||
if (step.latch !== latch) {
|
||||
setLatch(step.latch)
|
||||
}
|
||||
return {
|
||||
settledTurns,
|
||||
workingStartedAt: step.workingStartedAt,
|
||||
activeTurnOpenedBy,
|
||||
turnKeysByItemId
|
||||
}
|
||||
return { settledTurns, turnJournal, workingStartedAt: step.workingStartedAt }
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
@@ -94,12 +95,16 @@ describe('Claude background task row journal', () => {
|
||||
}
|
||||
const resolver = new ClaudeBackgroundTaskIdentityResolver()
|
||||
|
||||
expect(writeClaudeBackgroundTaskRow(sink, resolver, 'task-1', task)).toEqual({
|
||||
expect(
|
||||
writeClaudeBackgroundTaskRow(sink, resolver, 'task-1', task, () => AGENT_JOURNAL_THREAD_SCOPE)
|
||||
).toEqual({
|
||||
accepted: false,
|
||||
reason: 'backpressure'
|
||||
})
|
||||
expect(task.lastSerialized).toBeNull()
|
||||
expect(writeClaudeBackgroundTaskRow(sink, resolver, 'task-1', task)).toEqual({
|
||||
expect(
|
||||
writeClaudeBackgroundTaskRow(sink, resolver, 'task-1', task, () => AGENT_JOURNAL_THREAD_SCOPE)
|
||||
).toEqual({
|
||||
accepted: true
|
||||
})
|
||||
expect(task.lastSerialized).not.toBeNull()
|
||||
@@ -130,7 +135,13 @@ describe('Claude background task row journal', () => {
|
||||
}
|
||||
|
||||
expect(
|
||||
writeClaudeBackgroundTaskRow(sink, new ClaudeBackgroundTaskIdentityResolver(), 'task-1', task)
|
||||
writeClaudeBackgroundTaskRow(
|
||||
sink,
|
||||
new ClaudeBackgroundTaskIdentityResolver(),
|
||||
'task-1',
|
||||
task,
|
||||
() => AGENT_JOURNAL_THREAD_SCOPE
|
||||
)
|
||||
).toEqual({ accepted: true })
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
@@ -153,7 +164,8 @@ describe('Claude background task row journal', () => {
|
||||
publish: vi.fn(),
|
||||
tryAppendResolvedItemAndPublish: appendAndPublish
|
||||
},
|
||||
isForwardedParentTool: () => true
|
||||
isForwardedParentTool: () => true,
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
|
||||
rows.observe(START_BASH)
|
||||
@@ -175,7 +187,8 @@ describe('Claude background task row journal', () => {
|
||||
publish: vi.fn(),
|
||||
tryAppendResolvedItemAndPublish: appendAndPublish
|
||||
},
|
||||
isForwardedParentTool: () => true
|
||||
isForwardedParentTool: () => true,
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
|
||||
rows.observe({
|
||||
@@ -203,7 +216,8 @@ describe('Claude background task row journal', () => {
|
||||
publish: vi.fn(),
|
||||
tryAppendResolvedItemAndPublish: appendAndPublish
|
||||
},
|
||||
isForwardedParentTool: () => true
|
||||
isForwardedParentTool: () => true,
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
|
||||
expect(rows.observe(START_BASH)).toBe(true)
|
||||
@@ -227,7 +241,8 @@ describe('Claude background task row journal', () => {
|
||||
tryAppendResolvedItemAndPublish: appendAndPublish
|
||||
},
|
||||
isForwardedParentTool: () => true,
|
||||
onPersistenceFailure
|
||||
onPersistenceFailure,
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
|
||||
rows.observe(START_BASH)
|
||||
@@ -249,7 +264,8 @@ describe('Claude background task row journal', () => {
|
||||
}))
|
||||
},
|
||||
isForwardedParentTool: () => true,
|
||||
onPersistenceFailure
|
||||
onPersistenceFailure,
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
|
||||
for (let index = 0; index < 512; index += 1) {
|
||||
@@ -287,7 +303,13 @@ describe('Claude background task row journal', () => {
|
||||
}
|
||||
|
||||
expect(
|
||||
writeClaudeBackgroundTaskRow(sink, new ClaudeBackgroundTaskIdentityResolver(), 'task-1', task)
|
||||
writeClaudeBackgroundTaskRow(
|
||||
sink,
|
||||
new ClaudeBackgroundTaskIdentityResolver(),
|
||||
'task-1',
|
||||
task,
|
||||
() => AGENT_JOURNAL_THREAD_SCOPE
|
||||
)
|
||||
).toEqual({ accepted: false, reason })
|
||||
expect(task.lastSerialized).toBeNull()
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { backgroundTaskFallbackText } from '../../shared/native-chat-background-task-row'
|
||||
import {
|
||||
@@ -141,6 +142,8 @@ export function writeClaudeBackgroundTaskRow(
|
||||
identities: ClaudeBackgroundTaskIdentityResolver,
|
||||
id: string,
|
||||
row: ClaudeBackgroundTaskRow,
|
||||
/** The turn the row belongs to, read once `beforeAppend` has opened it. */
|
||||
turnScope: () => AgentJournalTurnScope,
|
||||
/** Runs before admission to preserve turn-before-row ordering; duplicate
|
||||
* delivery skips it, and a retry reuses the turn the first attempt opened. */
|
||||
beforeAppend?: () => void,
|
||||
@@ -157,7 +160,11 @@ export function writeClaudeBackgroundTaskRow(
|
||||
// recreated. Keep unresolved writes from distinct provider runs queued side
|
||||
// by using the provider's parent tool identity as the coalescing discriminator.
|
||||
const coalescingKey = JSON.stringify(['claude-background-task', id, row.toolUseId ?? null])
|
||||
const appendOptions = { coalescingKey, ...(lifecycle ? { lifecycle: true } : {}) }
|
||||
const appendOptions = {
|
||||
coalescingKey,
|
||||
turnScope: turnScope(),
|
||||
...(lifecycle ? { lifecycle: true } : {})
|
||||
}
|
||||
const publishOptions = lifecycle ? { lifecycle: true } : {}
|
||||
const resolveIdentity = (journal: StructuredAgentSessionLifecycleJournal) =>
|
||||
identities.resolve(journal, id, row.toolUseId)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
// Shared fixtures and the sink harness the background-task row suites drive.
|
||||
//
|
||||
// Moved out of claude-background-task-rows.test.ts verbatim when that suite
|
||||
@@ -85,7 +86,8 @@ export function harness(
|
||||
sink,
|
||||
isForwardedParentTool: (toolUseId) => forwardedTools.has(toolUseId),
|
||||
openOutputTurn: () => turnOpens.push(1),
|
||||
now: () => (clock += 10)
|
||||
now: () => (clock += 10),
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
const keys = (): string[] =>
|
||||
items.map((item) =>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session-journal-types'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionSinkAdmission
|
||||
@@ -19,6 +20,7 @@ export class ClaudeBackgroundTaskRowWriter {
|
||||
|
||||
constructor(
|
||||
private readonly sink: StructuredAgentSessionEventSink,
|
||||
private readonly turnScope: () => AgentJournalTurnScope,
|
||||
private readonly onPersistenceFailure?: (error: Error) => void
|
||||
) {}
|
||||
|
||||
@@ -33,6 +35,7 @@ export class ClaudeBackgroundTaskRowWriter {
|
||||
this.identities,
|
||||
id,
|
||||
row,
|
||||
this.turnScope,
|
||||
beforeAppend,
|
||||
lifecycle
|
||||
)
|
||||
@@ -61,6 +64,7 @@ export class ClaudeBackgroundTaskRowWriter {
|
||||
this.identities,
|
||||
pending.id,
|
||||
pending.row,
|
||||
this.turnScope,
|
||||
undefined,
|
||||
pending.lifecycle
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// One durable row per Claude background `task_id`, revised in place from the
|
||||
// lifecycle frames so a failed command prints once with the provider sentence.
|
||||
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session-journal-types'
|
||||
import { isSettledBackgroundTaskState } from '../../shared/native-chat-background-task-row'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import { record, taskAliasId } from './claude-background-task-frames'
|
||||
@@ -46,6 +47,8 @@ export type ClaudeBackgroundTaskRowsDeps = {
|
||||
* output, so writing one must reopen a turn the provider resumed itself —
|
||||
* otherwise the session renders the row while reporting idle. */
|
||||
openOutputTurn?: (frame: Record<string, unknown>, observedAt: number) => void
|
||||
/** The turn a row written now belongs to: the open one, else the conversation. */
|
||||
turnScope: () => AgentJournalTurnScope
|
||||
onPersistenceFailure?: (error: Error) => void
|
||||
now?: () => number
|
||||
}
|
||||
@@ -60,7 +63,11 @@ export class ClaudeBackgroundTaskRows {
|
||||
|
||||
constructor(private readonly deps: ClaudeBackgroundTaskRowsDeps) {
|
||||
this.now = deps.now ?? (() => Date.now())
|
||||
this.writer = new ClaudeBackgroundTaskRowWriter(deps.sink, deps.onPersistenceFailure)
|
||||
this.writer = new ClaudeBackgroundTaskRowWriter(
|
||||
deps.sink,
|
||||
deps.turnScope,
|
||||
deps.onPersistenceFailure
|
||||
)
|
||||
this.overflowTerminalRows = new ClaudeOverflowTerminalRows(
|
||||
this.ledgers,
|
||||
this.now,
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
// Claude Code 2.1.283 (SDK 0.3.251) stream-json captures of `/compact`, driven through `query()` with
|
||||
// streaming input and cut to the protocol fields Orca reads. The session id and the summary text
|
||||
// are replaced, and every frame carried `session_id: CAPTURED_COMPACT_SESSION_ID`; frame order,
|
||||
// uuids and the relative clock (`at`, ms) are the captured ones.
|
||||
//
|
||||
// Verified from these frames: a finished and a stopped `/compact` both end in a `success` result
|
||||
// with no `terminal_reason`, naming the command's input in `user_message_uuid`. Only the finished
|
||||
// one carries a `compact_boundary`; the stopped one answers with a synthetic "Compaction canceled."
|
||||
// instead. `command_lifecycle` frames bracket every input.
|
||||
|
||||
export type CapturedCompactEvent =
|
||||
| { at: number; sent: { text: string; uuid: string } }
|
||||
| { at: number; interrupt: true }
|
||||
| { at: number; frame: Record<string, unknown> }
|
||||
|
||||
export const CAPTURED_COMPACT_SESSION_ID = '00000000-0000-4000-8000-000000000001'
|
||||
|
||||
const lifecycle = (commandUuid: string, state: string) => ({
|
||||
type: 'command_lifecycle',
|
||||
command_uuid: commandUuid,
|
||||
state
|
||||
})
|
||||
|
||||
/** A `/compact` left to finish, from its send to its result. */
|
||||
export const CAPTURED_COMPACT_SUCCEEDS: CapturedCompactEvent[] = [
|
||||
{ at: 1750, sent: { text: '/compact', uuid: '563c9bb2-241a-4946-a35b-0f9088fd05de' } },
|
||||
{ at: 1751, frame: lifecycle('968b34fc-76cc-41bc-adfc-34f8840637a0', 'completed') },
|
||||
{ at: 1753, frame: lifecycle('563c9bb2-241a-4946-a35b-0f9088fd05de', 'queued') },
|
||||
{ at: 1753, frame: lifecycle('563c9bb2-241a-4946-a35b-0f9088fd05de', 'started') },
|
||||
{
|
||||
at: 1757,
|
||||
frame: {
|
||||
type: 'system',
|
||||
subtype: 'status',
|
||||
status: 'compacting',
|
||||
uuid: 'de45cbf4-0f29-4ad7-a2a4-f9d9d8847f88'
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 6602,
|
||||
frame: {
|
||||
type: 'system',
|
||||
subtype: 'status',
|
||||
status: null,
|
||||
compact_result: 'success',
|
||||
uuid: 'c9cd62b1-02d9-48fc-bb07-1ccb4889c0af'
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 6608,
|
||||
frame: {
|
||||
type: 'system',
|
||||
subtype: 'init',
|
||||
uuid: '9cebf016-94d0-43d5-a23b-acbd606efeae',
|
||||
model: 'claude-opus-5-5[1m]'
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 6609,
|
||||
frame: {
|
||||
type: 'system',
|
||||
subtype: 'compact_boundary',
|
||||
compact_metadata: {
|
||||
trigger: 'manual',
|
||||
pre_tokens: 13576,
|
||||
post_tokens: 1011,
|
||||
cumulative_dropped_tokens: 12565,
|
||||
duration_ms: 4711
|
||||
},
|
||||
uuid: '1ed30bd1-8113-4c3d-b4ef-8020a2f80bfe'
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 6609,
|
||||
frame: {
|
||||
type: 'user',
|
||||
parent_tool_use_id: null,
|
||||
isReplay: false,
|
||||
isSynthetic: true,
|
||||
uuid: '4fa68de9-8e28-40d1-a332-da8dba6edd14',
|
||||
message: {
|
||||
role: 'user',
|
||||
content:
|
||||
'This session is being continued from a previous conversation that ran out of context. [summary scrubbed]'
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 6609,
|
||||
frame: {
|
||||
type: 'user',
|
||||
parent_tool_use_id: null,
|
||||
isReplay: true,
|
||||
uuid: '302b225c-05fd-45a5-ac2d-0435f9b50845',
|
||||
message: { role: 'user', content: '<local-command-stdout>Compacted</local-command-stdout>' }
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 6609,
|
||||
frame: {
|
||||
type: 'result',
|
||||
subtype: 'success',
|
||||
is_error: false,
|
||||
result: '',
|
||||
user_message_uuid: '563c9bb2-241a-4946-a35b-0f9088fd05de',
|
||||
uuid: 'd4c86a55-621b-40ae-9f26-612c842d3ca2'
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
/** A `/compact` interrupted 1.5 s in, then the next send and its own answer. */
|
||||
export const CAPTURED_COMPACT_STOPPED_THEN_SEND: CapturedCompactEvent[] = [
|
||||
{ at: 9663, sent: { text: '/compact', uuid: 'a4e04ce1-37ad-4d40-aaf8-e03a1bbbbc7d' } },
|
||||
{ at: 9664, frame: lifecycle('0be27e6d-49b7-4ee8-a784-744b3fb3b55c', 'completed') },
|
||||
{ at: 9664, frame: lifecycle('a4e04ce1-37ad-4d40-aaf8-e03a1bbbbc7d', 'queued') },
|
||||
{ at: 9665, frame: lifecycle('a4e04ce1-37ad-4d40-aaf8-e03a1bbbbc7d', 'started') },
|
||||
{
|
||||
at: 9666,
|
||||
frame: {
|
||||
type: 'system',
|
||||
subtype: 'status',
|
||||
status: 'compacting',
|
||||
uuid: 'c85f1131-b4a5-424e-af6a-85e8bd98b2fc'
|
||||
}
|
||||
},
|
||||
{ at: 11166, interrupt: true },
|
||||
{
|
||||
at: 11168,
|
||||
frame: {
|
||||
type: 'system',
|
||||
subtype: 'status',
|
||||
status: null,
|
||||
compact_result: 'failed',
|
||||
compact_error: 'API Error: Request was aborted.',
|
||||
uuid: '7fede6b2-afdf-4455-8c69-096ae3fa6f55'
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 11170,
|
||||
frame: {
|
||||
type: 'system',
|
||||
subtype: 'init',
|
||||
uuid: '067d1daa-f0da-4ca0-a9de-bedaa72c606a',
|
||||
model: 'claude-opus-5-5[1m]'
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 11170,
|
||||
frame: {
|
||||
type: 'assistant',
|
||||
parent_tool_use_id: null,
|
||||
uuid: '0d252793-d95f-4c80-b4a1-7309614b7eeb',
|
||||
message: {
|
||||
id: '9c14e2f0-6480-4760-92f8-aa73e461bc47',
|
||||
model: '<synthetic>',
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', text: 'Compaction canceled.' }]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 11170,
|
||||
frame: {
|
||||
type: 'result',
|
||||
subtype: 'success',
|
||||
is_error: false,
|
||||
result: '',
|
||||
user_message_uuid: 'a4e04ce1-37ad-4d40-aaf8-e03a1bbbbc7d',
|
||||
uuid: '523a8c1d-5054-422e-b81e-f5f350d992fd'
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 11170,
|
||||
sent: {
|
||||
text: 'Reply with the single word AFTERSTOP.',
|
||||
uuid: '4178c081-0d9e-414f-a861-ea156efa1e7e'
|
||||
}
|
||||
},
|
||||
{ at: 11170, frame: lifecycle('a4e04ce1-37ad-4d40-aaf8-e03a1bbbbc7d', 'cancelled') },
|
||||
{ at: 11171, frame: lifecycle('4178c081-0d9e-414f-a861-ea156efa1e7e', 'queued') },
|
||||
{ at: 11171, frame: lifecycle('4178c081-0d9e-414f-a861-ea156efa1e7e', 'started') },
|
||||
{
|
||||
at: 11200,
|
||||
frame: {
|
||||
type: 'system',
|
||||
subtype: 'init',
|
||||
uuid: '1eedc4e5-d48c-4682-b593-144466641d13',
|
||||
model: 'claude-opus-5-5[1m]'
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 12778,
|
||||
frame: {
|
||||
type: 'assistant',
|
||||
user_message_uuid: '4178c081-0d9e-414f-a861-ea156efa1e7e',
|
||||
parent_tool_use_id: null,
|
||||
uuid: '39969651-5abd-4dba-ae80-ab1299c07a47',
|
||||
message: {
|
||||
id: 'msg_011CfUXeXFfvAtj1PLLjB1H4',
|
||||
model: 'claude-opus-5-5',
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', text: 'AFTERSTOP' }]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
at: 12844,
|
||||
frame: {
|
||||
type: 'result',
|
||||
subtype: 'success',
|
||||
is_error: false,
|
||||
terminal_reason: 'completed',
|
||||
result: 'AFTERSTOP',
|
||||
user_message_uuid: '4178c081-0d9e-414f-a861-ea156efa1e7e',
|
||||
uuid: 'd9b4faaa-f9be-4d7b-9f81-a5106bd003f3'
|
||||
}
|
||||
},
|
||||
{ at: 12844, frame: lifecycle('4178c081-0d9e-414f-a861-ea156efa1e7e', 'completed') }
|
||||
]
|
||||
@@ -0,0 +1,367 @@
|
||||
// A `/compact` as the Claude translator's open turn, driven by real captured frames: which of them
|
||||
// end the command, how, and what the timeline draws.
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { readAgentJournalTurn } from '../../shared/agent-session-turn-record'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionRevisionJournal
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import {
|
||||
CAPTURED_COMPACT_SESSION_ID,
|
||||
CAPTURED_COMPACT_STOPPED_THEN_SEND,
|
||||
CAPTURED_COMPACT_SUCCEEDS,
|
||||
type CapturedCompactEvent
|
||||
} from './claude-captured-compact-frames.test-fixture'
|
||||
import { createClaudeJournalTranslator } from './claude-structured-journal-translation'
|
||||
|
||||
const COMMAND_IDENTITY: AgentJournalItemIdentity = {
|
||||
provider: 'orca',
|
||||
clientMessageId: 'command-turn:cmd-1'
|
||||
}
|
||||
const COMMAND_KEY = agentJournalItemKey(COMMAND_IDENTITY)
|
||||
const IN_COMMAND: AgentJournalTurnScope = { kind: 'turn', turnItemId: COMMAND_KEY }
|
||||
const RUNNING = {
|
||||
kind: 'turn' as const,
|
||||
turnId: 'compact:cmd-1',
|
||||
state: 'running' as const,
|
||||
userItemId: 'orca:submission:cmd-1',
|
||||
requestedAt: 900,
|
||||
startedAt: 1_000
|
||||
}
|
||||
|
||||
type Row = { key: string; body: AgentJournalItemBody; turnScope?: AgentJournalTurnScope }
|
||||
|
||||
/** A sink over a journal that holds the host's running command turn, revising rows in place. */
|
||||
function harness() {
|
||||
const rows = new Map<string, Row>([[COMMAND_KEY, { key: COMMAND_KEY, body: RUNNING }]])
|
||||
const writes: Row[] = []
|
||||
const write = (
|
||||
identity: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody,
|
||||
turnScope?: AgentJournalTurnScope
|
||||
) => {
|
||||
const row = { key: agentJournalItemKey(identity), body, ...(turnScope ? { turnScope } : {}) }
|
||||
rows.set(row.key, row)
|
||||
writes.push(row)
|
||||
}
|
||||
const journal: StructuredAgentSessionRevisionJournal = {
|
||||
epoch: 'epoch-1',
|
||||
itemBody: (itemId) => rows.get(itemId)?.body ?? null,
|
||||
visitItems: (visit) => {
|
||||
let sequence = 0
|
||||
for (const row of rows.values()) {
|
||||
visit(row.key, sequence++, row.body)
|
||||
}
|
||||
}
|
||||
}
|
||||
const revise: NonNullable<StructuredAgentSessionEventSink['tryReviseResolvedItem']> = (
|
||||
_bytes,
|
||||
resolve,
|
||||
options
|
||||
) => {
|
||||
const resolved = resolve(journal)
|
||||
if (resolved) {
|
||||
write(resolved.identity, resolved.body, options.turnScope)
|
||||
}
|
||||
return { accepted: true }
|
||||
}
|
||||
const sink: StructuredAgentSessionEventSink = {
|
||||
appendItem: (identity, body, options) => write(identity, body, options.turnScope),
|
||||
appendTombstone: vi.fn(),
|
||||
publish: vi.fn(),
|
||||
tryReviseResolvedItem: revise,
|
||||
tryReviseResolvedItemAndPublish: revise
|
||||
}
|
||||
const translator = createClaudeJournalTranslator({ sink, fallbackIdPrefix: 'test' })
|
||||
const frame = (message: Record<string, unknown>, extra: Record<string, unknown> = {}) =>
|
||||
translator.handle({
|
||||
type: 'message',
|
||||
sessionId: 'orca-session',
|
||||
message: { session_id: CAPTURED_COMPACT_SESSION_ID, ...message },
|
||||
observedAt: 5_000,
|
||||
...extra
|
||||
})
|
||||
const begin = (sentUuid: string) =>
|
||||
translator.beginCommand({
|
||||
clientMessageId: 'cmd-1',
|
||||
turnId: RUNNING.turnId,
|
||||
identity: COMMAND_IDENTITY,
|
||||
resultIdentity: { provider: 'orca', clientMessageId: 'command-result:cmd-1' },
|
||||
running: RUNNING,
|
||||
providerSessionId: CAPTURED_COMPACT_SESSION_ID,
|
||||
sentUuid
|
||||
})
|
||||
/** Replays a capture as the adapter delivers it: `/compact` goes through `beginCommand`, and a
|
||||
* Stop marks the interrupt the way the cancel path does. */
|
||||
const replay = (events: readonly CapturedCompactEvent[]) => {
|
||||
for (const event of events) {
|
||||
if ('sent' in event) {
|
||||
if (event.sent.text === '/compact') {
|
||||
begin(event.sent.uuid)
|
||||
}
|
||||
} else if ('interrupt' in event) {
|
||||
translator.commandInterruptRequested(RUNNING.turnId)
|
||||
} else {
|
||||
frame(event.frame)
|
||||
}
|
||||
}
|
||||
}
|
||||
const commandTurn = () => readAgentJournalTurn(rows.get(COMMAND_KEY)?.body)
|
||||
const drawn = () =>
|
||||
[...rows.values()].filter((row) => row.key !== COMMAND_KEY && row.body.kind !== 'turn')
|
||||
return { translator, rows, writes, frame, begin, replay, commandTurn, drawn }
|
||||
}
|
||||
|
||||
describe('a captured /compact as the open Claude turn', () => {
|
||||
it('ends a finished compaction as a success, drawing only the compaction separator', () => {
|
||||
const { replay, commandTurn, drawn, translator } = harness()
|
||||
replay(CAPTURED_COMPACT_SUCCEEDS)
|
||||
|
||||
expect(commandTurn()).toMatchObject({
|
||||
turnId: RUNNING.turnId,
|
||||
state: 'completed',
|
||||
outcome: 'success',
|
||||
userItemId: RUNNING.userItemId,
|
||||
requestedAt: RUNNING.requestedAt,
|
||||
startedAt: RUNNING.startedAt
|
||||
})
|
||||
// Not the continuation summary, not the command's echo, not a lifecycle opcode row.
|
||||
expect(drawn()).toEqual([
|
||||
{
|
||||
key: agentJournalItemKey({ provider: 'orca', clientMessageId: 'command-result:cmd-1' }),
|
||||
body: { kind: 'status', text: 'Context compacted', presentation: 'compaction' },
|
||||
turnScope: IN_COMMAND
|
||||
}
|
||||
])
|
||||
expect(translator.commandTurnId).toBeNull()
|
||||
})
|
||||
|
||||
it("ends a stopped compaction as the user's cancellation, then answers the next send in its own turn", () => {
|
||||
const { replay, commandTurn, drawn, rows } = harness()
|
||||
replay(CAPTURED_COMPACT_STOPPED_THEN_SEND)
|
||||
|
||||
// Claude's result for the stopped command is `success` like a finished one's.
|
||||
expect(commandTurn()).toMatchObject({ state: 'interrupted', outcome: 'cancellation' })
|
||||
const answer = drawn().find((row) => row.body.kind === 'message')
|
||||
expect(answer?.body).toMatchObject({ role: 'assistant' })
|
||||
expect(answer?.turnScope).not.toEqual(IN_COMMAND)
|
||||
const answered = readAgentJournalTurn(
|
||||
answer?.turnScope?.kind === 'turn' ? rows.get(answer.turnScope.turnItemId)?.body : undefined
|
||||
)
|
||||
expect(answered).toMatchObject({ state: 'completed', outcome: 'success' })
|
||||
// "Compaction canceled." is the command's own output, and a stop earns no failure row.
|
||||
expect(drawn().filter((row) => row.body.kind === 'status')).toEqual([])
|
||||
})
|
||||
|
||||
it('reads a compaction with no boundary and no stop as a failure, with Claude’s reason', () => {
|
||||
const { replay, commandTurn, drawn } = harness()
|
||||
// The stopped capture without Orca's stop: Claude reported the compaction failed.
|
||||
replay(CAPTURED_COMPACT_STOPPED_THEN_SEND.filter((event) => !('interrupt' in event)))
|
||||
|
||||
expect(commandTurn()).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
expect(
|
||||
drawn().filter(
|
||||
(row) => row.turnScope?.kind === 'turn' && row.turnScope.turnItemId === COMMAND_KEY
|
||||
)
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
body: {
|
||||
kind: 'status',
|
||||
text: 'Compaction failed: API Error: Request was aborted.',
|
||||
failure: {
|
||||
kind: 'compactionFailed',
|
||||
detail: { text: 'API Error: Request was aborted.', audience: 'person' }
|
||||
},
|
||||
tone: 'error'
|
||||
}
|
||||
})
|
||||
])
|
||||
})
|
||||
|
||||
it('reads a stop that lands after the summary but before the boundary as a cancellation', () => {
|
||||
const { replay, commandTurn, drawn } = harness()
|
||||
// Only the boundary says the conversation was replaced; the status that precedes it does not.
|
||||
replay(
|
||||
CAPTURED_COMPACT_SUCCEEDS.flatMap((event): CapturedCompactEvent[] =>
|
||||
'frame' in event && event.frame.subtype === 'compact_boundary'
|
||||
? []
|
||||
: 'frame' in event && event.frame.compact_result === 'success'
|
||||
? [event, { at: event.at, interrupt: true }]
|
||||
: [event]
|
||||
)
|
||||
)
|
||||
|
||||
expect(commandTurn()).toMatchObject({ state: 'interrupted', outcome: 'cancellation' })
|
||||
expect(drawn().filter((row) => row.body.kind === 'status')).toEqual([])
|
||||
})
|
||||
|
||||
it('leaves the command running at a result that names another input', () => {
|
||||
const { begin, frame, commandTurn, translator } = harness()
|
||||
begin('compact-input')
|
||||
frame({ type: 'system', subtype: 'compact_boundary', uuid: 'boundary' })
|
||||
frame({ type: 'result', subtype: 'success', is_error: false, user_message_uuid: 'earlier' })
|
||||
expect(commandTurn()?.state).toBe('running')
|
||||
expect(translator.commandTurnId).toBe(RUNNING.turnId)
|
||||
|
||||
frame({
|
||||
type: 'result',
|
||||
subtype: 'success',
|
||||
is_error: false,
|
||||
user_message_uuid: 'compact-input'
|
||||
})
|
||||
expect(commandTurn()).toMatchObject({ state: 'completed', outcome: 'success' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('the command turn at each point the ordinary result path threads through', () => {
|
||||
it('suppresses a provider reopen after a command that failed, as after any failed turn', () => {
|
||||
const failed = harness()
|
||||
failed.begin('compact-input')
|
||||
failed.frame({ type: 'result', subtype: 'error_during_execution', is_error: true })
|
||||
failed.frame({
|
||||
type: 'assistant',
|
||||
uuid: 'stray',
|
||||
parent_tool_use_id: null,
|
||||
message: { id: 'msg-stray', role: 'assistant', content: [{ type: 'text', text: 'hi' }] }
|
||||
})
|
||||
expect(failed.translator.currentTurnId).toBeNull()
|
||||
|
||||
const finished = harness()
|
||||
finished.begin('compact-input')
|
||||
finished.frame({ type: 'system', subtype: 'compact_boundary', uuid: 'boundary' })
|
||||
finished.frame({ type: 'result', subtype: 'success', is_error: false })
|
||||
finished.frame({
|
||||
type: 'assistant',
|
||||
uuid: 'resumed',
|
||||
parent_tool_use_id: null,
|
||||
message: { id: 'msg-resumed', role: 'assistant', content: [{ type: 'text', text: 'hi' }] }
|
||||
})
|
||||
expect(finished.translator.currentTurnId).not.toBeNull()
|
||||
})
|
||||
|
||||
it("settles a child still working in the command's turn when the command ends", () => {
|
||||
const { begin, frame, rows } = harness()
|
||||
begin('compact-input')
|
||||
frame({
|
||||
type: 'system',
|
||||
subtype: 'task_started',
|
||||
task_id: 'task-1',
|
||||
task_type: 'local_agent',
|
||||
description: 'Map the lane'
|
||||
})
|
||||
frame({ type: 'result', subtype: 'success', is_error: false })
|
||||
const group = rows.get(
|
||||
agentJournalItemKey({
|
||||
provider: 'orca',
|
||||
clientMessageId: `claude-subagents:${CAPTURED_COMPACT_SESSION_ID}:${RUNNING.turnId}`
|
||||
})
|
||||
)
|
||||
const agents =
|
||||
group?.body.kind === 'message'
|
||||
? group.body.blocks.flatMap((block) =>
|
||||
block.type === 'subagent-group' ? block.agents : []
|
||||
)
|
||||
: []
|
||||
expect(agents).toEqual([expect.objectContaining({ state: 'unverifiable' })])
|
||||
})
|
||||
|
||||
it("records the context window the command's result reports on the command's turn", () => {
|
||||
const { begin, frame, commandTurn } = harness()
|
||||
begin('compact-input')
|
||||
frame({ type: 'system', subtype: 'init', model: 'claude-opus-5-5[1m]', uuid: 'init' })
|
||||
frame({ type: 'system', subtype: 'compact_boundary', uuid: 'boundary' })
|
||||
frame({
|
||||
type: 'result',
|
||||
subtype: 'success',
|
||||
is_error: false,
|
||||
modelUsage: { 'claude-opus-5-5[1m]': { contextWindow: 1_000_000 } }
|
||||
})
|
||||
expect(commandTurn()).toMatchObject({
|
||||
state: 'completed',
|
||||
contextUsage: { window: { tokens: 1_000_000 } }
|
||||
})
|
||||
})
|
||||
|
||||
it("reports a compaction Claude refused in Claude's own words, and one with none plainly", () => {
|
||||
const worded = harness()
|
||||
worded.begin('compact-input')
|
||||
worded.frame({
|
||||
type: 'system',
|
||||
subtype: 'status',
|
||||
compact_result: 'failed',
|
||||
compact_error: 'Not enough messages to compact.'
|
||||
})
|
||||
worded.frame({ type: 'result', subtype: 'success', is_error: false })
|
||||
expect(worded.commandTurn()).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
expect(worded.drawn().map((row) => row.body)).toEqual([
|
||||
{
|
||||
kind: 'status',
|
||||
text: 'Compaction failed: Not enough messages to compact.',
|
||||
failure: {
|
||||
kind: 'compactionFailed',
|
||||
detail: { text: 'Not enough messages to compact.', audience: 'person' }
|
||||
},
|
||||
tone: 'error'
|
||||
}
|
||||
])
|
||||
|
||||
const unworded = harness()
|
||||
unworded.begin('compact-input')
|
||||
unworded.frame({ type: 'system', subtype: 'status', compact_result: 'failed' })
|
||||
unworded.frame({ type: 'result', subtype: 'success', is_error: false })
|
||||
expect(unworded.drawn().map((row) => row.body)).toEqual([
|
||||
{
|
||||
kind: 'status',
|
||||
text: 'Compaction failed.',
|
||||
failure: { kind: 'compactionFailed' },
|
||||
tone: 'error'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('reports a result with no compaction and no failure as a compaction Claude never confirmed', () => {
|
||||
const { begin, frame, commandTurn, drawn } = harness()
|
||||
begin('compact-input')
|
||||
frame({ type: 'result', subtype: 'success', is_error: false })
|
||||
expect(commandTurn()).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
expect(drawn().map((row) => row.body)).toEqual([
|
||||
{
|
||||
kind: 'status',
|
||||
text: 'Compaction completion is unconfirmed.',
|
||||
failure: { kind: 'compactionUnconfirmed' },
|
||||
tone: 'error'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('fails a command whose result ended in error', () => {
|
||||
const { begin, frame, commandTurn } = harness()
|
||||
begin('compact-input')
|
||||
frame({ type: 'result', subtype: 'error_during_execution', is_error: true })
|
||||
expect(commandTurn()).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
})
|
||||
|
||||
it("draws one error row, the provider's, for a command whose result is an error", () => {
|
||||
const { begin, frame, drawn } = harness()
|
||||
begin('compact-input')
|
||||
frame({
|
||||
type: 'result',
|
||||
subtype: 'success',
|
||||
is_error: true,
|
||||
result: 'API Error: 529 upstream overloaded'
|
||||
})
|
||||
expect(drawn().filter((row) => row.body.kind === 'status')).toEqual([
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({ text: 'API Error: 529 upstream overloaded' }),
|
||||
turnScope: IN_COMMAND
|
||||
})
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,153 @@
|
||||
// A conversation command Claude runs as the session's open turn. The turn is the host's record, and
|
||||
// the command's own result ends it. Everything Claude writes for the command meanwhile — the
|
||||
// summary it continues from, the command's echo, a "Compaction canceled." — is the command's
|
||||
// output, never a reply, so none of it draws.
|
||||
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import { providerDiagnostic, type ProviderDiagnostic } from '../../shared/agent-session-failure'
|
||||
import { agentSessionFailureWords } from '../../shared/agent-session-failure-words'
|
||||
import { TUI_AGENT_DISPLAY_NAMES } from '../../shared/tui-agent-display-names'
|
||||
import type { StructuredAgentSessionCommandRun } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import { structuredCompactionOutcome } from '../native-chat/agent-session-wire/structured-conversation-command-outcome'
|
||||
import { claudeText } from './claude-structured-item-translation'
|
||||
import { claudeResultFailure } from './claude-structured-provider-fallback'
|
||||
import type { ClaudeCurrentTurn, ClaudeTurnEnd } from './claude-turn-lifecycle-item'
|
||||
import { isRootClaudeFrame } from './claude-turn-opening'
|
||||
import type { ClaudeOpenTurn } from './claude-open-turn'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
|
||||
export type ClaudeCommandTurn = {
|
||||
identity: AgentJournalItemIdentity
|
||||
resultIdentity: AgentJournalItemIdentity
|
||||
/** The command input's uuid, which the result answering it names. */
|
||||
sentUuid: string
|
||||
compacted: boolean
|
||||
/** Orca asked Claude to stop the command. */
|
||||
interruptRequested: boolean
|
||||
/** Claude reported the compaction failed, with its words for a person when it gave any. */
|
||||
failed: { detail?: ProviderDiagnostic } | null
|
||||
}
|
||||
|
||||
export type ClaudeCommandStart = StructuredAgentSessionCommandRun & {
|
||||
providerSessionId: string
|
||||
sentUuid: string
|
||||
}
|
||||
|
||||
export function claudeCommandCurrentTurn(start: ClaudeCommandStart): ClaudeCurrentTurn {
|
||||
const { running } = start
|
||||
return {
|
||||
sessionId: start.providerSessionId,
|
||||
turnId: start.turnId,
|
||||
startedAt: running.startedAt ?? Date.now(),
|
||||
...(running.requestedAt === undefined ? {} : { requestedAt: running.requestedAt }),
|
||||
userItemId: running.userItemId ?? agentJournalItemKey(start.identity),
|
||||
command: {
|
||||
identity: start.identity,
|
||||
resultIdentity: start.resultIdentity,
|
||||
sentUuid: start.sentUuid,
|
||||
compacted: false,
|
||||
interruptRequested: false,
|
||||
failed: null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a running command's evidence off a frame. True for the command's own output, which
|
||||
* draws nothing. */
|
||||
export function observeClaudeCommandFrame(
|
||||
command: ClaudeCommandTurn | null,
|
||||
message: Record<string, unknown>
|
||||
): boolean {
|
||||
if (!command) {
|
||||
return false
|
||||
}
|
||||
if (message.type === 'system') {
|
||||
// Only the boundary says the history was replaced; `compact_result: 'success'` precedes it.
|
||||
if (message.subtype === 'compact_boundary') {
|
||||
command.compacted = true
|
||||
} else if (message.compact_result === 'failed') {
|
||||
const words = claudeText(message.compact_error)
|
||||
const detail = words === null ? undefined : providerDiagnostic(words, 'person')
|
||||
command.failed = detail ? { detail } : {}
|
||||
}
|
||||
return false
|
||||
}
|
||||
return (
|
||||
isRootClaudeFrame(message) &&
|
||||
(message.type === 'user' || message.type === 'assistant' || message.type === 'stream_event')
|
||||
)
|
||||
}
|
||||
|
||||
/** The command's end from a root result, and the one row that reports it; null when the result
|
||||
* names another input. */
|
||||
export function claudeCommandEnd(
|
||||
command: ClaudeCommandTurn,
|
||||
message: Record<string, unknown>,
|
||||
completedAt: number
|
||||
): { end: ClaudeTurnEnd; row: AgentJournalItemBody | null } | null {
|
||||
const answers = claudeText(message.user_message_uuid)
|
||||
if (answers !== null && answers !== command.sentUuid) {
|
||||
return null
|
||||
}
|
||||
// A stopped `/compact` ends in the same success result as a finished one: only the provider's
|
||||
// report of the compaction tells them apart.
|
||||
const shown = claudeResultFailure(message)
|
||||
const verdict = structuredCompactionOutcome({
|
||||
compacted: command.compacted,
|
||||
interruptRequested: command.interruptRequested,
|
||||
failed: command.failed ?? (shown ? {} : null)
|
||||
})
|
||||
const durationMs = message.duration_ms
|
||||
const end: ClaudeTurnEnd = {
|
||||
state: verdict.outcome === 'cancellation' ? 'interrupted' : 'completed',
|
||||
completedAt,
|
||||
outcome: verdict.outcome,
|
||||
...(typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0
|
||||
? { durationMs }
|
||||
: {})
|
||||
}
|
||||
if (verdict.outcome === 'success') {
|
||||
return { end, row: { kind: 'status', text: 'Context compacted', presentation: 'compaction' } }
|
||||
}
|
||||
// An error result already draws its own row through the provider fallback.
|
||||
return verdict.failure && !shown
|
||||
? {
|
||||
end,
|
||||
row: {
|
||||
kind: 'status',
|
||||
...agentSessionFailureWords(verdict.failure, {
|
||||
surface: 'row',
|
||||
agentName: TUI_AGENT_DISPLAY_NAMES.claude
|
||||
}),
|
||||
tone: 'error'
|
||||
}
|
||||
}
|
||||
: { end, row: null }
|
||||
}
|
||||
|
||||
/** A root result, when a command is the open turn: the command's end, with its one result row
|
||||
* already written; `another-input` for a result that answers something else; null when no
|
||||
* command is open. */
|
||||
export function claudeCommandResultEnd(
|
||||
turn: Pick<ClaudeOpenTurn, 'command' | 'turnScope'>,
|
||||
sink: Pick<StructuredAgentSessionEventSink, 'appendItem'>,
|
||||
message: Record<string, unknown>,
|
||||
completedAt: number
|
||||
): ClaudeTurnEnd | 'another-input' | null {
|
||||
const { command } = turn
|
||||
if (!command) {
|
||||
return null
|
||||
}
|
||||
const ended = claudeCommandEnd(command, message, completedAt)
|
||||
if (!ended) {
|
||||
return 'another-input'
|
||||
}
|
||||
if (ended.row) {
|
||||
sink.appendItem(command.resultIdentity, ended.row, { turnScope: turn.turnScope })
|
||||
}
|
||||
return ended.end
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
type AgentSessionTokenUsage
|
||||
} from '../../shared/agent-session-context-usage'
|
||||
import type { ClaudeStreamJsonConnection } from './claude-stream-json-connection'
|
||||
import type { ClaudeJournalTranslator } from './claude-structured-journal-translation'
|
||||
import type { ClaudeJournalTranslator } from './claude-journal-translator-contract'
|
||||
|
||||
/** A report later than this describes a context the user has likely moved past. */
|
||||
export const CLAUDE_CONTEXT_USAGE_TIMEOUT_MS = 5_000
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { ClaudeChildToolQueries } from './claude-child-tool-queries'
|
||||
import type { ClaudeContextReportPart, ClaudeContextReportTarget } from './claude-context-facts'
|
||||
import type { ClaudeJournalPrompts } from './claude-structured-journal-prompts'
|
||||
import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state'
|
||||
import type { ClaudeCommandStart } from './claude-command-turn'
|
||||
|
||||
export type ClaudeJournalTranslator = {
|
||||
handle: (event: ClaudeStructuredSessionEvent) => void
|
||||
@@ -13,6 +14,14 @@ export type ClaudeJournalTranslator = {
|
||||
/** The open turn's provider id — the same id its journal row carries, and the one
|
||||
* a client's Stop names. Sole owner: no reader keeps a copy to disagree with. */
|
||||
readonly currentTurnId: string | null
|
||||
/** The open turn's id while it is a conversation command's. */
|
||||
readonly commandTurnId: string | null
|
||||
/** Makes the host's command turn the open one until the command's result ends it. */
|
||||
beginCommand: (start: ClaudeCommandStart) => void
|
||||
/** The command was never sent. */
|
||||
forgetCommand: (turnId: string) => void
|
||||
/** Orca asked Claude to stop the command `turnId` names. */
|
||||
commandInterruptRequested: (turnId: string) => void
|
||||
/** True while a turn is open and the provider's current request cycle has
|
||||
* done root work since its init — the state in which the CLI folds an
|
||||
* arriving send into the turn. */
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// Which turn a Claude row belongs to (B8): the root turn open when the row is written, whoever
|
||||
// produced it, and the conversation once that turn has ended.
|
||||
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionItemAppendOptions
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import { createClaudeJournalTranslator } from './claude-structured-journal-translation'
|
||||
|
||||
function recorder() {
|
||||
const writes: {
|
||||
identity: AgentJournalItemIdentity
|
||||
body: AgentJournalItemBody
|
||||
options: StructuredAgentSessionItemAppendOptions
|
||||
}[] = []
|
||||
const sink: StructuredAgentSessionEventSink = {
|
||||
appendItem: (identity, body, options) => writes.push({ identity, body, options }),
|
||||
appendTombstone: vi.fn(),
|
||||
publish: vi.fn()
|
||||
}
|
||||
const scopeOfProse = (text: string) =>
|
||||
writes.findLast(
|
||||
(write) =>
|
||||
write.body.kind === 'message' &&
|
||||
write.body.blocks.some((block) => block.type === 'text' && block.text === text)
|
||||
)?.options.turnScope
|
||||
return { sink, writes, scopeOfProse }
|
||||
}
|
||||
|
||||
function frame(message: Record<string, unknown>, startsTurn = false) {
|
||||
return {
|
||||
type: 'message' as const,
|
||||
sessionId: 'orca-session',
|
||||
...(startsTurn ? { startsTurn: true as const } : {}),
|
||||
message: { session_id: 'claude-session', ...message }
|
||||
}
|
||||
}
|
||||
|
||||
function prose(uuid: string, text: string, parentToolUseId: string | null = null) {
|
||||
return frame({
|
||||
type: 'assistant',
|
||||
uuid,
|
||||
parent_tool_use_id: parentToolUseId,
|
||||
message: { role: 'assistant', content: [{ type: 'text', text }] }
|
||||
})
|
||||
}
|
||||
|
||||
it("scopes the session's and a subagent's rows to the open turn, and a late one to none", () => {
|
||||
const { sink, writes, scopeOfProse } = recorder()
|
||||
const translator = createClaudeJournalTranslator({ sink, fallbackIdPrefix: 'test' })
|
||||
translator.handle(
|
||||
frame(
|
||||
{
|
||||
type: 'user',
|
||||
uuid: 'user-1',
|
||||
parent_tool_use_id: null,
|
||||
message: { role: 'user', content: [{ type: 'text', text: 'go' }] }
|
||||
},
|
||||
true
|
||||
)
|
||||
)
|
||||
translator.handle(prose('assistant-1', 'Working on it'))
|
||||
translator.handle(prose('child-1', 'Child mid-turn', 'toolu_1'))
|
||||
translator.handle(frame({ type: 'result', subtype: 'success', uuid: 'result-1', result: 'ok' }))
|
||||
translator.handle(prose('child-2', 'Child after the turn', 'toolu_1'))
|
||||
|
||||
const turnRecord = writes.find((write) => write.body.kind === 'turn')
|
||||
expect(turnRecord?.options.turnScope).toEqual({ kind: 'thread' })
|
||||
const turnKey = expect.stringContaining('turn-lifecycle')
|
||||
expect(scopeOfProse('Working on it')).toEqual({ kind: 'turn', turnItemId: turnKey })
|
||||
expect(scopeOfProse('Child mid-turn')).toEqual({ kind: 'turn', turnItemId: turnKey })
|
||||
expect(scopeOfProse('Child after the turn')).toEqual({ kind: 'thread' })
|
||||
})
|
||||
@@ -5,15 +5,21 @@
|
||||
// keeping a copy, so there is nothing to disagree with.
|
||||
|
||||
import type { AgentSessionContextUsage } from '../../shared/agent-session-context-usage'
|
||||
import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalItemIdentity,
|
||||
type AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import {
|
||||
claudeTurnLifecycleIdentity,
|
||||
claudeCurrentTurnIdentity,
|
||||
claudeTurnLifecycleItem,
|
||||
type ClaudeCurrentTurn,
|
||||
type ClaudeTurnEnd
|
||||
} from './claude-turn-lifecycle-item'
|
||||
import { writeClaudeTurnRow } from './claude-turn-row-revision'
|
||||
import type { ClaudeCommandTurn } from './claude-command-turn'
|
||||
import { createClaudeTurnOpener, type ClaudeTurnSource } from './claude-turn-opening'
|
||||
|
||||
export type ClaudeOpenTurnDeps = {
|
||||
@@ -55,9 +61,21 @@ export class ClaudeOpenTurn {
|
||||
|
||||
/** The open turn's row, where a fact about the running turn lands. */
|
||||
get identity(): AgentJournalItemIdentity | null {
|
||||
return this.current
|
||||
? claudeTurnLifecycleIdentity(this.current.sessionId, this.current.turnId)
|
||||
: null
|
||||
return this.current ? claudeCurrentTurnIdentity(this.current) : null
|
||||
}
|
||||
|
||||
/** The conversation command the open turn is, if it is one. */
|
||||
get command(): ClaudeCommandTurn | null {
|
||||
return this.current?.command ?? null
|
||||
}
|
||||
|
||||
/** Which turn a row written now belongs to: the open one, or none. A subagent's rows too —
|
||||
* its work is its parent turn's. */
|
||||
get turnScope(): AgentJournalTurnScope {
|
||||
const identity = this.identity
|
||||
return identity
|
||||
? { kind: 'turn', turnItemId: agentJournalItemKey(identity) }
|
||||
: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}
|
||||
|
||||
get groupKey(): string | null {
|
||||
@@ -99,6 +117,32 @@ export class ClaudeOpenTurn {
|
||||
this.deps.sink.setActivity?.(null)
|
||||
}
|
||||
|
||||
/** A conversation command the host opened a turn for. Its row is the host's, already written,
|
||||
* so only an end is published; the command's result is what ends it. */
|
||||
beginCommand(turn: ClaudeCurrentTurn): void {
|
||||
this.deps.onOpen?.()
|
||||
if (this.current) {
|
||||
this.deps.settleChildren(this.groupKey)
|
||||
this.publish(this.current, { state: 'interrupted', completedAt: turn.startedAt })
|
||||
}
|
||||
this.current = turn
|
||||
this.deps.sink.setActivity?.(null)
|
||||
}
|
||||
|
||||
/** Orca asked the provider to stop the command `turnId` names. */
|
||||
commandInterruptRequested(turnId: string): void {
|
||||
if (this.current?.command && this.current.turnId === turnId) {
|
||||
this.current.command.interruptRequested = true
|
||||
}
|
||||
}
|
||||
|
||||
/** The command was never sent; its turn is the host's to settle. */
|
||||
forgetCommand(turnId: string): void {
|
||||
if (this.current?.command && this.current.turnId === turnId) {
|
||||
this.current = null
|
||||
}
|
||||
}
|
||||
|
||||
/** The provider produced, so a turn is running. Idempotent: every frame of one
|
||||
* reply stays inside the turn its first frame opened. A subagent's output is
|
||||
* its parent turn's work and never a turn of its own. */
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
// Journaling an approval or question prompt, and remembering the rows it wrote
|
||||
// so a cancellation can tombstone exactly those.
|
||||
|
||||
import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state'
|
||||
import {
|
||||
claudeApprovalItem,
|
||||
claudePromptIdentity,
|
||||
claudeQuestionItems
|
||||
} from './claude-structured-prompt-items'
|
||||
|
||||
export type ClaudePromptJournalDeps = {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
bindPromptItemId?: (journalItemId: string, promptKey: string) => void
|
||||
/** Prompt key → the rows it wrote, owned by the translator so a cancel can sweep them. */
|
||||
promptItems: Map<string, AgentJournalItemIdentity[]>
|
||||
}
|
||||
|
||||
export function journalClaudePrompt(
|
||||
deps: ClaudePromptJournalDeps,
|
||||
event: Extract<ClaudeStructuredSessionEvent, { type: 'prompt' }>
|
||||
): void {
|
||||
const identities: AgentJournalItemIdentity[] = []
|
||||
if (event.prompt.kind === 'question') {
|
||||
for (const question of claudeQuestionItems({
|
||||
sessionId: event.sessionId,
|
||||
prompt: event.prompt
|
||||
})) {
|
||||
identities.push(question.identity)
|
||||
deps.sink.appendItem(question.identity, question.body)
|
||||
deps.bindPromptItemId?.(agentJournalItemKey(question.identity), event.prompt.promptKey)
|
||||
}
|
||||
} else {
|
||||
const identity = claudePromptIdentity({
|
||||
sessionId: event.sessionId,
|
||||
promptKey: event.prompt.promptKey
|
||||
})
|
||||
identities.push(identity)
|
||||
deps.sink.appendItem(identity, claudeApprovalItem(event.prompt))
|
||||
deps.bindPromptItemId?.(agentJournalItemKey(identity), event.prompt.promptKey)
|
||||
}
|
||||
deps.promptItems.set(event.prompt.promptKey, identities)
|
||||
deps.sink.publish()
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
@@ -38,6 +39,7 @@ function ledger(initial: Record<string, ClaudeSubagentLinkageVerdict> = {}) {
|
||||
: { kind: 'linked', linkage: { agentId: ref, providerParentRef: ref, producerKind: 'agent' } }
|
||||
}
|
||||
const corrections = new ClaudeProvisionalRowCorrections({
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE,
|
||||
linkageFor: (ref) => verdicts.get(ref) ?? { kind: 'pending' },
|
||||
settledLinkageFor: (ref) => {
|
||||
const verdict = settledFor(ref)
|
||||
@@ -71,9 +73,11 @@ function ledger(initial: Record<string, ClaudeSubagentLinkageVerdict> = {}) {
|
||||
}
|
||||
|
||||
describe('ClaudeProvisionalRowCorrections', () => {
|
||||
it("stamps the session's own rows with nothing and owes them nothing", () => {
|
||||
it("stamps the session's own rows with no producer and owes them nothing", () => {
|
||||
const { corrections, rewrites } = ledger()
|
||||
expect(corrections.stampFor(null)(identityOf('toolu_2'), RUNNING)).toEqual({})
|
||||
expect(corrections.stampFor(null)(identityOf('toolu_2'), RUNNING)).toEqual({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
expect(corrections.pending).toBe(0)
|
||||
corrections.retry()
|
||||
expect(rewrites).toEqual([])
|
||||
|
||||
@@ -21,9 +21,11 @@ import { agentJournalLinkageFields } from '../../shared/agent-session-journal-pr
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalProducerLinkage,
|
||||
AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import type { StructuredAgentSessionAppendOptions } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import type { StructuredAgentSessionItemAppendOptions } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import type { ClaudeSubagentLinkageSource } from './claude-subagent-linkage'
|
||||
|
||||
/**
|
||||
@@ -36,12 +38,7 @@ import type { ClaudeSubagentLinkageSource } from './claude-subagent-linkage'
|
||||
export type ClaudeRowStamp = (
|
||||
identity: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody
|
||||
) => StructuredAgentSessionAppendOptions
|
||||
|
||||
/** The session's own agent wrote this row: nothing is stamped, nothing is owed.
|
||||
* Only for a site with no ledger to consult; a ledger-backed root write goes
|
||||
* through `stampFor(null)`, which also supersedes anything owed to the row. */
|
||||
export const rootClaudeRowStamp: ClaudeRowStamp = () => ({})
|
||||
) => StructuredAgentSessionItemAppendOptions
|
||||
|
||||
/** Corrections outstanding at once, across every producer. */
|
||||
const MAX_OUTSTANDING_CORRECTIONS = 256
|
||||
@@ -57,17 +54,19 @@ type OutstandingCorrection = {
|
||||
* a tool call and its result do — and a correction carrying the older body
|
||||
* would revert the row it is only meant to re-attribute. */
|
||||
body: AgentJournalItemBody
|
||||
stamped: StructuredAgentSessionAppendOptions
|
||||
stamped: StructuredAgentSessionItemAppendOptions
|
||||
}
|
||||
|
||||
export type ClaudeProvisionalRowCorrectionsDeps = ClaudeSubagentLinkageSource & {
|
||||
/** The turn a row written now belongs to: the open root turn, whoever produced the row. */
|
||||
turnScope: () => AgentJournalTurnScope
|
||||
/** Re-appends a row under its own identity, which revises it in place.
|
||||
* Returns whether the write was ADMITTED: a sink under backpressure refuses,
|
||||
* and a correction dropped on a refusal is an obligation nothing re-derives. */
|
||||
rewrite: (
|
||||
identity: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody,
|
||||
options: StructuredAgentSessionAppendOptions
|
||||
options: StructuredAgentSessionItemAppendOptions
|
||||
) => boolean
|
||||
publish: () => void
|
||||
}
|
||||
@@ -92,12 +91,12 @@ export class ClaudeProvisionalRowCorrections {
|
||||
if (parentToolUseId === null) {
|
||||
return (identity) => {
|
||||
this.supersede(identity)
|
||||
return {}
|
||||
return { turnScope: this.deps.turnScope() }
|
||||
}
|
||||
}
|
||||
return (identity, body) => {
|
||||
const provisional = this.deps.linkageFor(parentToolUseId).kind === 'pending'
|
||||
const options = this.stamp(parentToolUseId)
|
||||
const options = { ...this.stamp(parentToolUseId), turnScope: this.deps.turnScope() }
|
||||
if (provisional) {
|
||||
this.remember(parentToolUseId, identity, body, options)
|
||||
} else {
|
||||
@@ -160,7 +159,7 @@ export class ClaudeProvisionalRowCorrections {
|
||||
this.outstanding.delete(agentJournalItemKey(identity))
|
||||
}
|
||||
|
||||
private stamp(parentToolUseId: string): StructuredAgentSessionAppendOptions {
|
||||
private stamp(parentToolUseId: string): ReturnType<typeof agentJournalLinkageFields> {
|
||||
return agentJournalLinkageFields(this.deps.settledLinkageFor(parentToolUseId).linkage)
|
||||
}
|
||||
|
||||
@@ -171,14 +170,16 @@ export class ClaudeProvisionalRowCorrections {
|
||||
if (sameLinkage(options, correction.stamped)) {
|
||||
return 'unchanged'
|
||||
}
|
||||
return this.deps.rewrite(correction.identity, correction.body, options) ? 'wrote' : 'refused'
|
||||
// A re-stamp revises the row, so its scope stays the one it was created with.
|
||||
const restamped = { ...options, turnScope: correction.stamped.turnScope }
|
||||
return this.deps.rewrite(correction.identity, correction.body, restamped) ? 'wrote' : 'refused'
|
||||
}
|
||||
|
||||
private remember(
|
||||
ref: string,
|
||||
identity: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody,
|
||||
stamped: StructuredAgentSessionAppendOptions
|
||||
stamped: StructuredAgentSessionItemAppendOptions
|
||||
): void {
|
||||
if (this.givenUp.has(ref)) {
|
||||
return
|
||||
@@ -233,8 +234,8 @@ export class ClaudeProvisionalRowCorrections {
|
||||
}
|
||||
|
||||
function sameLinkage(
|
||||
left: StructuredAgentSessionAppendOptions,
|
||||
right: StructuredAgentSessionAppendOptions
|
||||
left: AgentJournalProducerLinkage,
|
||||
right: AgentJournalProducerLinkage
|
||||
): boolean {
|
||||
return (
|
||||
left.agentId === right.agentId &&
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Journaling ONE Claude `result` frame: the end of the root turn it settles, and the diagnostic
|
||||
// row a failed or unrecognised result leaves.
|
||||
//
|
||||
// Split out of the translator when that file reached its line budget; the translator still owns
|
||||
// the open turn and every collaborator this writes through.
|
||||
|
||||
import type { ClaudeContextFacts } from './claude-context-facts'
|
||||
import { claudeCommandResultEnd } from './claude-command-turn'
|
||||
import type { ClaudeMessageJournalContext } from './claude-message-journaling'
|
||||
import type { ClaudeJournalPrompts } from './claude-structured-journal-prompts'
|
||||
import {
|
||||
claudeProviderFrameKind,
|
||||
claudeResultFailure,
|
||||
isSettledClaudeResultKind
|
||||
} from './claude-structured-provider-fallback'
|
||||
import { claudeTurnEndForResult } from './claude-turn-lifecycle-item'
|
||||
import { claudeFrameParentRef, isRootClaudeFrame } from './claude-turn-opening'
|
||||
|
||||
export type ClaudeResultJournalContext = Pick<
|
||||
ClaudeMessageJournalContext,
|
||||
| 'sink'
|
||||
| 'streamedBlocks'
|
||||
| 'streamedText'
|
||||
| 'subagents'
|
||||
| 'providerFallback'
|
||||
| 'corrections'
|
||||
| 'turn'
|
||||
> & {
|
||||
prompts: ClaudeJournalPrompts
|
||||
context: ClaudeContextFacts
|
||||
}
|
||||
|
||||
export function journalClaudeResult(
|
||||
{
|
||||
sink,
|
||||
streamedBlocks,
|
||||
streamedText,
|
||||
subagents,
|
||||
providerFallback,
|
||||
corrections,
|
||||
turn,
|
||||
prompts,
|
||||
context
|
||||
}: ClaudeResultJournalContext,
|
||||
message: Record<string, unknown>,
|
||||
observedAt: number
|
||||
): void {
|
||||
// Every turn this translator opens is root by construction, so a nested
|
||||
// result settles the child that produced it and never the turn. The
|
||||
// diagnostic below still runs: a child's failure is reportable even when
|
||||
// it ends no turn.
|
||||
const settlesTurn = isRootClaudeFrame(message)
|
||||
const commandEnd = settlesTurn ? claudeCommandResultEnd(turn, sink, message, observedAt) : null
|
||||
if (commandEnd === 'another-input') {
|
||||
return
|
||||
}
|
||||
// Read before the settle below closes it: the result reports that turn's end.
|
||||
const endedTurnScope = turn.turnScope
|
||||
if (settlesTurn) {
|
||||
prompts.retryPendingCancellations()
|
||||
turn.suppressReopenOnFailure(message.is_error === true)
|
||||
// The turn is over however it ended, so a foreground child still
|
||||
// reported as working will never be settled by an event.
|
||||
subagents.settleTurn(turn.groupKey)
|
||||
context.settle(message, commandEnd ?? claudeTurnEndForResult(message, observedAt))
|
||||
// The turn is over. A block still awaiting its final keeps the text the
|
||||
// flush above journaled, but its live state goes: an interrupted turn
|
||||
// would otherwise retain that text for the life of the session.
|
||||
streamedBlocks.clear()
|
||||
streamedText.settle()
|
||||
}
|
||||
const kind = claudeProviderFrameKind(message)
|
||||
const failure = claudeResultFailure(message)
|
||||
if (failure || !isSettledClaudeResultKind(kind)) {
|
||||
providerFallback.append(
|
||||
kind,
|
||||
message,
|
||||
failure?.text,
|
||||
undefined,
|
||||
undefined,
|
||||
// A result that settles no turn is a CHILD's result: this
|
||||
// translator only ever opens root turns.
|
||||
settlesTurn
|
||||
? () => ({ turnScope: endedTurnScope })
|
||||
: corrections.stampFor(claudeFrameParentRef(message))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type {
|
||||
AgentSessionCommandAdmission,
|
||||
StructuredAgentSessionCommandRun
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import { dispatchClaudeTurn } from './claude-structured-dispatch'
|
||||
import type { ClaudeSession } from './claude-structured-session-state'
|
||||
|
||||
/** Sent like any message, so the slash-command waiter settles it on its result. The translator
|
||||
* makes the command's turn the open one before the send, and that same result ends it. */
|
||||
export async function dispatchClaudeCommand(
|
||||
session: ClaudeSession,
|
||||
command: StructuredAgentSessionCommandRun
|
||||
): Promise<AgentSessionCommandAdmission> {
|
||||
const sentUuid = randomUUID()
|
||||
session.translator?.beginCommand({
|
||||
...command,
|
||||
providerSessionId: session.providerSessionId,
|
||||
sentUuid
|
||||
})
|
||||
try {
|
||||
const admission = await dispatchClaudeTurn(session, {
|
||||
clientMessageId: command.clientMessageId,
|
||||
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: '/compact' }] },
|
||||
...(command.running.requestedAt === undefined
|
||||
? {}
|
||||
: { requestedAt: command.running.requestedAt }),
|
||||
sentUuid
|
||||
})
|
||||
if (admission.state === 'rejected') {
|
||||
session.translator?.forgetCommand(command.turnId)
|
||||
}
|
||||
return admission
|
||||
} catch (error) {
|
||||
session.translator?.forgetCommand(command.turnId)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { StructuredSessionCompaction } from '../native-chat/agent-session-wire/structured-session-compaction'
|
||||
import { claudeUnwrittenUserMessageError } from './claude-agent-sdk-user-message-queue'
|
||||
import { compactClaudeSession, isClaudeCompactionContent } from './claude-structured-compaction'
|
||||
import { sessionFor } from './claude-structured-dispatch-test-support'
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('Claude compaction transcript content', () => {
|
||||
it('keeps generated summaries and command echoes out of the transcript only during explicit compaction', async () => {
|
||||
const tracker = new StructuredSessionCompaction()
|
||||
const event = {
|
||||
type: 'message' as const,
|
||||
sessionId: 'orca-session',
|
||||
message: {
|
||||
type: 'user',
|
||||
session_id: 'provider',
|
||||
uuid: 'summary',
|
||||
message: { role: 'user', content: 'generated compaction summary' }
|
||||
}
|
||||
}
|
||||
expect(isClaudeCompactionContent(tracker, event)).toBe(false)
|
||||
const completion = tracker.run('orca-session', 'provider', async () => undefined)
|
||||
expect(isClaudeCompactionContent(tracker, event)).toBe(true)
|
||||
expect(isClaudeCompactionContent(tracker, { ...event, sessionId: 'other' })).toBe(false)
|
||||
expect(isClaudeCompactionContent(tracker, { ...event, message: { type: 'result' } })).toBe(
|
||||
false
|
||||
)
|
||||
tracker.ended('orca-session')
|
||||
await completion
|
||||
expect(isClaudeCompactionContent(tracker, event)).toBe(false)
|
||||
})
|
||||
|
||||
it('fails a provably unwritten command without waiting for the completion deadline', async () => {
|
||||
vi.useFakeTimers()
|
||||
const session = sessionFor(
|
||||
vi.fn().mockRejectedValue(claudeUnwrittenUserMessageError(new Error('input closed')))
|
||||
)
|
||||
const pending = compactClaudeSession(session, new StructuredSessionCompaction(60_000), {
|
||||
sessionId: 'orca-session',
|
||||
fence: 1,
|
||||
turnId: 'compact-1'
|
||||
})
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
|
||||
await expect(pending).resolves.toEqual({ outcome: 'failed' })
|
||||
})
|
||||
|
||||
it('keeps waiting when the command write outcome is ambiguous', async () => {
|
||||
vi.useFakeTimers()
|
||||
const session = sessionFor(vi.fn().mockRejectedValue(new Error('input pump stopped')))
|
||||
const pending = compactClaudeSession(session, new StructuredSessionCompaction(10), {
|
||||
sessionId: 'orca-session',
|
||||
fence: 1,
|
||||
turnId: 'compact-1'
|
||||
})
|
||||
const rejection = expect(pending).rejects.toThrow('Compaction completion is unconfirmed.')
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
|
||||
await rejection
|
||||
})
|
||||
})
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { ClaudeSession, ClaudeStructuredSessionEvent } from './claude-structured-session-state'
|
||||
import type {
|
||||
StructuredSessionCompaction,
|
||||
StructuredSessionCompactionResult
|
||||
} from '../native-chat/agent-session-wire/structured-session-compaction'
|
||||
import { dispatchClaudeTurn } from './claude-structured-dispatch'
|
||||
import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
/** Compaction needs no ack deadline of its own: `compactions.run` keeps its own
|
||||
* 180s completion window and settles on Claude's terminal `result` frame, so
|
||||
* the dispatch here only has to report a refusal to send. */
|
||||
export function compactClaudeSession(
|
||||
session: ClaudeSession,
|
||||
compactions: StructuredSessionCompaction,
|
||||
input: Parameters<NonNullable<StructuredAgentSessionAdapter['compact']>>[0]
|
||||
): Promise<StructuredSessionCompactionResult> {
|
||||
return compactions.run(
|
||||
input.sessionId,
|
||||
session.providerSessionId,
|
||||
async () => {
|
||||
const result = await dispatchClaudeTurn(session, {
|
||||
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: '/compact' }] }
|
||||
})
|
||||
if (result.state === 'rejected') {
|
||||
return { outcome: 'failed' as const }
|
||||
}
|
||||
return undefined
|
||||
},
|
||||
input.onLateResult,
|
||||
input.turnId
|
||||
)
|
||||
}
|
||||
|
||||
export function observeClaudeCompaction(
|
||||
compactions: StructuredSessionCompaction,
|
||||
event: ClaudeStructuredSessionEvent,
|
||||
translator: ClaudeSession['translator'] | undefined
|
||||
): void {
|
||||
if (!isClaudeCompactionContent(compactions, event)) {
|
||||
translator?.handle(event)
|
||||
}
|
||||
if (event.type === 'message') {
|
||||
compactions.claude(event.sessionId, event.message)
|
||||
}
|
||||
if (event.type === 'ended') {
|
||||
compactions.ended(event.sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
export function isClaudeCompactionContent(
|
||||
compactions: StructuredSessionCompaction,
|
||||
event: ClaudeStructuredSessionEvent
|
||||
): boolean {
|
||||
return (
|
||||
event.type === 'message' &&
|
||||
compactions.hasPending(event.sessionId) &&
|
||||
['user', 'assistant', 'stream_event'].includes(String(event.message.type))
|
||||
)
|
||||
}
|
||||
@@ -249,6 +249,10 @@ describe('answerClaudePrompt', () => {
|
||||
resolve: resolvePrompt
|
||||
},
|
||||
currentTurnId: null,
|
||||
commandTurnId: null,
|
||||
beginCommand: vi.fn(),
|
||||
forgetCommand: vi.fn(),
|
||||
commandInterruptRequested: vi.fn(),
|
||||
flush: vi.fn(),
|
||||
contextActivity: 0,
|
||||
markContextActivity: vi.fn(),
|
||||
|
||||
@@ -79,7 +79,13 @@ function claudeWriteFailureRejection(error: unknown): AgentJournalDispatchReject
|
||||
|
||||
export async function dispatchClaudeTurn(
|
||||
session: ClaudeSession,
|
||||
input: { clientMessageId?: string; body: AgentJournalMessageItem; requestedAt?: number },
|
||||
input: {
|
||||
clientMessageId?: string
|
||||
body: AgentJournalMessageItem
|
||||
requestedAt?: number
|
||||
/** The frame's uuid, for a caller that correlates the provider's answer to it. */
|
||||
sentUuid?: string
|
||||
},
|
||||
beforeDispatch?: () => Promise<void>
|
||||
): Promise<AgentSessionDispatchOutcome> {
|
||||
let content: unknown[]
|
||||
@@ -98,7 +104,7 @@ export async function dispatchClaudeTurn(
|
||||
// Read the sent content, not the journal blocks: only the mapped trailing prompt decides
|
||||
// whether Claude runs a command, so the two cannot disagree about which frame settles this.
|
||||
const acceptsResult = claudeDispatchInvokesSlashCommand(content)
|
||||
const sentUuid = randomUUID()
|
||||
const sentUuid = input.sentUuid ?? randomUUID()
|
||||
const arm = () => {
|
||||
++session.dispatchSequence
|
||||
// A context report asked for before this send may land after it and misstate the context.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type {
|
||||
AgentJournalApprovalItem,
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalQuestionItem
|
||||
AgentJournalQuestionItem,
|
||||
AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import { cancelledJournalPromptBody } from '../native-chat/agent-session-journal/journal-prompt-body-bounds'
|
||||
@@ -22,6 +23,7 @@ const ADMITTED = { accepted: true } as const
|
||||
type ClaudeJournalPrompt = {
|
||||
identity: AgentJournalItemIdentity
|
||||
body: AgentJournalApprovalItem | AgentJournalQuestionItem
|
||||
turnScope: AgentJournalTurnScope
|
||||
}
|
||||
|
||||
type ClaudeJournalPromptEntry = {
|
||||
@@ -54,6 +56,8 @@ export class ClaudeJournalPrompts {
|
||||
constructor(
|
||||
private readonly deps: {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
/** The turn that raised the prompt: the open one, else the conversation. */
|
||||
turnScope: () => AgentJournalTurnScope
|
||||
bindPromptItemId?: (journalItemId: string, promptKey: string) => void
|
||||
questionItems?: (input: {
|
||||
sessionId: string
|
||||
@@ -75,13 +79,14 @@ export class ClaudeJournalPrompts {
|
||||
*/
|
||||
handle(event: Extract<ClaudeStructuredSessionEvent, { type: 'prompt' }>): void {
|
||||
const items: ClaudeJournalPrompt[] = []
|
||||
const turnScope = this.deps.turnScope()
|
||||
if (event.prompt.kind === 'question') {
|
||||
for (const question of (this.deps.questionItems ?? claudeQuestionItems)({
|
||||
sessionId: event.sessionId,
|
||||
prompt: event.prompt
|
||||
})) {
|
||||
items.push(question)
|
||||
this.deps.sink.appendItem(question.identity, question.body)
|
||||
items.push({ ...question, turnScope })
|
||||
this.deps.sink.appendItem(question.identity, question.body, { turnScope })
|
||||
this.deps.bindPromptItemId?.(agentJournalItemKey(question.identity), event.prompt.promptKey)
|
||||
}
|
||||
} else {
|
||||
@@ -90,8 +95,8 @@ export class ClaudeJournalPrompts {
|
||||
promptKey: event.prompt.promptKey
|
||||
})
|
||||
const body = claudeApprovalItem(event.prompt)
|
||||
items.push({ identity, body })
|
||||
this.deps.sink.appendItem(identity, body)
|
||||
items.push({ identity, body, turnScope })
|
||||
this.deps.sink.appendItem(identity, body, { turnScope })
|
||||
this.deps.bindPromptItemId?.(agentJournalItemKey(identity), event.prompt.promptKey)
|
||||
}
|
||||
this.deletePrompt(event.prompt.promptKey)
|
||||
@@ -104,10 +109,11 @@ export class ClaudeJournalPrompts {
|
||||
if (items.length === 0) {
|
||||
return ADMITTED
|
||||
}
|
||||
const mutations = items.map(({ identity, body }) => ({
|
||||
const mutations = items.map(({ identity, body, turnScope }) => ({
|
||||
kind: 'item' as const,
|
||||
identity,
|
||||
body: cancelledPromptBody(body)
|
||||
body: cancelledPromptBody(body),
|
||||
turnScope
|
||||
}))
|
||||
let admission: StructuredAgentSessionSinkAdmission
|
||||
if (this.deps.sink.tryAppendLifecycleBatch) {
|
||||
@@ -129,9 +135,10 @@ export class ClaudeJournalPrompts {
|
||||
return ADMITTED
|
||||
}
|
||||
const body = cancelledPromptBody(item.body)
|
||||
const options = { lifecycle: true, turnScope: item.turnScope }
|
||||
admission = this.deps.sink.tryAppendItem
|
||||
? this.deps.sink.tryAppendItem(item.identity, body, { lifecycle: true })
|
||||
: (this.deps.sink.appendItem(item.identity, body, { lifecycle: true }), ADMITTED)
|
||||
? this.deps.sink.tryAppendItem(item.identity, body, options)
|
||||
: (this.deps.sink.appendItem(item.identity, body, options), ADMITTED)
|
||||
} else {
|
||||
return { accepted: false, reason: 'failed' }
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type {
|
||||
@@ -201,7 +202,8 @@ describe('claude journal translation — background task rows', () => {
|
||||
deferred.bind(target)
|
||||
deferred.sink.appendItem(
|
||||
{ provider: 'orca', clientMessageId: 'blocked-prefill' },
|
||||
{ kind: 'message', role: 'system', blocks: [{ type: 'text', text: 'prefill' }] }
|
||||
{ kind: 'message', role: 'system', blocks: [{ type: 'text', text: 'prefill' }] },
|
||||
{ turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
await appendEntered.promise
|
||||
const notification = systemFrame({
|
||||
|
||||
@@ -529,7 +529,9 @@ describe('claude journal translation — which agent produced a row', () => {
|
||||
(entry) => orcaClientMessageId(entry.identity) === 'claude-tool:claude-session:toolu_bash'
|
||||
)
|
||||
expect(row?.body).toMatchObject({ kind: 'tool-call', state: 'completed' })
|
||||
expect(row?.options).toEqual({})
|
||||
expect(row?.options).toEqual({
|
||||
turnScope: { kind: 'turn', turnItemId: expect.any(String) }
|
||||
})
|
||||
})
|
||||
|
||||
/** One streamed text block, as the SDK sends it: a message start, then deltas.
|
||||
|
||||
@@ -161,7 +161,7 @@ describe('Claude structured turn timing', () => {
|
||||
state: 'running',
|
||||
startedAt: 1_000,
|
||||
userItemId: USER_1_KEY,
|
||||
options: { observedAt: 1_000 }
|
||||
options: { observedAt: 1_000, turnScope: { kind: 'thread' } }
|
||||
}
|
||||
])
|
||||
})
|
||||
@@ -194,7 +194,7 @@ describe('Claude structured turn timing', () => {
|
||||
startedAt: 1_000,
|
||||
completedAt: 4_500,
|
||||
userItemId: USER_1_KEY,
|
||||
options: {}
|
||||
options: { turnScope: { kind: 'thread' } }
|
||||
})
|
||||
expect(state.items.at(-1)?.identity).toEqual(state.items[0]?.identity)
|
||||
})
|
||||
|
||||
@@ -9,9 +9,7 @@ import type { ClaudePromptRegistry } from './claude-structured-prompt-replies'
|
||||
import { claudeProviderFrameActivity } from '../native-chat/agent-session-wire/provider-frame-activity'
|
||||
import {
|
||||
claudeProviderFrameKind,
|
||||
claudeResultFailure,
|
||||
createClaudeProviderFrameFallback,
|
||||
isSettledClaudeResultKind
|
||||
createClaudeProviderFrameFallback
|
||||
} from './claude-structured-provider-fallback'
|
||||
import { taskFrameSentence } from './claude-background-task-frames'
|
||||
import { ClaudeBackgroundTaskRows } from './claude-background-task-rows'
|
||||
@@ -26,13 +24,14 @@ import {
|
||||
claudeStreamTurnSource,
|
||||
isRootClaudeFrame
|
||||
} from './claude-turn-opening'
|
||||
import { claudeTurnEndForResult } from './claude-turn-lifecycle-item'
|
||||
import { ClaudeOpenTurn } from './claude-open-turn'
|
||||
import { claudeCommandCurrentTurn, observeClaudeCommandFrame } from './claude-command-turn'
|
||||
import { ClaudeContextFacts } from './claude-context-facts'
|
||||
import { claudeSessionStateEndsTurn } from './claude-session-state-turn-over'
|
||||
import { ClaudeJournalPrompts } from './claude-structured-journal-prompts'
|
||||
import { claudeChildToolQueries } from './claude-child-tool-queries'
|
||||
import { journalClaudeMessage, type ClaudeMessageJournalContext } from './claude-message-journaling'
|
||||
import { journalClaudeResult, type ClaudeResultJournalContext } from './claude-result-journaling'
|
||||
|
||||
export type { ClaudeJournalTranslator } from './claude-journal-translator-contract'
|
||||
|
||||
@@ -65,7 +64,9 @@ export function createClaudeJournalTranslator(
|
||||
deps: ClaudeJournalTranslatorDeps
|
||||
): ClaudeJournalTranslator {
|
||||
const tools = new Map<string, ClaudeToolUse>()
|
||||
const prompts = new ClaudeJournalPrompts(deps)
|
||||
// Every row joins the root turn open when it is written, whoever produced it.
|
||||
const turnScope = () => turn.turnScope
|
||||
const prompts = new ClaudeJournalPrompts({ ...deps, turnScope })
|
||||
const streamedBlocks = createClaudeStreamedBlockRegistry()
|
||||
const turn = new ClaudeOpenTurn({
|
||||
sink: deps.sink,
|
||||
@@ -73,14 +74,13 @@ export function createClaudeJournalTranslator(
|
||||
onOpen: () => context.markActivity()
|
||||
})
|
||||
const context = new ClaudeContextFacts(turn, deps.sink)
|
||||
const providerFallback = createClaudeProviderFrameFallback(
|
||||
deps.sink,
|
||||
deps.fallbackIdPrefix ?? 'acquisition'
|
||||
)
|
||||
const fallbackId = deps.fallbackIdPrefix ?? 'acquisition'
|
||||
const providerFallback = createClaudeProviderFrameFallback(deps.sink, fallbackId, turnScope)
|
||||
const toolOrigins = new ClaudeToolOriginRegistry()
|
||||
const subagents = new ClaudeSubagentRoster({
|
||||
sink: deps.sink,
|
||||
currentGroupKey: () => turn.groupKey,
|
||||
currentTurnScope: turnScope,
|
||||
isForwardedParentTool: (toolUseId) => toolOrigins.has(toolUseId),
|
||||
childOwnerRefOf: (toolUseId) => toolOrigins.childOwnerRef(toolUseId),
|
||||
// A settled group can receive no further announcement, so a correction
|
||||
@@ -90,6 +90,7 @@ export function createClaudeJournalTranslator(
|
||||
const childQueries = claudeChildToolQueries({ tools, toolOrigins, linkage: subagents.linkage })
|
||||
const corrections = new ClaudeProvisionalRowCorrections({
|
||||
...subagents.linkage,
|
||||
turnScope,
|
||||
rewrite: (identity, body, options) => {
|
||||
// The admission-returning path, so a correction the sink refuses under
|
||||
// backpressure stays owed instead of vanishing. Sinks without it accept
|
||||
@@ -110,6 +111,7 @@ export function createClaudeJournalTranslator(
|
||||
// turn, or the session shows the row while reading idle.
|
||||
openOutputTurn: (frame, observedAt) =>
|
||||
turn.ensureOpen(frame, claudeStreamTurnSource(frame), observedAt),
|
||||
turnScope,
|
||||
...(deps.onBackgroundTaskJournalFailure
|
||||
? { onPersistenceFailure: deps.onBackgroundTaskJournalFailure }
|
||||
: {})
|
||||
@@ -119,7 +121,8 @@ export function createClaudeJournalTranslator(
|
||||
...(deps.schedule ? { schedule: deps.schedule } : {}),
|
||||
producer: subagents.linkage,
|
||||
persist: (identity, text, options) => {
|
||||
deps.sink.appendItem(identity, claudeStreamingMessageBody(text), options)
|
||||
const body = claudeStreamingMessageBody(text)
|
||||
deps.sink.appendItem(identity, body, { ...options, turnScope: turnScope() })
|
||||
deps.sink.publish()
|
||||
}
|
||||
})
|
||||
@@ -161,6 +164,8 @@ export function createClaudeJournalTranslator(
|
||||
turn
|
||||
}
|
||||
|
||||
const resultContext: ClaudeResultJournalContext = { ...messageContext, prompts, context }
|
||||
|
||||
const handleMessage = (
|
||||
message: Record<string, unknown>,
|
||||
startsTurn: boolean,
|
||||
@@ -200,6 +205,9 @@ export function createClaudeJournalTranslator(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (event.type === 'message' && observeClaudeCommandFrame(turn.command, event.message)) {
|
||||
return
|
||||
}
|
||||
if (event.type === 'message' && handleStream(event.message, event.observedAt ?? Date.now())) {
|
||||
return
|
||||
}
|
||||
@@ -218,41 +226,7 @@ export function createClaudeJournalTranslator(
|
||||
prompts.retryPendingCancellations()
|
||||
prompts.cancel(event.promptKey)
|
||||
} else if (event.type === 'message' && event.message.type === 'result') {
|
||||
// Every turn this translator opens is root by construction, so a nested
|
||||
// result settles the child that produced it and never the turn. The
|
||||
// diagnostic below still runs: a child's failure is reportable even when
|
||||
// it ends no turn.
|
||||
const settlesTurn = isRootClaudeFrame(event.message)
|
||||
if (settlesTurn) {
|
||||
prompts.retryPendingCancellations()
|
||||
turn.suppressReopenOnFailure(event.message.is_error === true)
|
||||
// The turn is over however it ended, so a foreground child still
|
||||
// reported as working will never be settled by an event.
|
||||
subagents.settleTurn(turn.groupKey)
|
||||
context.settle(
|
||||
event.message,
|
||||
claudeTurnEndForResult(event.message, event.observedAt ?? Date.now())
|
||||
)
|
||||
// The turn is over. A block still awaiting its final keeps the text the
|
||||
// flush above journaled, but its live state goes: an interrupted turn
|
||||
// would otherwise retain that text for the life of the session.
|
||||
streamedBlocks.clear()
|
||||
streamedText.settle()
|
||||
}
|
||||
const kind = claudeProviderFrameKind(event.message)
|
||||
const failure = claudeResultFailure(event.message)
|
||||
if (failure || !isSettledClaudeResultKind(kind)) {
|
||||
providerFallback.append(
|
||||
kind,
|
||||
event.message,
|
||||
failure?.text,
|
||||
undefined,
|
||||
undefined,
|
||||
// A result that settles no turn is a CHILD's result: this
|
||||
// translator only ever opens root turns.
|
||||
settlesTurn ? undefined : corrections.stampFor(claudeFrameParentRef(event.message))
|
||||
)
|
||||
}
|
||||
journalClaudeResult(resultContext, event.message, event.observedAt ?? Date.now())
|
||||
} else if (event.type === 'message') {
|
||||
const backgroundTaskCovered = backgroundTasks.observe(
|
||||
event.message,
|
||||
@@ -296,6 +270,12 @@ export function createClaudeJournalTranslator(
|
||||
get currentTurnId() {
|
||||
return turn.id
|
||||
},
|
||||
get commandTurnId() {
|
||||
return turn.command ? turn.id : null
|
||||
},
|
||||
beginCommand: (start) => turn.beginCommand(claudeCommandCurrentTurn(start)),
|
||||
forgetCommand: (turnId) => turn.forgetCommand(turnId),
|
||||
commandInterruptRequested: (turnId) => turn.commandInterruptRequested(turnId),
|
||||
get openTurnInLiveProviderCycle() {
|
||||
return turn.openedInLiveProviderCycle
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types'
|
||||
@@ -341,7 +342,10 @@ describe('Claude live prompt ownership', () => {
|
||||
})
|
||||
|
||||
it('drops resolved prompt bodies instead of retaining them for the session lifetime', () => {
|
||||
const prompts = new ClaudeJournalPrompts({ sink: lifecycleRecorder().sink })
|
||||
const prompts = new ClaudeJournalPrompts({
|
||||
sink: lifecycleRecorder().sink,
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
|
||||
for (let index = 0; index < 128; index += 1) {
|
||||
const promptKey = `resolved-${index}`
|
||||
@@ -673,7 +677,8 @@ describe('Claude live prompt ownership', () => {
|
||||
}
|
||||
]
|
||||
: []
|
||||
}
|
||||
},
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
const prompt: ClaudePendingPrompt = {
|
||||
requestId: 'grouped-request',
|
||||
@@ -714,7 +719,8 @@ describe('Claude live prompt ownership', () => {
|
||||
lifecycleAttempts += 1
|
||||
return backpressured ? { accepted: false, reason: 'backpressure' } : { accepted: true }
|
||||
}
|
||||
}
|
||||
},
|
||||
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
const registerCancellation = (index: number): void => {
|
||||
const promptKey = `permission-${index}`
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
AgentSessionPromptUnavailableError,
|
||||
type StructuredAgentSessionAdapter
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import type { StructuredSessionCompaction } from '../native-chat/agent-session-wire/structured-session-compaction'
|
||||
import { CLAUDE_DEFAULT_REQUEST_TIMEOUT_MS } from './claude-agent-sdk-control-requests'
|
||||
import {
|
||||
answerClaudePrompt,
|
||||
@@ -116,12 +115,11 @@ function cancelClaudeConversation(
|
||||
export async function cancelClaudeStructuredTurn(input: {
|
||||
request: CancelInput
|
||||
sessions: Map<string, ClaudeSession>
|
||||
compactions: StructuredSessionCompaction
|
||||
timeoutMs?: number
|
||||
admitPromptCancellation: (session: ClaudeSession, promptKey: string) => boolean
|
||||
onDispatchSettledLate?: ClaudeLateDispatchSettlement
|
||||
}): Promise<{ cancelled: boolean }> {
|
||||
const { request, sessions, compactions, timeoutMs } = input
|
||||
const { request, sessions, timeoutMs } = input
|
||||
const session = requireSession(sessions, request.sessionId)
|
||||
const acquisitionGeneration = session.acquisitionGeneration
|
||||
const prompt = request.prompt
|
||||
@@ -172,7 +170,8 @@ export async function cancelClaudeStructuredTurn(input: {
|
||||
const dispatchAdmissionAllowsCancellation = (): boolean =>
|
||||
dispatchAdmissionIsCurrent() ||
|
||||
(Boolean(prompt) && supportsClaudeQueuedInterruptCancellation(session))
|
||||
const compactionOwnsTurn = (): boolean => compactions.ownsTurn(request.sessionId, requestedTurnId)
|
||||
const compactionOwnsTurn = (): boolean =>
|
||||
session.translator !== null && session.translator.commandTurnId === requestedTurnId
|
||||
const currentDispatchHasRetiredWaiter = (): boolean =>
|
||||
session.retiredDispatchWaiters.some(
|
||||
(waiter) => waiter.dispatchSequence === session.dispatchSequence
|
||||
@@ -204,7 +203,14 @@ export async function cancelClaudeStructuredTurn(input: {
|
||||
const result = await cancelClaudeTurn(
|
||||
session,
|
||||
timeoutMs,
|
||||
isCurrent,
|
||||
() => {
|
||||
const current = isCurrent()
|
||||
// Read with the result that ends it: a stopped command reports no compaction.
|
||||
if (current && compactionOwnsTurn()) {
|
||||
session.translator?.commandInterruptRequested(requestedTurnId)
|
||||
}
|
||||
return current
|
||||
},
|
||||
input.onDispatchSettledLate
|
||||
)
|
||||
if (result.cancelled && claim && cancellationObserved) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session-journal-types'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import {
|
||||
boundInlineText,
|
||||
@@ -15,7 +16,7 @@ import {
|
||||
type ClaudeMessageEnvelope
|
||||
} from './claude-structured-item-translation'
|
||||
import { claudeResultOutcome } from './claude-result-outcome'
|
||||
import { rootClaudeRowStamp, type ClaudeRowStamp } from './claude-provisional-row-corrections'
|
||||
import type { ClaudeRowStamp } from './claude-provisional-row-corrections'
|
||||
import {
|
||||
CLAUDE_API_RETRY_FRAME_KIND,
|
||||
claudeApiRetryRowBody,
|
||||
@@ -109,7 +110,9 @@ export function isModeledClaudeContent(value: unknown): boolean {
|
||||
|
||||
export function createClaudeProviderFrameFallback(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
acquisitionId: string
|
||||
acquisitionId: string,
|
||||
/** The frame's turn — the open one once `beforeAppend` ran — or the conversation. */
|
||||
turnScope: () => AgentJournalTurnScope
|
||||
): {
|
||||
/** `displayText` leads the row when Claude knows the sentence the frame itself does not name. */
|
||||
append: (
|
||||
@@ -139,7 +142,7 @@ export function createClaudeProviderFrameFallback(
|
||||
clientMessageId: `provider-retry:claude:${acquisitionId}:${retryRun(retrying)}`
|
||||
} as const
|
||||
const body = claudeApiRetryRowBody(retrying)
|
||||
sink.appendItem(identity, body, (stamp ?? rootClaudeRowStamp)(identity, body))
|
||||
sink.appendItem(identity, body, stamp?.(identity, body) ?? { turnScope: turnScope() })
|
||||
sink.publish()
|
||||
return true
|
||||
}
|
||||
@@ -162,7 +165,7 @@ export function createClaudeProviderFrameFallback(
|
||||
clientMessageId: `provider-frame:claude:${acquisitionId}:${sequence}`
|
||||
} as const
|
||||
const body = bounded ? { ...translated.body, text: bounded } : translated.body
|
||||
sink.appendItem(identity, body, (stamp ?? rootClaudeRowStamp)(identity, body))
|
||||
sink.appendItem(identity, body, stamp?.(identity, body) ?? { turnScope: turnScope() })
|
||||
sink.publish()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { SubmissionRejectionFact } from '../../shared/agent-session-failure'
|
||||
import { compactClaudeSession, observeClaudeCompaction } from './claude-structured-compaction'
|
||||
import { dispatchClaudeCommand } from './claude-structured-command-dispatch'
|
||||
import type {
|
||||
AgentSessionAcquisition,
|
||||
StructuredAgentSessionAcquireInput,
|
||||
@@ -7,7 +7,6 @@ import type {
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import { stopClaudeBackgroundTasks } from './claude-structured-control-actions'
|
||||
import { dispatchClaudeTurn } from './claude-structured-dispatch'
|
||||
import { StructuredSessionCompaction } from '../native-chat/agent-session-wire/structured-session-compaction'
|
||||
import { releaseClaudeAcquisition } from './claude-structured-acquisition-release'
|
||||
import { acquireClaudeSession } from './claude-structured-session-acquisition'
|
||||
import { supportsClaudeStructuredLocation } from './claude-structured-location-support'
|
||||
@@ -55,7 +54,6 @@ function backgroundTaskState(session: ClaudeSession): AgentSessionBackgroundTask
|
||||
}
|
||||
|
||||
export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAdapter {
|
||||
private readonly compactions = new StructuredSessionCompaction()
|
||||
private readonly sessions = new Map<string, ClaudeSession>()
|
||||
private readonly acquisitions = new ClaudeAcquisitionRegistry()
|
||||
private readonly exits = new Map<string, ClaudeSessionExit>()
|
||||
@@ -156,7 +154,7 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda
|
||||
if (event.type === 'message' && session?.commands.observe(event.message)) {
|
||||
session.events?.publish()
|
||||
}
|
||||
observeClaudeCompaction(this.compactions, event, session?.translator)
|
||||
session?.translator?.handle(event)
|
||||
this.deps.onEvent?.(event)
|
||||
if (backgroundTasksChanged) {
|
||||
this.deps.onBackgroundTasksChanged?.(
|
||||
@@ -193,13 +191,12 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda
|
||||
dispatchClaudeTurn(this.session(input.sessionId), input, input.beforeDispatch)
|
||||
|
||||
compact: NonNullable<StructuredAgentSessionAdapter['compact']> = (input) =>
|
||||
compactClaudeSession(this.session(input.sessionId), this.compactions, input)
|
||||
dispatchClaudeCommand(this.session(input.sessionId), input.command)
|
||||
|
||||
cancelTurn: StructuredAgentSessionAdapter['cancelTurn'] = (request) =>
|
||||
cancelClaudeStructuredTurn({
|
||||
request,
|
||||
sessions: this.sessions,
|
||||
compactions: this.compactions,
|
||||
admitPromptCancellation: (session, promptKey) =>
|
||||
admitClaudePromptCancellation(session, promptKey),
|
||||
onDispatchSettledLate: (settlement) =>
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
AgentSessionPreSpawnError
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import type { ClaudeStreamJsonConnection } from './claude-stream-json-connection'
|
||||
import type { ClaudeJournalTranslator } from './claude-structured-journal-translation'
|
||||
import type { ClaudeJournalTranslator } from './claude-journal-translator-contract'
|
||||
import type { ClaudePromptRegistry } from './claude-structured-prompt-replies'
|
||||
import type { AgentSessionBackgroundTaskState } from '../../shared/agent-session-wire'
|
||||
import { closeProcessRegistry } from '../../shared/child-process/close-process-registry'
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
} from './claude-context-usage'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import type { ClaudeStreamJsonConnection } from './claude-stream-json-connection'
|
||||
import type { ClaudeJournalTranslator } from './claude-structured-journal-translation'
|
||||
import type { ClaudeJournalTranslator } from './claude-journal-translator-contract'
|
||||
import type { ClaudeInitProof } from './claude-structured-session-startup'
|
||||
import type {
|
||||
ClaudeAcquisitionAttempt,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { AgentSessionAcquisition } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import { claudeProviderHandleLink } from './claude-structured-owner-identity'
|
||||
import type { ClaudePromptRegistry } from './claude-structured-prompt-replies'
|
||||
import type { ClaudeJournalTranslator } from './claude-structured-journal-translation'
|
||||
import type { ClaudeJournalTranslator } from './claude-journal-translator-contract'
|
||||
import type { ClaudeSession } from './claude-structured-session-state'
|
||||
import { ClaudeBackgroundTaskTracker } from './claude-background-task-tracker'
|
||||
import { ClaudeChildWorkDecoder } from './claude-child-work-decoder'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createDeferredStructuredAgentSessionEventSink,
|
||||
@@ -236,7 +237,8 @@ describe('Claude structured reading control', () => {
|
||||
const resumeReading = vi.spyOn(claude.connections[0], 'resumeReading')
|
||||
deferred.sink.appendItem(
|
||||
{ provider: 'orca', clientMessageId: 'blocked-prefill' },
|
||||
{ kind: 'message', role: 'system', blocks: [{ type: 'text', text: 'prefill' }] }
|
||||
{ kind: 'message', role: 'system', blocks: [{ type: 'text', text: 'prefill' }] },
|
||||
{ turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
await appendEntered.promise
|
||||
const notification = {
|
||||
|
||||
@@ -11,7 +11,7 @@ import type {
|
||||
openClaudeStreamJsonConnection
|
||||
} from './claude-stream-json-connection'
|
||||
import type { ClaudeStructuredLaunch } from './claude-structured-launch-resolution'
|
||||
import type { ClaudeJournalTranslator } from './claude-structured-journal-translation'
|
||||
import type { ClaudeJournalTranslator } from './claude-journal-translator-contract'
|
||||
import type { ClaudePendingPrompt, ClaudePromptRegistry } from './claude-structured-prompt-replies'
|
||||
import { cancelProcessAcquisition } from '../../shared/child-process/cancel-process-acquisition'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
@@ -46,7 +46,7 @@ export function writeClaudeSubagentGroupRow(
|
||||
group: RosterGroup
|
||||
): void {
|
||||
const agents = [...group.entries.values()].map((tracked) => tracked.entry)
|
||||
const options = { coalescingKey: `claude-subagents:${group.groupId}` }
|
||||
const options = { coalescingKey: `claude-subagents:${group.groupId}`, turnScope: group.turnScope }
|
||||
if (agents.length === 0) {
|
||||
// The row's last child turned out not to be a subagent. An empty roster is
|
||||
// not a roster of nothing, so the row goes rather than reading "Ran 0".
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types'
|
||||
import type {
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import type { NativeChatSubagentEntry } from '../../shared/native-chat-types'
|
||||
import type { ClaudeSubagentTaskFrame } from './claude-subagent-task-frames'
|
||||
|
||||
@@ -22,6 +25,8 @@ export type TrackedEntry = {
|
||||
export type RosterGroup = {
|
||||
groupId: string
|
||||
identity: AgentJournalItemIdentity
|
||||
/** The spawning turn's scope: the row reports its children beside that turn's work. */
|
||||
turnScope: AgentJournalTurnScope
|
||||
/** Insertion order is the display order; the map holds the state. */
|
||||
entries: Map<string, TrackedEntry>
|
||||
/** Lifetime admissions bound retained labels even when entries are removed. */
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
@@ -43,6 +44,7 @@ function harness(groupKey: string | null = TURN_1) {
|
||||
const roster = new ClaudeSubagentRoster({
|
||||
sink,
|
||||
currentGroupKey: () => key,
|
||||
currentTurnScope: () => AGENT_JOURNAL_THREAD_SCOPE,
|
||||
now: () => (clock += 1)
|
||||
})
|
||||
const roles = (): NativeChatSubagentEntry[] => agentsOf(items.at(-1)?.body)
|
||||
@@ -464,7 +466,11 @@ describe('ClaudeSubagentRoster — through the real sink queue', () => {
|
||||
published += 1
|
||||
}
|
||||
})
|
||||
const roster = new ClaudeSubagentRoster({ sink: deferred.sink, currentGroupKey: () => TURN_1 })
|
||||
const roster = new ClaudeSubagentRoster({
|
||||
sink: deferred.sink,
|
||||
currentGroupKey: () => TURN_1,
|
||||
currentTurnScope: () => AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
|
||||
// The first append is in flight while the rest are submitted, so a publish
|
||||
// sharing the row's coalescing key would evict them.
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
// child on every resume. Outcomes latch within an invocation; a new spawn
|
||||
// alias can reopen it, and authoritative evidence can correct lost contact.
|
||||
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session-journal-types'
|
||||
import {
|
||||
canReplaceSubagentState,
|
||||
isTerminalSubagentState
|
||||
@@ -46,6 +47,8 @@ export type ClaudeSubagentRosterDeps = {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
/** The turn that owns children spawned right now; null outside any turn. */
|
||||
currentGroupKey: () => string | null
|
||||
/** That turn's scope, which the roster row it spawns belongs to. */
|
||||
currentTurnScope: () => AgentJournalTurnScope
|
||||
/** Whether a tool id was forwarded at the TOP level. A child parented to one
|
||||
* was spawned by a call the transcript shows, so its announcement is still
|
||||
* expected; a child parented to anything else names an id that only ever
|
||||
@@ -364,6 +367,7 @@ export class ClaudeSubagentRoster {
|
||||
const group: RosterGroup = {
|
||||
groupId,
|
||||
identity: claudeSubagentGroupIdentity(groupId),
|
||||
turnScope: this.deps.currentTurnScope(),
|
||||
entries: new Map(),
|
||||
admittedEntries: 0,
|
||||
claimedLabels: new Set(),
|
||||
|
||||
@@ -7,6 +7,7 @@ import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key
|
||||
import { agentJournalTurnBody } from '../../shared/agent-session-turn-record'
|
||||
import type { StructuredAgentSessionAppendOptions } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import { claudeResultOutcome } from './claude-result-outcome'
|
||||
import type { ClaudeCommandTurn } from './claude-command-turn'
|
||||
|
||||
export type ClaudeCurrentTurn = {
|
||||
sessionId: string
|
||||
@@ -18,6 +19,13 @@ export type ClaudeCurrentTurn = {
|
||||
/** Provider key of the user echo, or the lifecycle row itself when provider
|
||||
* output opened a turn with no user row to receive its timing. */
|
||||
userItemId: string
|
||||
/** Present when the turn is the host's record of a conversation command. */
|
||||
command?: ClaudeCommandTurn
|
||||
}
|
||||
|
||||
/** The row a turn's lifecycle lives on: the host's record for a command, else the lane's own. */
|
||||
export function claudeCurrentTurnIdentity(turn: ClaudeCurrentTurn): AgentJournalItemIdentity {
|
||||
return turn.command?.identity ?? claudeTurnLifecycleIdentity(turn.sessionId, turn.turnId)
|
||||
}
|
||||
|
||||
export type ClaudeTurnEnd = {
|
||||
@@ -84,7 +92,7 @@ export function claudeTurnLifecycleItem(
|
||||
// already carried, because both are built from the same open turn.
|
||||
const requested = requestedAt === undefined ? {} : { requestedAt }
|
||||
return {
|
||||
identity: claudeTurnLifecycleIdentity(sessionId, turnId),
|
||||
identity: claudeCurrentTurnIdentity(turn),
|
||||
body: agentJournalTurnBody(
|
||||
end
|
||||
? {
|
||||
|
||||
@@ -6,7 +6,6 @@ import type { AgentJournalItemBody } from '../../shared/agent-session-journal-ty
|
||||
import { readAgentJournalTurn } from '../../shared/agent-session-turn-record'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import { StructuredSessionCompaction } from '../native-chat/agent-session-wire/structured-session-compaction'
|
||||
import {
|
||||
CLAUDE_DISPATCH_ADMISSION_TIMEOUT_MS,
|
||||
cancelClaudeStructuredTurn
|
||||
@@ -99,6 +98,10 @@ function sessionHoldingTurn(turnId: string | null): ReturnType<typeof sessionFor
|
||||
openTurnInLiveProviderCycle: false,
|
||||
journalPrompts: { cancel: vi.fn(), resolve: vi.fn() },
|
||||
currentTurnId: turnId,
|
||||
commandTurnId: null,
|
||||
beginCommand: vi.fn(),
|
||||
forgetCommand: vi.fn(),
|
||||
commandInterruptRequested: vi.fn(),
|
||||
flush: vi.fn(),
|
||||
contextActivity: 0,
|
||||
markContextActivity: vi.fn(),
|
||||
@@ -119,7 +122,6 @@ function cancellationOf(
|
||||
return cancelClaudeStructuredTurn({
|
||||
request,
|
||||
sessions: new Map([['session-1', session]]),
|
||||
compactions: new StructuredSessionCompaction(),
|
||||
admitPromptCancellation: () => true
|
||||
})
|
||||
}
|
||||
@@ -281,6 +283,10 @@ describe('Claude turn ownership', () => {
|
||||
openTurnInLiveProviderCycle: false,
|
||||
journalPrompts: { cancel: vi.fn(), resolve: vi.fn() },
|
||||
currentTurnId: 'turn-1',
|
||||
commandTurnId: null,
|
||||
beginCommand: vi.fn(),
|
||||
forgetCommand: vi.fn(),
|
||||
commandInterruptRequested: vi.fn(),
|
||||
flush: vi.fn(),
|
||||
contextActivity: 0,
|
||||
markContextActivity: vi.fn(),
|
||||
@@ -308,7 +314,6 @@ describe('Claude turn ownership', () => {
|
||||
const cancellation = cancelClaudeStructuredTurn({
|
||||
request: { sessionId: 'session-1', turnId: 'turn-1', fence: 1 },
|
||||
sessions: new Map([['session-1', session]]),
|
||||
compactions: new StructuredSessionCompaction(),
|
||||
admitPromptCancellation: () => true
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
|
||||
@@ -14,9 +14,10 @@ import {
|
||||
agentJournalItemKey,
|
||||
parseAgentJournalItemKey
|
||||
} from '../../shared/agent-session-journal-item-key'
|
||||
import type {
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalTurnItem
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalItemIdentity,
|
||||
type AgentJournalTurnItem
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { readAgentJournalTurn } from '../../shared/agent-session-turn-record'
|
||||
import { estimateStructuredAgentSessionItemBytes } from '../native-chat/agent-session-wire/structured-agent-session-event-sink-estimate'
|
||||
@@ -149,7 +150,7 @@ function findTurnRow(
|
||||
export type ClaudeTurnRowDelivery = {
|
||||
/** False only for a writer that publishes each write itself right after queueing it. */
|
||||
publish: boolean
|
||||
options?: StructuredAgentSessionRevisionOptions
|
||||
options?: Omit<StructuredAgentSessionRevisionOptions, 'turnScope'>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,8 +162,10 @@ export function writeClaudeTurnRow(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
target: ClaudeTurnRowTarget,
|
||||
write: ClaudeTurnRowWrite,
|
||||
{ publish, options = {} }: ClaudeTurnRowDelivery
|
||||
{ publish, options: delivery = {} }: ClaudeTurnRowDelivery
|
||||
): void {
|
||||
// A turn record belongs to no turn.
|
||||
const options = { ...delivery, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
const revise = publish ? sink.tryReviseResolvedItemAndPublish : sink.tryReviseResolvedItem
|
||||
if (!revise) {
|
||||
if (write.lifecycle && 'identity' in target) {
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { readAgentJournalTurn } from '../../shared/agent-session-turn-record'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionRevisionJournal,
|
||||
StructuredAgentSessionSinkAdmission
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import { createCodexJournalTranslator } from './codex-structured-journal-translation'
|
||||
import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter'
|
||||
|
||||
const SESSION = 'session-1'
|
||||
const THREAD = 'thread-1'
|
||||
const PROVIDER_TURN = 'compact-turn'
|
||||
const COMMAND_TURN_IDENTITY: AgentJournalItemIdentity = {
|
||||
provider: 'orca',
|
||||
clientMessageId: 'command-turn:cmd-1'
|
||||
}
|
||||
const COMMAND_TURN_KEY = agentJournalItemKey(COMMAND_TURN_IDENTITY)
|
||||
const RUNNING = {
|
||||
kind: 'turn' as const,
|
||||
turnId: 'compact:cmd-1',
|
||||
state: 'running' as const,
|
||||
userItemId: 'orca:submission:cmd-1',
|
||||
requestedAt: 1,
|
||||
startedAt: 1
|
||||
}
|
||||
const COMMAND = {
|
||||
clientMessageId: 'cmd-1',
|
||||
turnId: RUNNING.turnId,
|
||||
identity: COMMAND_TURN_IDENTITY,
|
||||
resultIdentity: { provider: 'orca' as const, clientMessageId: 'command-result:cmd-1' },
|
||||
running: RUNNING
|
||||
}
|
||||
const ACCEPTED: StructuredAgentSessionSinkAdmission = { accepted: true }
|
||||
|
||||
type Written = { key: string; body: AgentJournalItemBody; turnScope?: AgentJournalTurnScope }
|
||||
|
||||
/** Records every write with the scope it states; the journal holds the running command turn. */
|
||||
function recorder(refuseRevisions = 0) {
|
||||
const writes: Written[] = []
|
||||
const record = (
|
||||
identity: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody,
|
||||
turnScope?: AgentJournalTurnScope
|
||||
) => writes.push({ key: agentJournalItemKey(identity), body, turnScope })
|
||||
const commandTurn: AgentJournalItemBody = RUNNING
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the claim resolver reads only `itemBody`.
|
||||
const journal = {
|
||||
itemBody: (itemId: string) => (itemId === COMMAND_TURN_KEY ? commandTurn : null)
|
||||
} as unknown as StructuredAgentSessionRevisionJournal
|
||||
let refusals = refuseRevisions
|
||||
const sink: StructuredAgentSessionEventSink = {
|
||||
appendItem: (identity, body, options) => record(identity, body, options.turnScope),
|
||||
appendTombstone: () => {},
|
||||
publish: () => {},
|
||||
tryPublish: () => ACCEPTED,
|
||||
tryAppendItem: (identity, body, options) => {
|
||||
record(identity, body, options.turnScope)
|
||||
return ACCEPTED
|
||||
},
|
||||
appendLifecycleBatch: (_settlementId, mutations) => {
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.kind === 'item') {
|
||||
record(mutation.identity, mutation.body, mutation.turnScope)
|
||||
}
|
||||
}
|
||||
},
|
||||
tryReviseResolvedItemAndPublish: (_bytes, resolve, options) => {
|
||||
if (refusals > 0) {
|
||||
refusals -= 1
|
||||
return { accepted: false, reason: 'backpressure' }
|
||||
}
|
||||
const resolved = resolve(journal)
|
||||
if (resolved) {
|
||||
record(resolved.identity, resolved.body, options.turnScope)
|
||||
}
|
||||
return ACCEPTED
|
||||
}
|
||||
}
|
||||
return { sink, writes }
|
||||
}
|
||||
|
||||
/** Codex names the thread inside every notification's params too. */
|
||||
function notification(
|
||||
method: string,
|
||||
params: Record<string, unknown>
|
||||
): CodexStructuredSessionEvent {
|
||||
return {
|
||||
type: 'notification',
|
||||
sessionId: SESSION,
|
||||
threadId: THREAD,
|
||||
method,
|
||||
params: { threadId: THREAD, ...params }
|
||||
}
|
||||
}
|
||||
|
||||
function harness(refuseRevisions = 0) {
|
||||
const tap = recorder(refuseRevisions)
|
||||
const translator = createCodexJournalTranslator({
|
||||
sink: tap.sink,
|
||||
sessionId: SESSION,
|
||||
primaryThreadId: () => THREAD
|
||||
})
|
||||
return {
|
||||
...tap,
|
||||
translator,
|
||||
emit: (event: CodexStructuredSessionEvent) => translator.handle(event)
|
||||
}
|
||||
}
|
||||
|
||||
const codexTurnRecords = (writes: readonly Written[]) =>
|
||||
writes.filter((write) => write.key !== COMMAND_TURN_KEY && readAgentJournalTurn(write.body))
|
||||
|
||||
/** The command turn's newest body, as the journal would hold it. */
|
||||
const commandTurn = (writes: readonly Written[]) =>
|
||||
readAgentJournalTurn(writes.findLast((write) => write.key === COMMAND_TURN_KEY)?.body)
|
||||
|
||||
const resultRows = (writes: readonly Written[]) =>
|
||||
writes.filter((write) => write.body.kind === 'status')
|
||||
|
||||
describe('a Codex turn a conversation command claims', () => {
|
||||
it('is the command turn: writes no root turn, scopes its content there, and ends it', () => {
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
|
||||
emit(notification('turn/started', { turn: { id: PROVIDER_TURN } }))
|
||||
// The claim is persisted on the command turn: nothing else re-derives it later.
|
||||
expect(commandTurn(writes)).toMatchObject({ state: 'running', providerTurnId: PROVIDER_TURN })
|
||||
emit(
|
||||
notification('item/completed', {
|
||||
turnId: PROVIDER_TURN,
|
||||
item: { type: 'agentMessage', id: 'summary', text: 'Summary of the conversation.' }
|
||||
})
|
||||
)
|
||||
emit(
|
||||
notification('item/completed', {
|
||||
turnId: PROVIDER_TURN,
|
||||
item: { type: 'contextCompaction', id: 'compaction' }
|
||||
})
|
||||
)
|
||||
emit(notification('turn/completed', { turn: { id: PROVIDER_TURN, status: 'completed' } }))
|
||||
|
||||
expect(codexTurnRecords(writes)).toEqual([])
|
||||
const scope = { kind: 'turn', turnItemId: COMMAND_TURN_KEY }
|
||||
const summary = writes.find(
|
||||
(write) => write.body.kind === 'message' && write.body.role === 'assistant'
|
||||
)
|
||||
expect(summary?.turnScope).toEqual(scope)
|
||||
// Codex's own marker is the command's result row.
|
||||
expect(resultRows(writes)).toEqual([
|
||||
expect.objectContaining({
|
||||
body: { kind: 'status', text: 'Context compacted', presentation: 'compaction' },
|
||||
turnScope: scope
|
||||
})
|
||||
])
|
||||
expect(commandTurn(writes)).toMatchObject({
|
||||
state: 'completed',
|
||||
outcome: 'success',
|
||||
providerTurnId: PROVIDER_TURN,
|
||||
userItemId: RUNNING.userItemId,
|
||||
requestedAt: RUNNING.requestedAt
|
||||
})
|
||||
})
|
||||
|
||||
it('reads an interrupted turn as the command cancelled, with no result row', () => {
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
emit(notification('turn/started', { turn: { id: PROVIDER_TURN } }))
|
||||
emit(notification('turn/completed', { turn: { id: PROVIDER_TURN, status: 'interrupted' } }))
|
||||
|
||||
expect(commandTurn(writes)).toMatchObject({ state: 'interrupted', outcome: 'cancellation' })
|
||||
expect(resultRows(writes)).toEqual([])
|
||||
})
|
||||
|
||||
it('reads a turn that completed without compacting as a failure, with the reason', () => {
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
emit(notification('turn/started', { turn: { id: PROVIDER_TURN } }))
|
||||
emit(
|
||||
notification('turn/completed', {
|
||||
turn: { id: PROVIDER_TURN, status: 'failed', error: { message: 'Unavailable' } }
|
||||
})
|
||||
)
|
||||
|
||||
expect(commandTurn(writes)).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
expect(resultRows(writes).map((write) => write.body)).toEqual([
|
||||
{
|
||||
kind: 'status',
|
||||
text: 'Compaction failed: Unavailable.',
|
||||
failure: {
|
||||
kind: 'compactionFailed',
|
||||
detail: { text: 'Unavailable', audience: 'person' }
|
||||
},
|
||||
tone: 'error'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('says only that the compaction failed when a turn that did not complete gave no words', () => {
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
emit(notification('turn/started', { turn: { id: PROVIDER_TURN } }))
|
||||
emit(notification('turn/completed', { turn: { id: PROVIDER_TURN, status: 'failed' } }))
|
||||
|
||||
expect(commandTurn(writes)).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
expect(resultRows(writes).map((write) => write.body)).toEqual([
|
||||
{
|
||||
kind: 'status',
|
||||
text: 'Compaction failed.',
|
||||
failure: { kind: 'compactionFailed' },
|
||||
tone: 'error'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('reports a turn that completed without Codex reporting a compaction as unconfirmed', () => {
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
emit(notification('turn/started', { turn: { id: PROVIDER_TURN } }))
|
||||
emit(notification('turn/completed', { turn: { id: PROVIDER_TURN, status: 'completed' } }))
|
||||
|
||||
expect(commandTurn(writes)).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
expect(resultRows(writes).map((write) => write.body)).toEqual([
|
||||
{
|
||||
kind: 'status',
|
||||
text: 'Compaction completion is unconfirmed.',
|
||||
failure: { kind: 'compactionUnconfirmed' },
|
||||
tone: 'error'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('ends a compaction Codex failed with an error once, however late its completion', () => {
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
emit(notification('turn/started', { turn: { id: PROVIDER_TURN } }))
|
||||
emit(
|
||||
notification('error', {
|
||||
turnId: PROVIDER_TURN,
|
||||
willRetry: false,
|
||||
error: { message: 'Unavailable' }
|
||||
})
|
||||
)
|
||||
// The error is a row; only the completion ends the turn.
|
||||
expect(commandTurn(writes)).toMatchObject({ state: 'running' })
|
||||
// Codex still completes the turn it failed, as status failed.
|
||||
emit(
|
||||
notification('turn/completed', {
|
||||
turn: { id: PROVIDER_TURN, status: 'failed', error: { message: 'Unavailable' } }
|
||||
})
|
||||
)
|
||||
|
||||
expect(codexTurnRecords(writes)).toEqual([])
|
||||
expect(commandTurn(writes)).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
expect(
|
||||
writes.filter(
|
||||
(write) => write.key === COMMAND_TURN_KEY && readAgentJournalTurn(write.body)?.completedAt
|
||||
)
|
||||
).toHaveLength(1)
|
||||
// Codex's own error row, in the command's turn; the completion adds none.
|
||||
expect(resultRows(writes)).toEqual([
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({ kind: 'status', text: 'Unavailable', tone: 'error' }),
|
||||
turnScope: { kind: 'turn', turnItemId: COMMAND_TURN_KEY }
|
||||
})
|
||||
])
|
||||
})
|
||||
|
||||
it("ends a captured failed compaction on its completion, below one row of Codex's own", () => {
|
||||
// A real app-server's compaction turn: two retried stream errors, the turn-ending error, then
|
||||
// the failed completion.
|
||||
const captured: { case: string; t: number; method: string; params: object }[] = readFileSync(
|
||||
join(__dirname, '__fixtures__', 'codex-app-server-turn-endings.jsonl'),
|
||||
'utf8'
|
||||
)
|
||||
.split('\n')
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => JSON.parse(line))
|
||||
.filter((frame) => frame.case === '0.158.0-compact-overloaded')
|
||||
const compactionTurn = captured.findLastIndex((frame) => frame.method === 'turn/started')
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
for (const frame of captured.slice(compactionTurn)) {
|
||||
emit({
|
||||
type: 'notification',
|
||||
sessionId: SESSION,
|
||||
threadId: THREAD,
|
||||
method: frame.method,
|
||||
params: { ...frame.params, threadId: THREAD },
|
||||
observedAt: frame.t
|
||||
})
|
||||
}
|
||||
|
||||
expect(codexTurnRecords(writes)).toEqual([])
|
||||
const completion = captured.at(-1)!
|
||||
expect(completion.method).toBe('turn/completed')
|
||||
expect(commandTurn(writes)).toMatchObject({
|
||||
state: 'completed',
|
||||
outcome: 'failure',
|
||||
completedAt: completion.t
|
||||
})
|
||||
// Every row is one of Codex's frames, inside the command's turn; the completion adds none.
|
||||
const scope = { kind: 'turn', turnItemId: COMMAND_TURN_KEY }
|
||||
const rows = resultRows(writes)
|
||||
expect(rows.map((write) => write.key)).not.toContain(
|
||||
agentJournalItemKey(COMMAND.resultIdentity)
|
||||
)
|
||||
expect(rows.map((write) => write.turnScope)).toEqual(rows.map(() => scope))
|
||||
expect(
|
||||
rows.some(
|
||||
(write) =>
|
||||
write.body.kind === 'status' &&
|
||||
write.body.tone === 'error' &&
|
||||
write.body.text.includes('Selected model is at capacity')
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('leaves the next turn to write its own record after a failed compaction', () => {
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
emit(notification('turn/started', { turn: { id: PROVIDER_TURN } }))
|
||||
emit(
|
||||
notification('error', { turnId: PROVIDER_TURN, willRetry: false, error: { message: 'x' } })
|
||||
)
|
||||
emit(notification('turn/completed', { turn: { id: PROVIDER_TURN, status: 'failed' } }))
|
||||
emit(notification('turn/started', { turn: { id: 'ordinary' } }))
|
||||
emit(notification('turn/completed', { turn: { id: 'ordinary', status: 'completed' } }))
|
||||
|
||||
expect(
|
||||
codexTurnRecords(writes).map((write) => readAgentJournalTurn(write.body)?.turnId)
|
||||
).toEqual(['ordinary', 'ordinary'])
|
||||
})
|
||||
|
||||
it('names no provider turn for a Stop until Codex opens one, then the one it opened', () => {
|
||||
const { translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
expect(translator.commandProviderTurnId(COMMAND.turnId)).toBeUndefined()
|
||||
emit(notification('turn/started', { turn: { id: PROVIDER_TURN } }))
|
||||
expect(translator.commandProviderTurnId(COMMAND.turnId)).toBe(PROVIDER_TURN)
|
||||
expect(translator.commandProviderTurnId('ordinary')).toBe('ordinary')
|
||||
})
|
||||
|
||||
it('claims the same provider turn when the refused start is retried', () => {
|
||||
const { writes, translator, emit } = harness(1)
|
||||
translator.beginCommand(COMMAND)
|
||||
const started = notification('turn/started', { turn: { id: PROVIDER_TURN } })
|
||||
|
||||
expect(emit(started)).toEqual({ accepted: false, reason: 'backpressure' })
|
||||
expect(emit(started)).toEqual(ACCEPTED)
|
||||
|
||||
expect(codexTurnRecords(writes)).toEqual([])
|
||||
expect(commandTurn(writes)).toMatchObject({ providerTurnId: PROVIDER_TURN })
|
||||
expect(translator.commandProviderTurnId(COMMAND.turnId)).toBe(PROVIDER_TURN)
|
||||
})
|
||||
|
||||
it('leaves a primary turn no command claims to write its own record', () => {
|
||||
const { writes, translator, emit } = harness()
|
||||
translator.beginCommand(COMMAND)
|
||||
translator.forgetCommand(COMMAND.turnId)
|
||||
emit(notification('turn/started', { turn: { id: 'ordinary' } }))
|
||||
emit(notification('turn/completed', { turn: { id: 'ordinary', status: 'completed' } }))
|
||||
expect(
|
||||
codexTurnRecords(writes).map((write) => readAgentJournalTurn(write.body)?.state)
|
||||
).toEqual(['running', 'completed'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { parseAgentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionSinkAdmission
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
|
||||
const CLAIM_BYTES = 4_096
|
||||
|
||||
/** Records on the command's turn which provider turn carried it out. Persisted because nothing
|
||||
* else re-derives it once the command settles, and a rewind has to place that turn's rows. */
|
||||
export function recordCodexCommandTurnClaim(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
commandTurnItemId: string,
|
||||
providerTurnId: string
|
||||
): StructuredAgentSessionSinkAdmission {
|
||||
const identity = parseAgentJournalItemKey(commandTurnItemId)
|
||||
if (!identity || !sink.tryReviseResolvedItemAndPublish) {
|
||||
return { accepted: true }
|
||||
}
|
||||
return sink.tryReviseResolvedItemAndPublish(
|
||||
CLAIM_BYTES,
|
||||
(journal) => {
|
||||
const body = journal.itemBody(commandTurnItemId)
|
||||
// Settled already — by the host, or by a child's death — leaves nothing to annotate.
|
||||
return body?.kind === 'turn' && body.state === 'running'
|
||||
? { identity, body: { ...body, providerTurnId } }
|
||||
: null
|
||||
},
|
||||
{ lifecycle: true, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// The conversation command a Codex child is running. Codex carries a command out as a turn of its
|
||||
// own; that turn writes no record, its rows join the command's turn, and its end is the command's.
|
||||
// Held by the child's translator, so it ends with the child and nothing has to release it.
|
||||
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import { agentJournalTurnBody } from '../../shared/agent-session-turn-record'
|
||||
import { providerDiagnostic } from '../../shared/agent-session-failure'
|
||||
import { agentSessionFailureWords } from '../../shared/agent-session-failure-words'
|
||||
import { TUI_AGENT_DISPLAY_NAMES } from '../../shared/tui-agent-display-names'
|
||||
import type { JournalLifecycleMutationInput } from '../native-chat/agent-session-journal/journal-row-builders'
|
||||
import type { StructuredAgentSessionCommandRun } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import { structuredCompactionOutcome } from '../native-chat/agent-session-wire/structured-conversation-command-outcome'
|
||||
import { readCodexJournalRecord } from './codex-structured-journal-translation-values'
|
||||
import { readCodexTurnId } from './codex-structured-thread-facts'
|
||||
|
||||
type CarriedCommand = {
|
||||
command: StructuredAgentSessionCommandRun
|
||||
compacted: boolean
|
||||
/** Codex's own error row already says why the command failed. */
|
||||
failureShown: boolean
|
||||
}
|
||||
|
||||
export class CodexJournalCommandTurn {
|
||||
/** Sent, and not yet carried by a provider turn. */
|
||||
private awaiting: StructuredAgentSessionCommandRun | null = null
|
||||
private readonly carried = new Map<string, CarriedCommand>()
|
||||
|
||||
/** Before Orca sends the command: the next primary turn to start carries it out. */
|
||||
begin(command: StructuredAgentSessionCommandRun): void {
|
||||
this.awaiting = command
|
||||
}
|
||||
|
||||
/** The command was never taken. */
|
||||
forget(turnId: string): void {
|
||||
if (this.awaiting?.turnId === turnId) {
|
||||
this.awaiting = null
|
||||
}
|
||||
}
|
||||
|
||||
/** The command the primary turn `providerTurnId` carries out. Idempotent per provider turn, so a
|
||||
* refused frame's retry gets the same answer. */
|
||||
claim(providerTurnId: string): StructuredAgentSessionCommandRun | null {
|
||||
const carried = this.carried.get(providerTurnId)
|
||||
if (carried || !this.awaiting) {
|
||||
return carried?.command ?? null
|
||||
}
|
||||
const command = this.awaiting
|
||||
this.awaiting = null
|
||||
this.carried.set(providerTurnId, { command, compacted: false, failureShown: false })
|
||||
return command
|
||||
}
|
||||
|
||||
isCarrying(providerTurnId: string): boolean {
|
||||
return this.carried.has(providerTurnId)
|
||||
}
|
||||
|
||||
scopeFor(providerTurnId: string): AgentJournalTurnScope | null {
|
||||
const carried = this.carried.get(providerTurnId)
|
||||
return carried
|
||||
? { kind: 'turn', turnItemId: agentJournalItemKey(carried.command.identity) }
|
||||
: null
|
||||
}
|
||||
|
||||
/** The provider turn a Stop on `turnId` interrupts: none while the command has not started one. */
|
||||
providerTurnId(turnId: string): string | undefined {
|
||||
if (this.awaiting?.turnId === turnId) {
|
||||
return undefined
|
||||
}
|
||||
for (const [providerTurnId, { command }] of this.carried) {
|
||||
if (command.turnId === turnId) {
|
||||
return providerTurnId
|
||||
}
|
||||
}
|
||||
return turnId
|
||||
}
|
||||
|
||||
/** Codex reported the compaction, in the turn carrying the command. */
|
||||
compacted(providerTurnId: string): void {
|
||||
const carried = this.carried.get(providerTurnId)
|
||||
if (carried) {
|
||||
carried.compacted = true
|
||||
}
|
||||
}
|
||||
|
||||
/** The command's end, for the batch that settles the provider turn carrying it. */
|
||||
end(
|
||||
providerTurnId: string,
|
||||
ended: {
|
||||
status: string | null
|
||||
error: string | null
|
||||
completedAt: number
|
||||
}
|
||||
): JournalLifecycleMutationInput[] {
|
||||
const carried = this.carried.get(providerTurnId)
|
||||
if (!carried) {
|
||||
return []
|
||||
}
|
||||
const { command } = carried
|
||||
const detail = ended.error === null ? undefined : providerDiagnostic(ended.error, 'person')
|
||||
const verdict = structuredCompactionOutcome({
|
||||
compacted: carried.compacted,
|
||||
// Codex reports the user's stop as the turn's own status.
|
||||
interruptRequested: ended.status === 'interrupted',
|
||||
// A turn that did not complete failed, not merely went unconfirmed.
|
||||
failed: ended.status !== 'completed' || detail ? (detail ? { detail } : {}) : null
|
||||
})
|
||||
const turnScope = { kind: 'turn' as const, turnItemId: agentJournalItemKey(command.identity) }
|
||||
return [
|
||||
// A success already drew Codex's own compaction marker inside the command's turn.
|
||||
...(verdict.failure && !carried.failureShown
|
||||
? [
|
||||
{
|
||||
kind: 'item' as const,
|
||||
identity: command.resultIdentity,
|
||||
body: {
|
||||
kind: 'status' as const,
|
||||
...agentSessionFailureWords(verdict.failure, {
|
||||
surface: 'row',
|
||||
agentName: TUI_AGENT_DISPLAY_NAMES.codex
|
||||
}),
|
||||
tone: 'error' as const
|
||||
},
|
||||
turnScope
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{
|
||||
kind: 'item',
|
||||
identity: command.identity,
|
||||
body: agentJournalTurnBody({
|
||||
...command.running,
|
||||
providerTurnId,
|
||||
state: verdict.outcome === 'cancellation' ? 'interrupted' : 'completed',
|
||||
outcome: verdict.outcome,
|
||||
completedAt: ended.completedAt
|
||||
}),
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
/** Codex's `error` frame, already a row in the turn it names. A turn-ending one says why the
|
||||
* command failed, so the failed completion that follows it adds no second row. */
|
||||
errorShown(params: unknown): void {
|
||||
const providerTurnId = readCodexTurnId(params)
|
||||
const carried = providerTurnId ? this.carried.get(providerTurnId) : undefined
|
||||
// A stream error Codex is about to retry ends nothing.
|
||||
if (carried && readCodexJournalRecord(params).willRetry !== true) {
|
||||
carried.failureShown = true
|
||||
}
|
||||
}
|
||||
|
||||
settled(providerTurnId: string): void {
|
||||
this.carried.delete(providerTurnId)
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.awaiting = null
|
||||
this.carried.clear()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Which turn a Codex row belongs to, stated when the row is written.
|
||||
//
|
||||
// A primary-thread row belongs to the turn it names: that turn's lifecycle record, or the
|
||||
// conversation command that claimed it. A child thread has turns of its own that the timeline
|
||||
// does not draw, so its rows belong to the primary turn running when they arrive — the work the
|
||||
// user is watching — or to no turn once the primary is idle.
|
||||
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { codexTurnLifecycleIdentity } from './codex-structured-journal-translation-turns'
|
||||
|
||||
export class CodexJournalTurnScopes {
|
||||
constructor(
|
||||
private readonly deps: {
|
||||
/** Without it no turn record is keyed, so every row reads as the thread's. */
|
||||
sessionId: string | undefined
|
||||
primaryThreadId: () => string | null
|
||||
activeTurn: (threadId: string) => string | null
|
||||
/** The command turn's scope, for a primary turn carrying a conversation command. */
|
||||
commandScope: (turnId: string) => AgentJournalTurnScope | null
|
||||
}
|
||||
) {}
|
||||
|
||||
scopeFor(threadId: string, turnId: string | null): AgentJournalTurnScope {
|
||||
const primary = this.deps.primaryThreadId()
|
||||
const primaryTurnId =
|
||||
primary === null ? null : threadId === primary ? turnId : this.deps.activeTurn(primary)
|
||||
if (primaryTurnId === null) {
|
||||
return AGENT_JOURNAL_THREAD_SCOPE
|
||||
}
|
||||
const { sessionId } = this.deps
|
||||
return (
|
||||
this.deps.commandScope(primaryTurnId) ??
|
||||
(sessionId === undefined
|
||||
? AGENT_JOURNAL_THREAD_SCOPE
|
||||
: {
|
||||
kind: 'turn',
|
||||
turnItemId: agentJournalItemKey(codexTurnLifecycleIdentity(sessionId, primaryTurnId))
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
@@ -45,7 +46,7 @@ function fixture(maxMetadataBytes?: number) {
|
||||
{
|
||||
sink,
|
||||
maxMetadataBytes,
|
||||
linkageFor: () => ({}),
|
||||
attributionFor: () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE }),
|
||||
schedule: (run) => {
|
||||
scheduled.add(run)
|
||||
return () => {
|
||||
@@ -119,7 +120,7 @@ describe('persistent command retention', () => {
|
||||
sink,
|
||||
streams: items.streams,
|
||||
activeItems: items.activeItems,
|
||||
linkageFor: () => ({})
|
||||
attributionFor: () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE })
|
||||
})
|
||||
).toEqual({ accepted: true })
|
||||
}
|
||||
@@ -215,7 +216,7 @@ describe('persistent command retention', () => {
|
||||
sink,
|
||||
streams: items.streams,
|
||||
activeItems: items.activeItems,
|
||||
linkageFor: () => ({})
|
||||
attributionFor: () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE })
|
||||
})
|
||||
).toEqual({ accepted: true })
|
||||
expect(items.activeItems.size).toBe(1)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// A compaction Codex refuses up front keeps Codex's own words for the chat's failure row.
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { structuredAgentSessionCommandTurn } from '../native-chat/agent-session-wire/structured-agent-session-command-turn'
|
||||
import { CodexAppServerRequestError } from './codex-app-server-connection'
|
||||
import { acquired, fakeCodex } from './codex-structured-session-adapter-fixture'
|
||||
|
||||
@@ -17,12 +18,25 @@ describe('Codex compaction refused at the request', () => {
|
||||
}
|
||||
})
|
||||
const adapter = await acquired(codex)
|
||||
const turn = structuredAgentSessionCommandTurn('cmd-1')
|
||||
|
||||
await expect(
|
||||
adapter.compact({ turnId: 'compact-1', sessionId: 'session-1', fence: 7 })
|
||||
adapter.compact({
|
||||
sessionId: 'session-1',
|
||||
fence: 7,
|
||||
command: {
|
||||
clientMessageId: 'cmd-1',
|
||||
...turn,
|
||||
running: { kind: 'turn', turnId: turn.turnId, state: 'running' }
|
||||
}
|
||||
})
|
||||
).resolves.toEqual({
|
||||
outcome: 'failed',
|
||||
detail: { text: 'thread has nothing to compact', audience: 'person' }
|
||||
state: 'rejected',
|
||||
reason: 'The provider did not accept this message: thread has nothing to compact.',
|
||||
rejection: {
|
||||
kind: 'providerRejected',
|
||||
detail: { text: 'thread has nothing to compact', audience: 'person' }
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// `turn/start` before it opens the turn, and refuses an interrupt until then.
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { structuredAgentSessionCommandTurn } from '../native-chat/agent-session-wire/structured-agent-session-command-turn'
|
||||
import {
|
||||
CODEX_TEST_THREAD_ID,
|
||||
codexTurnLifecycleRig
|
||||
@@ -71,16 +72,21 @@ describe('a Codex Stop that names no turn', () => {
|
||||
const rig = await codexTurnLifecycleRig()
|
||||
await openedTurn(rig)
|
||||
rig.turns.end('completed')
|
||||
const turn = structuredAgentSessionCommandTurn('operation-1')
|
||||
const compaction = rig.adapter.compact({
|
||||
turnId: 'compact:operation-1',
|
||||
sessionId: 'session-1',
|
||||
fence: 7
|
||||
fence: 7,
|
||||
command: {
|
||||
clientMessageId: 'operation-1',
|
||||
...turn,
|
||||
running: { kind: 'turn', turnId: turn.turnId, state: 'running' }
|
||||
}
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(rig.codex.connections[0]!.calls.at(-1)?.method).toBe('thread/compact/start')
|
||||
)
|
||||
|
||||
await expect(stop(rig, () => 'compact:operation-1')).resolves.toEqual({ cancelled: false })
|
||||
await expect(stop(rig, () => turn.turnId)).resolves.toEqual({ cancelled: false })
|
||||
expect(rig.interrupts()).toEqual([])
|
||||
|
||||
rig.notify('turn/started', { threadId: CODEX_TEST_THREAD_ID, turn: { id: 'turn-compact' } })
|
||||
@@ -89,6 +95,6 @@ describe('a Codex Stop that names no turn', () => {
|
||||
threadId: CODEX_TEST_THREAD_ID,
|
||||
turn: { id: 'turn-compact', status: 'completed' }
|
||||
})
|
||||
await expect(compaction).resolves.toEqual({ outcome: 'compacted' })
|
||||
await expect(compaction).resolves.toEqual({ state: 'accepted', providerIdentity: null })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { AgentJournalItemIdentity } from '../../shared/agent-session-journa
|
||||
import type { AgentSessionDeltaCoalescerDeps } from '../native-chat/agent-session-wire/agent-session-delta-coalescer'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import type { codexJournalItem, CodexThreadItem } from './codex-structured-item-translation'
|
||||
import type { CodexRowLinkage } from './codex-subagent-linkage'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
|
||||
export type CodexItemStreamDeps = {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
@@ -13,7 +13,7 @@ export type CodexItemStreamDeps = {
|
||||
turnId: string | null,
|
||||
item: CodexThreadItem
|
||||
) => AgentJournalItemIdentity
|
||||
linkageFor: CodexRowLinkage
|
||||
attributionFor: CodexRowAttribution
|
||||
coalesceMs?: number
|
||||
maxRetainedBytes?: number
|
||||
maxTotalRetainedBytes?: number
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalRowAttribution
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { createAgentSessionDeltaCoalescer } from '../native-chat/agent-session-wire/agent-session-delta-coalescer'
|
||||
import { CodexItemStreamRetention } from './codex-item-stream-retention'
|
||||
import { appendCodexItemAndPublish } from './codex-structured-journal-sink'
|
||||
@@ -51,12 +55,14 @@ export function createCodexStructuredItemStreams(
|
||||
const states = new CodexItemStreamRetention(deps.maxMetadataBytes)
|
||||
const checkpointLengths = new Map<string, number>()
|
||||
const pendingCheckpoints = new Set<string>()
|
||||
// Which thread and turn produced each stream, resolved to linkage per append
|
||||
// Which thread and turn produced each stream, resolved to its attribution per append
|
||||
// so a parent learned after the first checkpoint still reaches the row.
|
||||
const producers = new Map<string, { threadId: string; turnId: string | null }>()
|
||||
const linkageOf = (key: string) => {
|
||||
const attributionOf = (key: string): AgentJournalRowAttribution => {
|
||||
const producer = producers.get(key)
|
||||
return producer ? deps.linkageFor(producer.threadId, producer.turnId) : {}
|
||||
return producer
|
||||
? deps.attributionFor(producer.threadId, producer.turnId)
|
||||
: { turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
}
|
||||
// Patch updates are authoritative item snapshots. Keep the latest rejected
|
||||
// snapshot until the journal admits it; unlike streamed deltas, there is no
|
||||
@@ -114,7 +120,7 @@ export function createCodexStructuredItemStreams(
|
||||
}
|
||||
return appendCodexItemAndPublish(deps.sink, state.identity, translated.body, {
|
||||
coalescingKey: `checkpoint:${agentJournalItemKey(state.identity)}`,
|
||||
...linkageOf(key)
|
||||
...attributionOf(key)
|
||||
}).accepted
|
||||
}
|
||||
|
||||
@@ -191,7 +197,7 @@ export function createCodexStructuredItemStreams(
|
||||
deps.sink,
|
||||
pending.identity,
|
||||
pending.body,
|
||||
linkageOf(key)
|
||||
attributionOf(key)
|
||||
)
|
||||
if (!admission.accepted) {
|
||||
return admission
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types'
|
||||
@@ -82,7 +83,7 @@ describe('compaction provider generation compatibility', () => {
|
||||
if (stage === 'append' && reject) {
|
||||
return { accepted: false, reason: 'backpressure' }
|
||||
}
|
||||
sink.appendItem(identity, body)
|
||||
sink.appendItem(identity, body, { turnScope: AGENT_JOURNAL_THREAD_SCOPE })
|
||||
return { accepted: true }
|
||||
}
|
||||
sink.tryPublish = () => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { isCodexCompactionComplete } from '../native-chat/agent-session-wire/structured-session-compaction'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import {
|
||||
CODEX_JOURNAL_ADMITTED,
|
||||
@@ -8,7 +7,16 @@ import {
|
||||
import { MAX_CODEX_GENERIC_TURN_BUCKETS } from './codex-structured-journal-limits'
|
||||
import { appendCodexLifecycleItem, publishCodexLifecycle } from './codex-structured-journal-sink'
|
||||
import { readCodexTurnId } from './codex-structured-thread-facts'
|
||||
import type { CodexRowLinkage } from './codex-subagent-linkage'
|
||||
import { readRecord } from './codex-item-field-readers'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
|
||||
function isCodexCompactionComplete(method: string, params: unknown): boolean {
|
||||
return (
|
||||
method === 'thread/compacted' ||
|
||||
(method === 'item/completed' &&
|
||||
readRecord(readRecord(params).item).type === 'contextCompaction')
|
||||
)
|
||||
}
|
||||
|
||||
export class CodexJournalCompactions {
|
||||
private readonly turns = new Map<string, 'item' | 'legacy'>()
|
||||
@@ -16,7 +24,9 @@ export class CodexJournalCompactions {
|
||||
constructor(
|
||||
private readonly sink: StructuredAgentSessionEventSink,
|
||||
private readonly activeTurn: (threadId: string) => string | null,
|
||||
private readonly linkageFor: CodexRowLinkage
|
||||
private readonly attributionFor: CodexRowAttribution,
|
||||
/** Evidence for a conversation command the turn carries; its marker is the command's result. */
|
||||
private readonly compacted: (turnId: string) => void
|
||||
) {}
|
||||
|
||||
handle(event: {
|
||||
@@ -31,6 +41,7 @@ export class CodexJournalCompactions {
|
||||
if (!turnId) {
|
||||
return null
|
||||
}
|
||||
this.compacted(turnId)
|
||||
// Collapse compactions within a thread/turn; the canonical item replaces its legacy fallback.
|
||||
const key = createHash('sha256')
|
||||
.update(JSON.stringify([event.threadId, turnId]))
|
||||
@@ -44,7 +55,7 @@ export class CodexJournalCompactions {
|
||||
this.sink,
|
||||
{ provider: 'orca', clientMessageId: `codex-compaction:${key}` },
|
||||
{ kind: 'status', text: 'Context compacted', presentation: 'compaction' },
|
||||
this.linkageFor(event.threadId, turnId)
|
||||
this.attributionFor(event.threadId, turnId)
|
||||
)
|
||||
if (!admission.accepted) {
|
||||
return admission
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { AgentSessionDeltaCoalescerDeps } from '../native-chat/agent-sessio
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter'
|
||||
import type { CodexSubagentExecutions } from './codex-subagent-executions'
|
||||
import type { StructuredAgentSessionCommandRun } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
|
||||
export type CodexJournalTranslatorDeps = {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
@@ -34,6 +35,13 @@ export type CodexJournalTranslatorDeps = {
|
||||
|
||||
export type CodexJournalTranslator = {
|
||||
handle: (event: CodexStructuredSessionEvent) => CodexJournalTranslationAdmission
|
||||
/** Before Orca sends a conversation command: the next primary turn carries it out, and that
|
||||
* turn's end is the command's. */
|
||||
beginCommand: (command: StructuredAgentSessionCommandRun) => void
|
||||
/** The command was never taken. */
|
||||
forgetCommand: (turnId: string) => void
|
||||
/** The provider turn a Stop naming `turnId` interrupts; undefined while a command has none. */
|
||||
commandProviderTurnId: (turnId: string) => string | undefined
|
||||
cancelPrompt: (journalItemId: string) => CodexJournalTranslationAdmission
|
||||
restoreThread: (
|
||||
threadId: string,
|
||||
|
||||
@@ -12,7 +12,8 @@ import {
|
||||
MAX_CODEX_GENERIC_TURN_BUCKETS
|
||||
} from './codex-structured-journal-limits'
|
||||
import { readCodexTurnId } from './codex-structured-thread-facts'
|
||||
import type { CodexRowLinkage } from './codex-subagent-linkage'
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
|
||||
const OVERFLOW_BUCKET = '__codex-generic-overflow__'
|
||||
/** `producer` is absent only on the overflow bucket, which pools every thread's
|
||||
@@ -59,7 +60,7 @@ export class CodexJournalGenericFrames {
|
||||
|
||||
constructor(
|
||||
private readonly deps: Pick<CodexJournalTranslatorDeps, 'sink' | 'schedule' | 'coalesceMs'> & {
|
||||
linkageFor: CodexRowLinkage
|
||||
attributionFor: CodexRowAttribution
|
||||
},
|
||||
private readonly activeTurn: (threadId: string) => string | null
|
||||
) {
|
||||
@@ -102,10 +103,10 @@ export class CodexJournalGenericFrames {
|
||||
provider: 'orca' as const,
|
||||
clientMessageId: `provider-frame:codex:${this.fallbackSequence}`
|
||||
}
|
||||
const linkage = this.deps.linkageFor(threadId, frameTurnId)
|
||||
const attribution = this.deps.attributionFor(threadId, frameTurnId)
|
||||
const admission = this.deps.sink.tryAppendItem
|
||||
? this.deps.sink.tryAppendItem(identity, translated.body, linkage)
|
||||
: (this.deps.sink.appendItem(identity, translated.body, linkage), CODEX_JOURNAL_ADMITTED)
|
||||
? this.deps.sink.tryAppendItem(identity, translated.body, attribution)
|
||||
: (this.deps.sink.appendItem(identity, translated.body, attribution), CODEX_JOURNAL_ADMITTED)
|
||||
if (!admission.accepted) {
|
||||
this.fallbackSequence -= 1
|
||||
return admission
|
||||
@@ -139,11 +140,12 @@ export class CodexJournalGenericFrames {
|
||||
provider: 'orca' as const,
|
||||
clientMessageId: `provider-frame-suppressed:codex:${bucket}`
|
||||
}
|
||||
// A summary across evicted turns names no producer and belongs to no turn.
|
||||
const options = {
|
||||
coalescingKey: `provider-frame-suppressed:codex:${bucket}`,
|
||||
...(summary.producer
|
||||
? this.deps.linkageFor(summary.producer.threadId, summary.producer.turnId)
|
||||
: {})
|
||||
? this.deps.attributionFor(summary.producer.threadId, summary.producer.turnId)
|
||||
: { turnScope: AGENT_JOURNAL_THREAD_SCOPE })
|
||||
}
|
||||
const admission = this.deps.sink.tryAppendItem
|
||||
? this.deps.sink.tryAppendItem(identity, { kind: 'status', text }, options)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type {
|
||||
@@ -137,7 +138,7 @@ describe('codex goal lifecycle admission', () => {
|
||||
appendTombstone: () => {},
|
||||
publish: () => {}
|
||||
} satisfies StructuredAgentSessionEventSink
|
||||
const goals = new CodexJournalGoals(sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(sink, () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE }))
|
||||
const update = (goal: Record<string, unknown> = {}) =>
|
||||
goals.handle({ threadId: THREAD, method: 'thread/goal/updated', params: goalFrame(goal) })
|
||||
const clear = () =>
|
||||
@@ -178,7 +179,7 @@ describe('codex goal lifecycle admission', () => {
|
||||
appendTombstone: () => {},
|
||||
publish: () => {}
|
||||
} satisfies StructuredAgentSessionEventSink
|
||||
const goals = new CodexJournalGoals(sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(sink, () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE }))
|
||||
const send = (threadId: string) =>
|
||||
goals.handle({ threadId, method: 'thread/goal/updated', params: goalFrame() })
|
||||
|
||||
@@ -211,7 +212,7 @@ describe('codex goal lifecycle admission', () => {
|
||||
appendTombstone: () => {},
|
||||
publish: () => {}
|
||||
} satisfies StructuredAgentSessionEventSink
|
||||
const goals = new CodexJournalGoals(sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(sink, () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE }))
|
||||
const event = { threadId: THREAD, method: 'thread/goal/updated', params: goalFrame() }
|
||||
|
||||
goals.handle(event)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import type {
|
||||
@@ -130,7 +131,9 @@ describe('codex goal lifecycle resume', () => {
|
||||
it('does not append a cleared snapshot when the journal has no prior goal occurrence', async () => {
|
||||
const journal = goalJournal()
|
||||
journal.unbind()
|
||||
const resumed = new CodexJournalGoals(journal.sink, () => ({}))
|
||||
const resumed = new CodexJournalGoals(journal.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
|
||||
expect(
|
||||
resumed.handle({
|
||||
@@ -151,7 +154,9 @@ describe('codex goal lifecycle resume', () => {
|
||||
|
||||
it('does not revisit durable history for accounting-only updates', async () => {
|
||||
const journal = goalJournal()
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
goals.handle({ threadId: THREAD, method: 'thread/goal/updated', params: goalFrame() })
|
||||
await journal.drained()
|
||||
const visits = journal.visits()
|
||||
@@ -176,7 +181,9 @@ describe('codex goal lifecycle resume', () => {
|
||||
|
||||
it('rebuilds dedupe state after the journal epoch is replaced', async () => {
|
||||
const journal = goalJournal()
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
const event = { threadId: THREAD, method: 'thread/goal/updated', params: goalFrame() }
|
||||
|
||||
goals.handle(event)
|
||||
@@ -198,7 +205,9 @@ describe('codex goal lifecycle resume', () => {
|
||||
it('visits a large journal once per epoch when thread churn exceeds the transient LRU', async () => {
|
||||
const journal = goalJournal()
|
||||
journal.seedProviderItems(10_000)
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
const threadCount = MAX_CODEX_GOAL_THREADS + 1
|
||||
const sendRound = () => {
|
||||
for (let index = 0; index < threadCount; index += 1) {
|
||||
@@ -227,7 +236,9 @@ describe('codex goal lifecycle resume', () => {
|
||||
const journal = goalJournal()
|
||||
journal.seedProviderItems(10_000)
|
||||
journal.unbind()
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
|
||||
for (let index = 0; index < MAX_CODEX_GOAL_THREADS; index += 1) {
|
||||
goals.handle({
|
||||
@@ -249,7 +260,9 @@ describe('codex goal lifecycle resume', () => {
|
||||
|
||||
it('retries a journal-derived transition after lifecycle backpressure', async () => {
|
||||
const journal = goalJournal({ watermarks: { maxLifecycleQueuedOperations: 1 } })
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(journal.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
journal.unbind()
|
||||
|
||||
expect(
|
||||
@@ -317,7 +330,9 @@ describe('codex goal lifecycle resume', () => {
|
||||
})
|
||||
}
|
||||
|
||||
const prior = new CodexJournalGoals(journal.sink, () => ({}))
|
||||
const prior = new CodexJournalGoals(journal.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
for (const state of scenario.beforeResume) {
|
||||
send(prior, state)
|
||||
}
|
||||
@@ -329,7 +344,9 @@ describe('codex goal lifecycle resume', () => {
|
||||
prior.dispose()
|
||||
journal.unbind()
|
||||
|
||||
const resumed = new CodexJournalGoals(journal.sink, () => ({}))
|
||||
const resumed = new CodexJournalGoals(journal.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
resumed.handle({
|
||||
threadId: THREAD,
|
||||
method: scenario.resumed.method,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
@@ -93,10 +94,10 @@ describe('codex goal accounting revisions', () => {
|
||||
await journal.appendItem(
|
||||
{ provider: 'orca', clientMessageId: 'earlier' },
|
||||
{ kind: 'status', text: 'Context compacted' },
|
||||
{ fence: 1 }
|
||||
{ fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
const { sink, drained, subscribe, published } = journalSink(journal)
|
||||
const goals = new CodexJournalGoals(sink, () => ({}))
|
||||
const goals = new CodexJournalGoals(sink, () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE }))
|
||||
|
||||
goals.handle({ threadId: THREAD, method: 'thread/goal/updated', params: goalFrame() })
|
||||
await drained()
|
||||
@@ -104,7 +105,7 @@ describe('codex goal accounting revisions', () => {
|
||||
await journal.appendItem(
|
||||
{ provider: 'orca', clientMessageId: 'later' },
|
||||
{ kind: 'status', text: 'Something after the goal' },
|
||||
{ fence: 1 }
|
||||
{ fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
subscribe()
|
||||
|
||||
@@ -160,14 +161,18 @@ describe('codex goal accounting revisions', () => {
|
||||
root = await mkdtemp(join(tmpdir(), 'orca-goal-resume-revision-'))
|
||||
const journal = await journals.open({ identity: IDENTITY, journalDir: root })
|
||||
const first = journalSink(journal)
|
||||
const prior = new CodexJournalGoals(first.sink, () => ({}))
|
||||
const prior = new CodexJournalGoals(first.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
prior.handle({ threadId: THREAD, method: 'thread/goal/updated', params: goalFrame() })
|
||||
await first.drained()
|
||||
prior.dispose()
|
||||
const [created] = journal.snapshot().items
|
||||
|
||||
const second = journalSink(journal)
|
||||
const resumed = new CodexJournalGoals(second.sink, () => ({}))
|
||||
const resumed = new CodexJournalGoals(second.sink, () => ({
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
}))
|
||||
// Only a few seconds more: a resume snapshot still refreshes, since no live tick follows.
|
||||
const snapshot = goalFrame({ timeUsedSeconds: 3, updatedAt: 1789067991 })
|
||||
resumed.handle({ threadId: THREAD, method: 'thread/goal/updated', params: snapshot })
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
@@ -35,8 +36,11 @@ function frames(): {
|
||||
},
|
||||
publish: vi.fn()
|
||||
} as unknown as StructuredAgentSessionEventSink
|
||||
const goals = new CodexJournalGoals(sink, () => ({}))
|
||||
const generic = new CodexJournalGenericFrames({ sink, linkageFor: () => ({}) }, () => null)
|
||||
const goals = new CodexJournalGoals(sink, () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE }))
|
||||
const generic = new CodexJournalGenericFrames(
|
||||
{ sink, attributionFor: () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE }) },
|
||||
() => null
|
||||
)
|
||||
return {
|
||||
rows,
|
||||
frames: {
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
} from './codex-structured-journal-contracts'
|
||||
import { MAX_CODEX_GOAL_THREADS } from './codex-structured-journal-limits'
|
||||
import { appendCodexLifecycleTransition } from './codex-structured-journal-sink'
|
||||
import type { CodexRowLinkage } from './codex-subagent-linkage'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
|
||||
type GoalAccounting = { key: string; timeUsedSeconds: number; tokenBudget: number | null }
|
||||
|
||||
@@ -70,7 +70,7 @@ export class CodexJournalGoals {
|
||||
|
||||
constructor(
|
||||
private readonly sink: StructuredAgentSessionEventSink,
|
||||
private readonly linkageFor: CodexRowLinkage
|
||||
private readonly attributionFor: CodexRowAttribution
|
||||
) {}
|
||||
|
||||
handle(event: {
|
||||
@@ -132,7 +132,7 @@ export class CodexJournalGoals {
|
||||
event.method === 'thread/goal/cleared'
|
||||
),
|
||||
// A goal belongs to its thread, not to one run of it, so no turn is named.
|
||||
this.linkageFor(event.threadId, null)
|
||||
this.attributionFor(event.threadId, null)
|
||||
)
|
||||
if (!admission.accepted) {
|
||||
return admission
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalProducerLinkage
|
||||
AgentJournalRowAttribution
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { requiresTerminalSettlement } from '../native-chat/agent-session-journal/journal-terminal-settlement'
|
||||
import {
|
||||
@@ -31,7 +31,7 @@ import type { CodexActiveJournalItem } from './codex-structured-journal-settleme
|
||||
import { readCodexJournalString } from './codex-structured-journal-translation-values'
|
||||
import { readCodexTurnId } from './codex-structured-thread-facts'
|
||||
import { readCodexDispatchEcho } from './codex-structured-dispatch-echo'
|
||||
import type { CodexRowLinkage } from './codex-subagent-linkage'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
|
||||
export class CodexJournalItems {
|
||||
readonly ordinals = new CodexTurnOrdinals()
|
||||
@@ -44,7 +44,7 @@ export class CodexJournalItems {
|
||||
private readonly deps: Pick<
|
||||
CodexJournalTranslatorDeps,
|
||||
'sink' | 'coalesceMs' | 'maxRetainedBytes' | 'schedule'
|
||||
> & { maxMetadataBytes?: number; linkageFor: CodexRowLinkage },
|
||||
> & { maxMetadataBytes?: number; attributionFor: CodexRowAttribution },
|
||||
private readonly activeTurn: (threadId: string) => string | null,
|
||||
private readonly suppress: (threadId: string, turnId: string) => void
|
||||
) {
|
||||
@@ -56,7 +56,7 @@ export class CodexJournalItems {
|
||||
maxMetadataBytes: deps.maxMetadataBytes,
|
||||
turnIdFor: (threadId, params) => readCodexTurnId(params) ?? this.activeTurn(threadId),
|
||||
identityFor: (threadId, turnId, item) => this.identityFor(threadId, turnId, item),
|
||||
linkageFor: deps.linkageFor
|
||||
attributionFor: deps.attributionFor
|
||||
})
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ export class CodexJournalItems {
|
||||
event.method,
|
||||
identity,
|
||||
translated,
|
||||
this.deps.linkageFor(event.threadId, turnId)
|
||||
this.deps.attributionFor(event.threadId, turnId)
|
||||
)
|
||||
if (!admission.accepted) {
|
||||
return { handled: true, admission }
|
||||
@@ -151,17 +151,22 @@ export class CodexJournalItems {
|
||||
method: string,
|
||||
identity: AgentJournalItemIdentity,
|
||||
translated: ReturnType<typeof codexJournalItem>,
|
||||
linkage: AgentJournalProducerLinkage
|
||||
attribution: AgentJournalRowAttribution
|
||||
): CodexJournalTranslationAdmission {
|
||||
if (!translated.body) {
|
||||
return CODEX_JOURNAL_ADMITTED
|
||||
}
|
||||
if (method === 'item/completed') {
|
||||
const admission = appendCodexLifecycleItem(this.deps.sink, identity, translated.body, linkage)
|
||||
const admission = appendCodexLifecycleItem(
|
||||
this.deps.sink,
|
||||
identity,
|
||||
translated.body,
|
||||
attribution
|
||||
)
|
||||
return admission.accepted ? publishCodexLifecycle(this.deps.sink) : admission
|
||||
}
|
||||
const options = requiresTerminalSettlement(translated.body) ? { lifecycle: true } : {}
|
||||
const appendOptions = { ...options, ...linkage }
|
||||
const appendOptions = { ...options, ...attribution }
|
||||
const admission = this.deps.sink.tryAppendItem
|
||||
? this.deps.sink.tryAppendItem(identity, translated.body, appendOptions)
|
||||
: (this.deps.sink.appendItem(identity, translated.body, appendOptions),
|
||||
@@ -235,7 +240,7 @@ export class CodexJournalItems {
|
||||
this.deps.sink,
|
||||
evicted.identity,
|
||||
evictedActiveBody(translated),
|
||||
this.deps.linkageFor(evicted.threadId, evicted.turnId)
|
||||
this.deps.attributionFor(evicted.threadId, evicted.turnId)
|
||||
)
|
||||
if (!admission.accepted) {
|
||||
return admission
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
} from './codex-structured-journal-sink'
|
||||
import type { CodexPendingJournalPrompt } from './codex-structured-journal-settlement'
|
||||
import { readCodexTurnId } from './codex-structured-thread-facts'
|
||||
import type { CodexRowLinkage } from './codex-subagent-linkage'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
import { journalLifecycleItemMutation } from '../native-chat/agent-session-journal/journal-row-builders'
|
||||
|
||||
type CodexGroupedPendingJournalPrompt = CodexPendingJournalPrompt & { promptKey: string }
|
||||
@@ -30,7 +30,7 @@ export class CodexJournalPrompts {
|
||||
|
||||
constructor(
|
||||
private readonly deps: Pick<CodexJournalTranslatorDeps, 'sink' | 'bindPromptItemId'> & {
|
||||
linkageFor: CodexRowLinkage
|
||||
attributionFor: CodexRowAttribution
|
||||
},
|
||||
private readonly detailFor: (threadId: string, itemId: string) => string | null,
|
||||
private readonly activeTurn: (threadId: string) => string | null
|
||||
@@ -118,7 +118,7 @@ export class CodexJournalPrompts {
|
||||
)
|
||||
const mutations = group.flatMap(([, prompt]) => {
|
||||
const body = cancelledJournalPromptBody(prompt.body)
|
||||
const producer = this.deps.linkageFor(prompt.threadId, prompt.turnId)
|
||||
const producer = this.deps.attributionFor(prompt.threadId, prompt.turnId)
|
||||
return body ? [journalLifecycleItemMutation(producer, prompt.identity, body)] : []
|
||||
})
|
||||
const admission = appendCodexLifecycleMutations(
|
||||
@@ -152,7 +152,7 @@ export class CodexJournalPrompts {
|
||||
)}:${encodeURIComponent(event.promptKey)}`,
|
||||
items,
|
||||
// A child's approval arrives on the child's own thread, so it names the asker.
|
||||
this.deps.linkageFor(event.threadId, turnId)
|
||||
this.deps.attributionFor(event.threadId, turnId)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -170,7 +170,7 @@ export class CodexJournalPrompts {
|
||||
this.deps.sink,
|
||||
evicted.identity,
|
||||
cancelled,
|
||||
this.deps.linkageFor(evicted.threadId, evicted.turnId)
|
||||
this.deps.attributionFor(evicted.threadId, evicted.turnId)
|
||||
)
|
||||
if (!admission.accepted) {
|
||||
return admission
|
||||
|
||||
@@ -2,10 +2,11 @@ import { describe, expect, it } from 'vitest'
|
||||
import type { AgentJournalRenderItem } from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import { nativeChatTurnFold } from '../../shared/native-chat-turn-fold'
|
||||
import { nativeChatRowTurnKeys } from '../../shared/native-chat-turn-grouping'
|
||||
import { nativeChatTurnMembership } from '../../shared/native-chat-turn-membership'
|
||||
import type { NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import { projectStructuredItemToNativeChat } from '../../shared/structured-agent-session-projection'
|
||||
import { selectStructuredAgentTurnBars } from '../../shared/structured-agent-session-turn-timing'
|
||||
import { JournalDerivedTurnScope } from '../native-chat/agent-session-journal/journal-derived-turn-scope'
|
||||
import { createCodexJournalTranslator } from './codex-structured-journal-translation'
|
||||
|
||||
const THREAD_ID = 'thread-abc'
|
||||
@@ -29,19 +30,25 @@ function historicalTurn(index: number): Record<string, unknown> {
|
||||
}
|
||||
}
|
||||
|
||||
/** What the journal hands a reader after a restore: rows in append order. */
|
||||
function restoredJournal(turnCount: number): AgentJournalRenderItem[] {
|
||||
/** What the journal hands a reader after a restore: rows in append order. With `statesScope`, each
|
||||
* row carries the turn scope the journal gives a row the translator writes without one. */
|
||||
function restoredJournal(turnCount: number, statesScope: boolean): AgentJournalRenderItem[] {
|
||||
const items: AgentJournalRenderItem[] = []
|
||||
const derived = new JournalDerivedTurnScope()
|
||||
const translator = createCodexJournalTranslator({
|
||||
sink: {
|
||||
appendItem: (identity, body) => {
|
||||
appendItem: (identity, body, options) => {
|
||||
const sequence = items.length + 1
|
||||
const itemId = agentJournalItemKey(identity)
|
||||
const turnScope = options.turnScope ?? derived.scopeFor(body)
|
||||
derived.observe(itemId, true, undefined, body)
|
||||
items.push({
|
||||
itemId: agentJournalItemKey(identity),
|
||||
itemId,
|
||||
revision: 1,
|
||||
body,
|
||||
sequence,
|
||||
observedAt: sequence
|
||||
observedAt: sequence,
|
||||
...(statesScope ? { turnScope } : {})
|
||||
})
|
||||
},
|
||||
appendTombstone: () => {},
|
||||
@@ -56,43 +63,50 @@ function restoredJournal(turnCount: number): AgentJournalRenderItem[] {
|
||||
}
|
||||
|
||||
describe('grouping a Codex thread restored from full history', () => {
|
||||
it('keeps each turn with its own rows and folds each to its own answer', () => {
|
||||
const items = restoredJournal(3)
|
||||
const bars = selectStructuredAgentTurnBars(items, [], null)
|
||||
const messages = items
|
||||
.map(projectStructuredItemToNativeChat)
|
||||
.filter((message): message is NativeChatMessage => message !== null)
|
||||
const turnKeys = nativeChatRowTurnKeys(messages, bars.turnKeysByItemId)
|
||||
const opener = (index: number): string => `codex:${THREAD_ID}:turn-${index}:0`
|
||||
it.each([
|
||||
['states each row’s turn', true],
|
||||
['states no scope', false]
|
||||
])(
|
||||
'keeps each turn with its own rows and folds each to its own answer on a host that %s',
|
||||
(_host, statesScope) => {
|
||||
const items = restoredJournal(3, statesScope)
|
||||
const bars = selectStructuredAgentTurnBars(items, [], null)
|
||||
const messages = items
|
||||
.map(projectStructuredItemToNativeChat)
|
||||
.filter((message): message is NativeChatMessage => message !== null)
|
||||
const { turnKeys } = nativeChatTurnMembership(messages, { items, submissions: [] })
|
||||
const opener = (index: number): string => `codex:${THREAD_ID}:turn-${index}:0`
|
||||
|
||||
expect(messages.map((message, index) => [message.role, turnKeys[index]])).toEqual([
|
||||
['user', opener(1)],
|
||||
['assistant', opener(1)],
|
||||
['assistant', opener(1)],
|
||||
['user', opener(2)],
|
||||
['assistant', opener(2)],
|
||||
['assistant', opener(2)],
|
||||
['user', opener(3)],
|
||||
['assistant', opener(3)],
|
||||
['assistant', opener(3)]
|
||||
])
|
||||
expect([...bars.settledTurns.keys()]).toEqual([opener(1), opener(2), opener(3)])
|
||||
|
||||
const { foldedRows } = nativeChatTurnFold({
|
||||
rows: messages.map((message, index) => ({
|
||||
turnKey: turnKeys[index],
|
||||
role: message.role,
|
||||
rendersProse: true,
|
||||
outlivesTurn: false
|
||||
})),
|
||||
settledTurnKeys: new Set(bars.settledTurns.keys()),
|
||||
expandedTurnKeys: new Set()
|
||||
})
|
||||
const visible = messages.filter((_, index) => !foldedRows.has(index))
|
||||
expect(visible.map((message) => message.blocks)).toEqual(
|
||||
['ask 1', 'answer 1', 'ask 2', 'answer 2', 'ask 3', 'answer 3'].map((text) => [
|
||||
{ type: 'text', text }
|
||||
expect(messages.map((message, index) => [message.role, turnKeys[index]])).toEqual([
|
||||
['user', opener(1)],
|
||||
['assistant', opener(1)],
|
||||
['assistant', opener(1)],
|
||||
['user', opener(2)],
|
||||
['assistant', opener(2)],
|
||||
['assistant', opener(2)],
|
||||
['user', opener(3)],
|
||||
['assistant', opener(3)],
|
||||
['assistant', opener(3)]
|
||||
])
|
||||
)
|
||||
})
|
||||
expect([...bars.settledTurns.keys()]).toEqual([opener(1), opener(2), opener(3)])
|
||||
|
||||
const { foldedRows } = nativeChatTurnFold({
|
||||
rows: messages.map((message, index) => ({
|
||||
turnKey: turnKeys[index],
|
||||
role: message.role,
|
||||
rendersProse: true,
|
||||
outlivesTurn: false,
|
||||
reportsTurnOutcome: false
|
||||
})),
|
||||
settledTurnKeys: new Set(bars.settledTurns.keys()),
|
||||
expandedTurnKeys: new Set()
|
||||
})
|
||||
const visible = messages.filter((_, index) => !foldedRows.has(index))
|
||||
expect(visible.map((message) => message.blocks)).toEqual(
|
||||
['ask 1', 'answer 1', 'ask 2', 'answer 2', 'ask 3', 'answer 3'].map((text) => [
|
||||
{ type: 'text', text }
|
||||
])
|
||||
)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalTurnLifecycle
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalItemBody,
|
||||
type AgentJournalItemIdentity,
|
||||
type AgentJournalTurnLifecycle
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import {
|
||||
journalLifecycleItemMutation,
|
||||
@@ -26,7 +27,7 @@ import {
|
||||
codexTurnLifecycleIdentity
|
||||
} from './codex-structured-journal-translation-turns'
|
||||
import { appendCodexLifecycleMutations } from './codex-structured-journal-sink'
|
||||
import type { CodexRowLinkage } from './codex-subagent-linkage'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
|
||||
export type CodexActiveJournalItem = {
|
||||
threadId: string
|
||||
@@ -53,9 +54,10 @@ export function settleCodexJournalSession(input: {
|
||||
currentTurnIds: ReadonlyMap<string, ReadonlySet<string>>
|
||||
primaryThreadId: string | null
|
||||
ordinals: CodexTurnOrdinals
|
||||
/** Terminal lifecycle for a turn the provider left running when it ended. */
|
||||
settledTurnLifecycle: (threadId: string, turnId: string) => AgentJournalTurnLifecycle
|
||||
linkageFor: CodexRowLinkage
|
||||
/** Terminal lifecycle for a turn the provider left running when it ended; null for a turn a
|
||||
* conversation command claimed, whose record the host settles. */
|
||||
settledTurnLifecycle: (threadId: string, turnId: string) => AgentJournalTurnLifecycle | null
|
||||
attributionFor: CodexRowAttribution
|
||||
}): StructuredAgentSessionSinkAdmission {
|
||||
// Rows from every thread settle in this one batch, so each names its own producer.
|
||||
const mutations: JournalLifecycleMutationInput[] = []
|
||||
@@ -67,13 +69,13 @@ export function settleCodexJournalSession(input: {
|
||||
: codexJournalItem(active.item)
|
||||
const body = interruptedBody(translated.body)
|
||||
if (body) {
|
||||
mutations.push(settledRow(input.linkageFor, active, body))
|
||||
mutations.push(settledRow(input.attributionFor, active, body))
|
||||
}
|
||||
}
|
||||
for (const prompt of input.pendingPrompts.values()) {
|
||||
const body = cancelledJournalPromptBody(prompt.body)
|
||||
if (body) {
|
||||
mutations.push(settledRow(input.linkageFor, prompt, body))
|
||||
mutations.push(settledRow(input.attributionFor, prompt, body))
|
||||
}
|
||||
}
|
||||
for (const [threadId, turnIds] of input.currentTurnIds) {
|
||||
@@ -81,11 +83,15 @@ export function settleCodexJournalSession(input: {
|
||||
continue
|
||||
}
|
||||
for (const turnId of turnIds) {
|
||||
mutations.push({
|
||||
kind: 'item',
|
||||
identity: codexTurnLifecycleIdentity(input.event.sessionId, turnId),
|
||||
body: codexTurnLifecycleBody(input.settledTurnLifecycle(threadId, turnId))
|
||||
})
|
||||
const turnLifecycle = input.settledTurnLifecycle(threadId, turnId)
|
||||
if (turnLifecycle) {
|
||||
mutations.push({
|
||||
kind: 'item',
|
||||
identity: codexTurnLifecycleIdentity(input.event.sessionId, turnId),
|
||||
body: codexTurnLifecycleBody(turnLifecycle),
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
}
|
||||
turnOrdinalsToForget.push({ threadId, turnId })
|
||||
}
|
||||
}
|
||||
@@ -114,7 +120,9 @@ export function settleCodexJournalTurn(input: {
|
||||
activeItems: Map<string, CodexActiveJournalItem>
|
||||
pendingPrompts?: Map<string, CodexPendingJournalPrompt>
|
||||
clearPromptTurn?: (threadId: string, turnId: string) => void
|
||||
linkageFor: CodexRowLinkage
|
||||
attributionFor: CodexRowAttribution
|
||||
/** The end of a conversation command the turn carried, which settles with it. */
|
||||
commandEnd?: readonly JournalLifecycleMutationInput[]
|
||||
}): StructuredAgentSessionSinkAdmission {
|
||||
const mutations: JournalLifecycleMutationInput[] = []
|
||||
const activeItemsToForget: { key: string; threadId: string; itemId: string }[] = []
|
||||
@@ -133,7 +141,7 @@ export function settleCodexJournalTurn(input: {
|
||||
: codexJournalItem(active.item)
|
||||
const body = interruptedBody(translated.body)
|
||||
if (body) {
|
||||
mutations.push(settledRow(input.linkageFor, active, body))
|
||||
mutations.push(settledRow(input.attributionFor, active, body))
|
||||
}
|
||||
activeItemsToForget.push({ key, threadId: active.threadId, itemId: active.item.id })
|
||||
}
|
||||
@@ -143,7 +151,7 @@ export function settleCodexJournalTurn(input: {
|
||||
}
|
||||
const body = cancelledJournalPromptBody(prompt.body)
|
||||
if (body) {
|
||||
mutations.push(settledRow(input.linkageFor, prompt, body))
|
||||
mutations.push(settledRow(input.attributionFor, prompt, body))
|
||||
}
|
||||
pendingPromptsToForget.push(key)
|
||||
}
|
||||
@@ -152,9 +160,11 @@ export function settleCodexJournalTurn(input: {
|
||||
mutations.push({
|
||||
kind: 'item',
|
||||
identity: codexTurnLifecycleIdentity(input.sessionId, input.turnId),
|
||||
body: codexTurnLifecycleBody(input.turnLifecycle)
|
||||
body: codexTurnLifecycleBody(input.turnLifecycle),
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
}
|
||||
mutations.push(...(input.commandEnd ?? []))
|
||||
const admission = appendCodexLifecycleMutations(
|
||||
input.sink,
|
||||
`turn-completed:${input.sessionId}:${input.threadId}:${input.turnId}`,
|
||||
@@ -176,11 +186,11 @@ export function settleCodexJournalTurn(input: {
|
||||
|
||||
/** A settled item or prompt, naming its producer: the settlement can be the row's first write. */
|
||||
function settledRow(
|
||||
linkageFor: CodexRowLinkage,
|
||||
attributionFor: CodexRowAttribution,
|
||||
row: { threadId: string; turnId: string | null; identity: AgentJournalItemIdentity },
|
||||
body: AgentJournalItemBody
|
||||
): JournalLifecycleMutationInput {
|
||||
return journalLifecycleItemMutation(linkageFor(row.threadId, row.turnId), row.identity, body)
|
||||
return journalLifecycleItemMutation(attributionFor(row.threadId, row.turnId), row.identity, body)
|
||||
}
|
||||
|
||||
function interruptedBody(body: AgentJournalItemBody | null): AgentJournalItemBody | null {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalProducerLinkage
|
||||
AgentJournalRowAttribution
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import type {
|
||||
StructuredAgentSessionAppendOptions,
|
||||
StructuredAgentSessionItemAppendOptions,
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionLifecycleIdentityResolver,
|
||||
StructuredAgentSessionSinkAdmission
|
||||
@@ -35,7 +35,11 @@ export function appendCodexLifecycleMutations(
|
||||
} else {
|
||||
for (const mutation of chunk) {
|
||||
if (mutation.kind === 'item') {
|
||||
const options = { lifecycle: true, ...mutation.linkage }
|
||||
const options = {
|
||||
lifecycle: true,
|
||||
...mutation.linkage,
|
||||
turnScope: mutation.turnScope
|
||||
}
|
||||
if (sink.tryAppendItem) {
|
||||
admission = sink.tryAppendItem(mutation.identity, mutation.body, options)
|
||||
if (!admission.accepted) {
|
||||
@@ -74,7 +78,7 @@ export function appendCodexItemAndPublish(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
identity: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody,
|
||||
options: StructuredAgentSessionAppendOptions
|
||||
options: StructuredAgentSessionItemAppendOptions
|
||||
): StructuredAgentSessionSinkAdmission {
|
||||
const admission = sink.tryAppendItem
|
||||
? sink.tryAppendItem(identity, body, options)
|
||||
@@ -95,9 +99,9 @@ export function appendCodexLifecycleItem(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
identity: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody,
|
||||
linkage: AgentJournalProducerLinkage
|
||||
attribution: AgentJournalRowAttribution
|
||||
): CodexJournalTranslationAdmission {
|
||||
const options = { lifecycle: true, ...linkage }
|
||||
const options = { lifecycle: true, ...attribution }
|
||||
if (sink.tryAppendItem) {
|
||||
return criticalAdmission(sink.tryAppendItem(identity, body, options))
|
||||
}
|
||||
@@ -110,14 +114,14 @@ export function appendCodexLifecycleTransition(
|
||||
identitySizeBound: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody,
|
||||
resolveIdentity: StructuredAgentSessionLifecycleIdentityResolver,
|
||||
linkage: AgentJournalProducerLinkage
|
||||
attribution: AgentJournalRowAttribution
|
||||
): CodexJournalTranslationAdmission {
|
||||
if (sink.tryAppendLifecycleTransition) {
|
||||
return criticalAdmission(
|
||||
sink.tryAppendLifecycleTransition(identitySizeBound, body, resolveIdentity, linkage)
|
||||
sink.tryAppendLifecycleTransition(identitySizeBound, body, resolveIdentity, attribution)
|
||||
)
|
||||
}
|
||||
const admission = appendCodexLifecycleItem(sink, identitySizeBound, body, linkage)
|
||||
const admission = appendCodexLifecycleItem(sink, identitySizeBound, body, attribution)
|
||||
return admission.accepted ? publishCodexLifecycle(sink) : admission
|
||||
}
|
||||
|
||||
@@ -136,7 +140,7 @@ export function admitCodexLifecycleItems(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
settlementId: string,
|
||||
items: readonly Pick<CodexPendingJournalPrompt, 'identity' | 'body'>[],
|
||||
linkage: AgentJournalProducerLinkage
|
||||
attribution: AgentJournalRowAttribution
|
||||
): CodexJournalTranslationAdmission {
|
||||
if (items.length === 0) {
|
||||
return { accepted: false, reason: 'untranslated' }
|
||||
@@ -145,14 +149,14 @@ export function admitCodexLifecycleItems(
|
||||
const admission = criticalAdmission(
|
||||
sink.tryAppendLifecycleBatch(
|
||||
settlementId,
|
||||
items.map((item) => journalLifecycleItemMutation(linkage, item.identity, item.body)),
|
||||
items.map((item) => journalLifecycleItemMutation(attribution, item.identity, item.body)),
|
||||
{ lifecycle: true }
|
||||
)
|
||||
)
|
||||
return admission.accepted ? publishCodexLifecycle(sink) : admission
|
||||
}
|
||||
for (const item of items) {
|
||||
const admission = appendCodexLifecycleItem(sink, item.identity, item.body, linkage)
|
||||
const admission = appendCodexLifecycleItem(sink, item.identity, item.body, attribution)
|
||||
if (!admission.accepted) {
|
||||
return admission
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { AgentJournalRenderItem } from '../../shared/agent-session-journal-types'
|
||||
import { selectStructuredAgentTurnActivity } from '../../shared/native-chat-turn-activity'
|
||||
import { latestStructuredAgentSessionAssistantMessage } from '../../shared/structured-agent-session-projection'
|
||||
import { latestStructuredAgentSessionAssistantMessage } from '../../shared/structured-agent-session-latest-request'
|
||||
import {
|
||||
isStructuredAgentSessionThinking,
|
||||
statusStructuredAgentSessionToolCall
|
||||
|
||||
@@ -551,7 +551,8 @@ describe('codex journal translation', () => {
|
||||
userItemId: `codex:${THREAD_ID}:${TURN_ID}:0`,
|
||||
startedAt: expect.any(Number),
|
||||
completedAt: expect.any(Number)
|
||||
}
|
||||
},
|
||||
turnScope: { kind: 'thread' }
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ import type {
|
||||
AgentJournalTurnLifecycle,
|
||||
AgentJournalTurnOutcome
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-item-key'
|
||||
import {
|
||||
agentJournalItemKey,
|
||||
agentJournalSubmissionKey
|
||||
} from '../../shared/agent-session-journal-item-key'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
|
||||
import {
|
||||
CODEX_JOURNAL_ADMITTED,
|
||||
@@ -27,7 +30,10 @@ import {
|
||||
readCodexTurnId,
|
||||
readCodexTurnStatus
|
||||
} from './codex-structured-thread-facts'
|
||||
import type { CodexRowLinkage } from './codex-subagent-linkage'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
import type { CodexJournalCommandTurn } from './codex-journal-command-turn'
|
||||
import { readRecord, readString } from './codex-item-field-readers'
|
||||
import { recordCodexCommandTurnClaim } from './codex-command-turn-claim'
|
||||
|
||||
type TurnBoundaryEvent = {
|
||||
sessionId: string
|
||||
@@ -59,7 +65,8 @@ export class CodexJournalTurnBoundaries {
|
||||
clearPromptTurn?: (threadId: string, turnId: string) => void
|
||||
flushSuppression: () => CodexJournalTranslationAdmission
|
||||
resetActivity: (threadId: string) => void
|
||||
linkageFor: CodexRowLinkage
|
||||
attributionFor: CodexRowAttribution
|
||||
commands: CodexJournalCommandTurn
|
||||
now?: () => number
|
||||
}
|
||||
) {}
|
||||
@@ -73,15 +80,20 @@ export class CodexJournalTurnBoundaries {
|
||||
return { accepted: false, reason: 'backpressure' }
|
||||
}
|
||||
const startedAt = this.receiptTime(event)
|
||||
const admission = publishCodexTurnLifecycle({
|
||||
sink: this.deps.sink,
|
||||
primaryThreadId: this.deps.primaryThreadId(),
|
||||
sessionId: event.sessionId,
|
||||
threadId: event.threadId,
|
||||
turnId,
|
||||
state: 'running',
|
||||
startedAt
|
||||
})
|
||||
const command =
|
||||
event.threadId === this.deps.primaryThreadId() ? this.deps.commands.claim(turnId) : null
|
||||
// The command's turn is the record: this turn writes none, and its rows join the command's.
|
||||
const admission = command
|
||||
? recordCodexCommandTurnClaim(this.deps.sink, agentJournalItemKey(command.identity), turnId)
|
||||
: publishCodexTurnLifecycle({
|
||||
sink: this.deps.sink,
|
||||
primaryThreadId: this.deps.primaryThreadId(),
|
||||
sessionId: event.sessionId,
|
||||
threadId: event.threadId,
|
||||
turnId,
|
||||
state: 'running',
|
||||
startedAt
|
||||
})
|
||||
if (admission.accepted) {
|
||||
this.deps.activeTurns.remember(
|
||||
event.threadId,
|
||||
@@ -156,15 +168,20 @@ export class CodexJournalTurnBoundaries {
|
||||
// turn boundary is no evidence contact was lost. Only `settleSession` may
|
||||
// write `unverifiable`.
|
||||
const status = readCodexTurnStatus(event.params)
|
||||
const turnLifecycle =
|
||||
event.threadId === this.deps.primaryThreadId()
|
||||
? this.settled(event.threadId, turnId, {
|
||||
state: codexTurnLifecycleState(status),
|
||||
outcome: codexTurnOutcome(status),
|
||||
completedAt: this.receiptTime(event),
|
||||
durationMs: readCodexTurnDurationMs(event.params)
|
||||
})
|
||||
: null
|
||||
const completedAt = this.receiptTime(event)
|
||||
const commandEnd = this.deps.commands.end(turnId, {
|
||||
status,
|
||||
error: readString(readRecord(readRecord(readRecord(event.params).turn).error), 'message'),
|
||||
completedAt
|
||||
})
|
||||
const turnLifecycle = this.ownsRecord(event.threadId, turnId)
|
||||
? this.settled(event.threadId, turnId, {
|
||||
state: codexTurnLifecycleState(status),
|
||||
outcome: codexTurnOutcome(status),
|
||||
completedAt,
|
||||
durationMs: readCodexTurnDurationMs(event.params)
|
||||
})
|
||||
: null
|
||||
const requestOrigin = this.deps.activeTurns.requestOrigin(event.threadId, turnId)
|
||||
const latestDispatchSequence = this.deps.activeTurns.latestDispatchSequence(
|
||||
event.threadId,
|
||||
@@ -180,7 +197,8 @@ export class CodexJournalTurnBoundaries {
|
||||
activeItems: this.deps.items.activeItems,
|
||||
pendingPrompts: this.deps.pendingPrompts,
|
||||
...(this.deps.clearPromptTurn ? { clearPromptTurn: this.deps.clearPromptTurn } : {}),
|
||||
linkageFor: this.deps.linkageFor
|
||||
attributionFor: this.deps.attributionFor,
|
||||
commandEnd
|
||||
})
|
||||
if (admission.accepted) {
|
||||
if (turnLifecycle) {
|
||||
@@ -193,6 +211,7 @@ export class CodexJournalTurnBoundaries {
|
||||
}
|
||||
this.deps.items.ordinals.forgetTurn(event.threadId, turnId)
|
||||
this.deps.activeTurns.forget(event.threadId, turnId)
|
||||
this.deps.commands.settled(turnId)
|
||||
this.deps.resetActivity(event.threadId)
|
||||
}
|
||||
return admission
|
||||
@@ -216,9 +235,15 @@ export class CodexJournalTurnBoundaries {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this translator writes the turn's record: a primary turn no command claimed. */
|
||||
ownsRecord(threadId: string, turnId: string): boolean {
|
||||
return threadId === this.deps.primaryThreadId() && !this.deps.commands.isCarrying(turnId)
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.deps.activeTurns.clear()
|
||||
this.recentTurns.clear()
|
||||
this.deps.commands.clear()
|
||||
}
|
||||
|
||||
private receiptTime(event: TurnBoundaryEvent): number {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type {
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalTurnItem,
|
||||
AgentJournalTurnLifecycle,
|
||||
AgentJournalTurnLifecycleState,
|
||||
AgentJournalTurnOutcome
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalItemIdentity,
|
||||
type AgentJournalTurnItem,
|
||||
type AgentJournalTurnLifecycle,
|
||||
type AgentJournalTurnLifecycleState,
|
||||
type AgentJournalTurnOutcome
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
|
||||
import { agentJournalTurnBody } from '../../shared/agent-session-turn-record'
|
||||
@@ -109,6 +110,7 @@ export function publishCodexTurnLifecycle(input: {
|
||||
// The running row's `ts` is the host's turn-start receipt so clients can anchor a live counter.
|
||||
const appendOptions = {
|
||||
lifecycle: true,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE,
|
||||
...(input.state === 'running' && input.startedAt !== undefined
|
||||
? { observedAt: input.startedAt }
|
||||
: {})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// The translator's writers, built once. Split out so the translator reads as
|
||||
// routing, and so one place shows that every writer is handed the same
|
||||
// producer resolver: the roster's, which knows each child thread.
|
||||
// row attribution: the roster's producer, which knows each child thread, and the turn scope.
|
||||
|
||||
import { CodexJournalCompactions } from './codex-structured-journal-compactions'
|
||||
import type { CodexJournalTranslatorDeps } from './codex-structured-journal-contracts'
|
||||
@@ -9,31 +9,50 @@ import { CodexJournalGoals } from './codex-structured-journal-goals'
|
||||
import { CodexJournalItems } from './codex-structured-journal-items'
|
||||
import { CodexJournalPrompts } from './codex-structured-journal-prompts'
|
||||
import { CodexJournalActiveTurns } from './codex-structured-journal-translation-turn-state'
|
||||
import { CodexJournalTurnScopes } from './codex-journal-turn-scopes'
|
||||
import { CodexJournalCommandTurn } from './codex-journal-command-turn'
|
||||
import { CodexSubagentRoster } from './codex-subagent-roster'
|
||||
import type { CodexRowAttribution } from './codex-subagent-linkage'
|
||||
|
||||
export function createCodexJournalTranslatorWriters(deps: CodexJournalTranslatorDeps) {
|
||||
const activeTurns = new CodexJournalActiveTurns()
|
||||
const activeTurn = (threadId: string): string | null => activeTurns.current(threadId)
|
||||
const primaryThreadId = (): string | null => deps.primaryThreadId?.() ?? null
|
||||
const commands = new CodexJournalCommandTurn()
|
||||
const turnScopes = new CodexJournalTurnScopes({
|
||||
sessionId: deps.sessionId,
|
||||
primaryThreadId,
|
||||
activeTurn,
|
||||
commandScope: (turnId) => commands.scopeFor(turnId)
|
||||
})
|
||||
const subagents = new CodexSubagentRoster({
|
||||
sink: deps.sink,
|
||||
primaryThreadId: () => deps.primaryThreadId?.() ?? null,
|
||||
primaryThreadId,
|
||||
activeTurn,
|
||||
turnScopeFor: (threadId, turnId) => turnScopes.scopeFor(threadId, turnId),
|
||||
...(deps.subagentExecutions ? { executions: deps.subagentExecutions } : {})
|
||||
})
|
||||
const { linkageFor } = subagents.linkage
|
||||
const producerDeps = { ...deps, linkageFor }
|
||||
const attributionFor: CodexRowAttribution = (threadId, turnId) => ({
|
||||
...linkageFor(threadId, turnId),
|
||||
turnScope: turnScopes.scopeFor(threadId, turnId)
|
||||
})
|
||||
const producerDeps = { ...deps, attributionFor }
|
||||
const genericFrames = new CodexJournalGenericFrames(producerDeps, activeTurn)
|
||||
const items = new CodexJournalItems(producerDeps, activeTurn, (threadId, turnId) =>
|
||||
genericFrames.suppress(threadId, turnId)
|
||||
)
|
||||
return {
|
||||
activeTurns,
|
||||
commands,
|
||||
subagents,
|
||||
linkageFor,
|
||||
attributionFor,
|
||||
genericFrames,
|
||||
items,
|
||||
compactions: new CodexJournalCompactions(deps.sink, activeTurn, linkageFor),
|
||||
goals: new CodexJournalGoals(deps.sink, linkageFor),
|
||||
compactions: new CodexJournalCompactions(deps.sink, activeTurn, attributionFor, (turnId) =>
|
||||
commands.compacted(turnId)
|
||||
),
|
||||
goals: new CodexJournalGoals(deps.sink, attributionFor),
|
||||
prompts: new CodexJournalPrompts(
|
||||
producerDeps,
|
||||
(threadId, itemId) => items.detailFor(threadId, itemId),
|
||||
|
||||
@@ -35,8 +35,17 @@ export {
|
||||
export function createCodexJournalTranslator(
|
||||
deps: CodexJournalTranslatorDeps
|
||||
): CodexJournalTranslator {
|
||||
const { activeTurns, subagents, linkageFor, genericFrames, items, compactions, goals, prompts } =
|
||||
createCodexJournalTranslatorWriters(deps)
|
||||
const {
|
||||
activeTurns,
|
||||
commands,
|
||||
subagents,
|
||||
attributionFor,
|
||||
genericFrames,
|
||||
items,
|
||||
compactions,
|
||||
goals,
|
||||
prompts
|
||||
} = createCodexJournalTranslatorWriters(deps)
|
||||
const flushStreams = (): CodexJournalTranslationAdmission =>
|
||||
items.streams.flush() ? CODEX_JOURNAL_ADMITTED : { accepted: false, reason: 'backpressure' }
|
||||
let readActivity = createCodexProviderActivityReader()
|
||||
@@ -55,7 +64,8 @@ export function createCodexJournalTranslator(
|
||||
...(deps.clearPromptTurn ? { clearPromptTurn: deps.clearPromptTurn } : {}),
|
||||
flushSuppression: () => genericFrames.flush(),
|
||||
resetActivity,
|
||||
linkageFor,
|
||||
attributionFor,
|
||||
commands,
|
||||
...(deps.now ? { now: deps.now } : {})
|
||||
})
|
||||
let primaryThreadStoppedRunning = false
|
||||
@@ -150,11 +160,13 @@ export function createCodexJournalTranslator(
|
||||
// The host saw the child go, not what Codex made of the turn, so the row
|
||||
// carries no outcome: the end is observed, the verdict is unknown.
|
||||
settledTurnLifecycle: (threadId, turnId) =>
|
||||
turnBoundaries.settled(threadId, turnId, {
|
||||
state: 'interrupted',
|
||||
completedAt: event.observedAt ?? deps.now?.() ?? Date.now()
|
||||
}),
|
||||
linkageFor
|
||||
turnBoundaries.ownsRecord(threadId, turnId)
|
||||
? turnBoundaries.settled(threadId, turnId, {
|
||||
state: 'interrupted',
|
||||
completedAt: event.observedAt ?? deps.now?.() ?? Date.now()
|
||||
})
|
||||
: null,
|
||||
attributionFor
|
||||
})
|
||||
if (!admission.accepted) {
|
||||
return admission
|
||||
@@ -253,8 +265,14 @@ export function createCodexJournalTranslator(
|
||||
event.params,
|
||||
event.threadId
|
||||
)
|
||||
if (unhandled.accepted && event.method === 'error') {
|
||||
commands.errorShown(event.params)
|
||||
}
|
||||
return publishActivity(event, unhandled)
|
||||
},
|
||||
beginCommand: (command) => commands.begin(command),
|
||||
forgetCommand: (turnId) => commands.forget(turnId),
|
||||
commandProviderTurnId: (turnId) => commands.providerTurnId(turnId),
|
||||
cancelPrompt: (journalItemId) => prompts.cancel(journalItemId),
|
||||
resolvePrompt: (journalItemId) => prompts.resolve(journalItemId),
|
||||
flush: () => {
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
type AgentSessionCancelOutcome,
|
||||
type StructuredAgentSessionAdapter
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import type { StructuredSessionCompaction } from '../native-chat/agent-session-wire/structured-session-compaction'
|
||||
import {
|
||||
answerCodexPrompt,
|
||||
prepareCodexPromptAnswer,
|
||||
@@ -17,6 +16,11 @@ import type { CodexStructuredTurnCancellation } from './codex-structured-turn-ca
|
||||
type CancelInput = Parameters<StructuredAgentSessionAdapter['cancelTurn']>[0]
|
||||
type AnswerInput = Parameters<StructuredAgentSessionAdapter['answerPrompt']>[0]
|
||||
|
||||
/** A command's Stop interrupts the provider turn carrying it; any other turn is its own. */
|
||||
function providerTurnId(session: CodexSession, turnId: string): string | undefined {
|
||||
return session.translator ? session.translator.commandProviderTurnId(turnId) : turnId
|
||||
}
|
||||
|
||||
/** How long a Stop waits for Codex to open the turn it answered a send into. Under the quit
|
||||
* path's eviction budget, which a close or quit queued behind the Stop spends. */
|
||||
export const CODEX_STOP_TURN_OPEN_WAIT_MS = 5_000
|
||||
@@ -30,13 +34,13 @@ async function cancelCodexConversation(
|
||||
input: Parameters<typeof cancelCodexStructuredTurn>[0],
|
||||
session: CodexSession
|
||||
): Promise<AgentSessionCancelOutcome> {
|
||||
const { request, sessions, compactions, cancellation } = input
|
||||
const { request, sessions, cancellation } = input
|
||||
const liveTurnId = request.resolveLiveTurnId?.() ?? null
|
||||
// A turn the journal shows that Codex has not started yet (a compaction's) has nothing to stop.
|
||||
const turnId =
|
||||
liveTurnId === null
|
||||
? ([...(session.activeTurnIds ?? [])].at(-1) ?? (await openedAnsweredTurn(session)))
|
||||
: compactions.providerTurnId(request.sessionId, liveTurnId)
|
||||
: providerTurnId(session, liveTurnId)
|
||||
if (!turnId) {
|
||||
return { cancelled: false }
|
||||
}
|
||||
@@ -69,17 +73,16 @@ async function openedAnsweredTurn(session: CodexSession): Promise<string | null>
|
||||
export async function cancelCodexStructuredTurn(input: {
|
||||
request: CancelInput
|
||||
sessions: Map<string, CodexSession>
|
||||
compactions: StructuredSessionCompaction
|
||||
cancellation: CodexStructuredTurnCancellation
|
||||
}): Promise<AgentSessionCancelOutcome> {
|
||||
const { request, sessions, compactions, cancellation } = input
|
||||
const { request, sessions, cancellation } = input
|
||||
const session = requireLiveCodexSession(sessions, request.sessionId)
|
||||
const prompt = request.prompt
|
||||
const requestedTurnId = request.turnId
|
||||
if (requestedTurnId === undefined) {
|
||||
return prompt ? { cancelled: false } : cancelCodexConversation(input, session)
|
||||
}
|
||||
const turnId = compactions.providerTurnId(request.sessionId, requestedTurnId)
|
||||
const turnId = providerTurnId(session, requestedTurnId)
|
||||
if (!turnId) {
|
||||
return { cancelled: false }
|
||||
}
|
||||
@@ -103,7 +106,7 @@ export async function cancelCodexStructuredTurn(input: {
|
||||
!session.ended &&
|
||||
session.fence === request.fence &&
|
||||
session.acquisitionGeneration === acquisitionGeneration &&
|
||||
compactions.providerTurnId(request.sessionId, requestedTurnId) === turnId &&
|
||||
providerTurnId(session, requestedTurnId) === turnId &&
|
||||
session.prompts.ownsBoundClaim(claim, prompt.itemId, claim.prompt.threadId, promptTurnId)
|
||||
let interruptConfirmed = false
|
||||
try {
|
||||
|
||||
@@ -5,7 +5,10 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session-mutation-envelope'
|
||||
import type { AgentJournalRenderItem } from '../../shared/agent-session-journal-types'
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalRenderItem
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import {
|
||||
EMPTY_STRUCTURED_AGENT_SESSION,
|
||||
reduceStructuredAgentSession,
|
||||
@@ -125,7 +128,7 @@ function codexPrompts(): CodexJournalPrompts {
|
||||
throw new Error('session was never acquired')
|
||||
}
|
||||
return new CodexJournalPrompts(
|
||||
{ sink, linkageFor: () => ({}) },
|
||||
{ sink, attributionFor: () => ({ turnScope: AGENT_JOURNAL_THREAD_SCOPE }) },
|
||||
() => null,
|
||||
() => 'turn-1'
|
||||
)
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
reportedCodexThreadOptions
|
||||
} from './codex-structured-fast-mode'
|
||||
import {
|
||||
assertCodexConnectionOpen,
|
||||
codexSessionLifecycle,
|
||||
mintCodexAcquisitionGeneration,
|
||||
type CodexAcquisitionRegistry,
|
||||
@@ -41,6 +42,7 @@ import {
|
||||
type CodexStructuredSessionAdapterDeps
|
||||
} from './codex-structured-session-state'
|
||||
import type { CodexStructuredTurnCancellation } from './codex-structured-turn-cancellation'
|
||||
import type { CodexStructuredSessionTeardown } from './codex-structured-session-teardown'
|
||||
import type { CodexStructuredNotificationRetry } from './codex-structured-notification-retry'
|
||||
import type { deliverCodexServerRequest } from './codex-structured-provider-events'
|
||||
|
||||
@@ -64,12 +66,7 @@ export async function acquireCodexStructuredSession(input: {
|
||||
request: Parameters<typeof deliverCodexServerRequest>[2]
|
||||
) => void
|
||||
handleUnhandledFrame: (sessionId: string, kind: string, payload: unknown) => void
|
||||
forceCloseUnexpected: (
|
||||
sessionId: string,
|
||||
fence: number,
|
||||
acquisitionGeneration: string,
|
||||
reason: Error
|
||||
) => Promise<boolean>
|
||||
forceCloseUnexpected: CodexStructuredSessionTeardown['forceCloseUnexpected']
|
||||
}): Promise<AgentSessionAcquisition> {
|
||||
const {
|
||||
input: acquireInput,
|
||||
@@ -224,9 +221,7 @@ export async function acquireCodexStructuredSession(input: {
|
||||
}),
|
||||
acquisitionGeneration: mintCodexAcquisitionGeneration(deps)
|
||||
}
|
||||
if (connection.closed) {
|
||||
throw new Error(`codex app-server for session ${sessionId} exited while being acquired`)
|
||||
}
|
||||
assertCodexConnectionOpen(connection, sessionId)
|
||||
acquisitions.assertCurrent(sessionId, attempt)
|
||||
const options = restoredCodexSessionOptions(acquireInput.options)
|
||||
const catalogAccess = codexAcquireCatalogAccess(deps, launch)
|
||||
@@ -238,9 +233,7 @@ export async function acquireCodexStructuredSession(input: {
|
||||
timeoutMs: deps.requestTimeoutMs
|
||||
})
|
||||
acquisitions.assertCurrent(sessionId, attempt)
|
||||
if (connection.closed) {
|
||||
throw new Error(`codex app-server for session ${sessionId} exited while being acquired`)
|
||||
}
|
||||
assertCodexConnectionOpen(connection, sessionId)
|
||||
acquisitions.deleteIfCurrent(sessionId, attempt)
|
||||
// Where this session's child work goes: the host's records, after each frame is journaled.
|
||||
const sink = codexChildWorkSink(sessionId, deps)
|
||||
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
AgentJournalMessageItem,
|
||||
AgentSessionJournalIdentity
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import { StructuredSessionCompaction } from '../native-chat/agent-session-wire/structured-session-compaction'
|
||||
import { isCodexAppServerRequestError } from './codex-app-server-connection'
|
||||
import type {
|
||||
AgentSessionAcquisition,
|
||||
@@ -14,6 +13,7 @@ import type {
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-adapter'
|
||||
import type { CodexJournalTranslationAdmission } from './codex-structured-journal-translation'
|
||||
import { dispatchCodexTurn, isCodexTurnOptionKey } from './codex-structured-turn-start'
|
||||
import { agentSessionFailureFact, providerDiagnosticOf } from '../../shared/agent-session-failure'
|
||||
import { supportsCodexStructuredLocation } from './codex-structured-location-support'
|
||||
import { CodexStructuredSessionTeardown } from './codex-structured-session-teardown'
|
||||
import {
|
||||
@@ -34,7 +34,10 @@ import {
|
||||
translateCodexNotification
|
||||
} from './codex-structured-provider-events'
|
||||
import { CodexStructuredTurnCancellation } from './codex-structured-turn-cancellation'
|
||||
import { settleCodexSendsInEndedTurn } from './codex-structured-turn-end-settlement'
|
||||
import {
|
||||
codexDispatchRejection,
|
||||
settleCodexSendsInEndedTurn
|
||||
} from './codex-structured-turn-end-settlement'
|
||||
import { createCodexStructuredNotificationRetry } from './codex-structured-notification-retry'
|
||||
import { acquireCodexStructuredSession } from './codex-structured-session-acquire'
|
||||
import { changeCodexThreadGoal } from './codex-structured-thread-goal'
|
||||
@@ -50,7 +53,6 @@ export type {
|
||||
} from './codex-structured-session-state'
|
||||
|
||||
export class CodexStructuredSessionAdapter implements StructuredAgentSessionAdapter {
|
||||
private readonly compactions = new StructuredSessionCompaction()
|
||||
private readonly sessions = new Map<string, CodexSession>()
|
||||
private readonly acquisitions = new CodexAcquisitionRegistry()
|
||||
private readonly turnCancellation: CodexStructuredTurnCancellation
|
||||
@@ -154,7 +156,6 @@ export class CodexStructuredSessionAdapter implements StructuredAgentSessionAdap
|
||||
return admission
|
||||
}
|
||||
if (event.type === 'notification') {
|
||||
this.compactions.codex(event.sessionId, event.method, event.params)
|
||||
// Only an admitted turn end settles; a refused one settles on the retry that lands.
|
||||
settleCodexSendsInEndedTurn(session, event.method, event.params, (settlement) =>
|
||||
this.deps.onDispatchSettledLate?.({ sessionId: event.sessionId, ...settlement })
|
||||
@@ -167,9 +168,6 @@ export class CodexStructuredSessionAdapter implements StructuredAgentSessionAdap
|
||||
// After the journal and the parent's republished row, never ahead of either.
|
||||
session.backgroundTasks.publishChildWork()
|
||||
}
|
||||
if (event.type === 'ended') {
|
||||
this.compactions.ended(event.sessionId)
|
||||
}
|
||||
this.deps.onEvent?.(event)
|
||||
return admission
|
||||
}
|
||||
@@ -236,7 +234,6 @@ export class CodexStructuredSessionAdapter implements StructuredAgentSessionAdap
|
||||
cancelCodexStructuredTurn({
|
||||
request,
|
||||
sessions: this.sessions,
|
||||
compactions: this.compactions,
|
||||
cancellation: this.turnCancellation
|
||||
})
|
||||
|
||||
@@ -251,33 +248,31 @@ export class CodexStructuredSessionAdapter implements StructuredAgentSessionAdap
|
||||
recoverRewind: NonNullable<StructuredAgentSessionAdapter['recoverRewind']> = (input) =>
|
||||
codexRewind.recoverCodexRewind(this.session(input.sessionId), input, this.deps.requestTimeoutMs)
|
||||
|
||||
compact: NonNullable<StructuredAgentSessionAdapter['compact']> = (input) => {
|
||||
/** The ack is Codex's receipt; the translator ends the command's turn from the turn it opens. */
|
||||
compact: NonNullable<StructuredAgentSessionAdapter['compact']> = async (input) => {
|
||||
const session = this.session(input.sessionId)
|
||||
return this.compactions.run(
|
||||
input.sessionId,
|
||||
session.threadId,
|
||||
async () => {
|
||||
await this.turnCancellation.captureBaseline(session)
|
||||
return session.connection
|
||||
.request(
|
||||
'thread/compact/start',
|
||||
{ threadId: session.threadId },
|
||||
{ timeoutMs: this.deps.requestTimeoutMs }
|
||||
session.translator?.beginCommand(input.command)
|
||||
try {
|
||||
await this.turnCancellation.captureBaseline(session)
|
||||
await session.connection.request(
|
||||
'thread/compact/start',
|
||||
{ threadId: session.threadId },
|
||||
{ timeoutMs: this.deps.requestTimeoutMs }
|
||||
)
|
||||
return { state: 'accepted', providerIdentity: null }
|
||||
} catch (error) {
|
||||
session.translator?.forgetCommand(input.command.turnId)
|
||||
if (isCodexAppServerRequestError(error)) {
|
||||
// Codex's own words, when it gave any, are the one part of the error a person can use.
|
||||
return {
|
||||
state: 'rejected',
|
||||
...codexDispatchRejection(
|
||||
agentSessionFailureFact('providerRejected', { detail: providerDiagnosticOf(error) })
|
||||
)
|
||||
.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
if (isCodexAppServerRequestError(error)) {
|
||||
const detail = error.providerDiagnostic
|
||||
return { outcome: 'failed' as const, ...(detail ? { detail } : {}) }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
)
|
||||
},
|
||||
input.onLateResult,
|
||||
input.turnId
|
||||
)
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
changeThreadGoal: NonNullable<StructuredAgentSessionAdapter['changeThreadGoal']> = (input) =>
|
||||
|
||||
@@ -170,6 +170,16 @@ export function codexSessionLifecycle(
|
||||
}
|
||||
}
|
||||
|
||||
/** A child that exited while being acquired never becomes the session's. */
|
||||
export function assertCodexConnectionOpen(
|
||||
connection: Pick<CodexAppServerConnection, 'closed'>,
|
||||
sessionId: string
|
||||
): void {
|
||||
if (connection.closed) {
|
||||
throw new Error(`codex app-server for session ${sessionId} exited while being acquired`)
|
||||
}
|
||||
}
|
||||
|
||||
export function requireLiveCodexSession(
|
||||
sessions: Map<string, CodexSession>,
|
||||
sessionId: string
|
||||
|
||||
@@ -8,15 +8,18 @@
|
||||
// run are learned from the roster's executions, and a later revision of the
|
||||
// row picks them up when they arrive.
|
||||
|
||||
import type { AgentJournalProducerLinkage } from '../../shared/agent-session-journal-types'
|
||||
import type {
|
||||
AgentJournalProducerLinkage,
|
||||
AgentJournalRowAttribution
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import type { CodexSubagentExecutions } from './codex-subagent-executions'
|
||||
|
||||
/** Linkage for a row one thread produced, within one of that thread's turns
|
||||
* (null outside any). Every Codex write site resolves through this. */
|
||||
export type CodexRowLinkage = (
|
||||
/** Who produced a row one thread wrote within one of that thread's turns (null outside any),
|
||||
* and which turn the row belongs to. Every Codex write site resolves through this. */
|
||||
export type CodexRowAttribution = (
|
||||
threadId: string,
|
||||
turnId: string | null
|
||||
) => AgentJournalProducerLinkage
|
||||
) => AgentJournalRowAttribution
|
||||
|
||||
export class CodexSubagentLinkage {
|
||||
constructor(
|
||||
@@ -26,7 +29,7 @@ export class CodexSubagentLinkage {
|
||||
}
|
||||
) {}
|
||||
|
||||
linkageFor: CodexRowLinkage = (threadId, turnId) => {
|
||||
linkageFor = (threadId: string, turnId: string | null): AgentJournalProducerLinkage => {
|
||||
const primary = this.deps.primaryThreadId()
|
||||
// An unknown primary means the session's thread is still opening, and no
|
||||
// turn has run that could have spawned a child.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// One spawn group's roster state, and the ids its journal row is keyed on.
|
||||
|
||||
import type {
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalTurnScope
|
||||
} from '../../shared/agent-session-journal-types'
|
||||
import type { NativeChatSubagentEntry } from '../../shared/native-chat-types'
|
||||
|
||||
/** The turn a group belongs to when Codex reports activity outside any turn.
|
||||
* Mirrors the generic-frame bucket name so the two read alike in the journal. */
|
||||
export type RosterGroup = {
|
||||
groupId: string
|
||||
identity: AgentJournalItemIdentity
|
||||
/** The spawning turn's scope: the row reports its children beside that turn's work. */
|
||||
turnScope: AgentJournalTurnScope
|
||||
/** Insertion order is the display order; the map holds the state. */
|
||||
entries: Map<string, NativeChatSubagentEntry>
|
||||
executionTurns: Map<string, string | null>
|
||||
/** Times each label has been claimed, so a repeat gets an ordinal suffix. */
|
||||
labelCounts: Map<string, number>
|
||||
/** Last body written, so an idempotent replay writes no new revision. */
|
||||
lastSerialized: string | null
|
||||
}
|
||||
|
||||
/** Group identity: the parent turn that spawned the children. `agentPath` is a
|
||||
* tree rooted at the parent thread, so every child of one turn shares a row
|
||||
* no matter which thread's stream carried its activity item. */
|
||||
export function codexSubagentGroupId(threadId: string, turnId: string | null): string {
|
||||
return `${threadId}:${turnId ?? 'outside-turn'}`
|
||||
}
|
||||
|
||||
/** Durable journal identity for the group's row — stable across revisions and
|
||||
* across a restart, so replay finds the same row instead of appending a new one. */
|
||||
export function codexSubagentGroupIdentity(groupId: string): AgentJournalItemIdentity {
|
||||
return { provider: 'orca', clientMessageId: `codex-subagents:${groupId}` }
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isAdmissibleAgentJournalItemBody } from '../../shared/agent-session-journal-schemas'
|
||||
import type {
|
||||
@@ -43,6 +44,7 @@ function createHarness(options: { threadId?: string | null } = {}): {
|
||||
tryPublish: () => ({ accepted: true })
|
||||
}
|
||||
const roster = new CodexSubagentRoster({
|
||||
turnScopeFor: () => AGENT_JOURNAL_THREAD_SCOPE,
|
||||
sink,
|
||||
primaryThreadId: () => (options.threadId === undefined ? THREAD : options.threadId),
|
||||
activeTurn: () => TURN,
|
||||
@@ -138,6 +140,7 @@ function createCoalescingHarness(): {
|
||||
}
|
||||
}
|
||||
const roster = new CodexSubagentRoster({
|
||||
turnScopeFor: () => AGENT_JOURNAL_THREAD_SCOPE,
|
||||
sink,
|
||||
primaryThreadId: () => THREAD,
|
||||
activeTurn: () => TURN,
|
||||
@@ -668,6 +671,7 @@ describe('CodexSubagentRoster', () => {
|
||||
const published: number[] = []
|
||||
const refusal = { accepted: false, reason: 'backpressure' } as const
|
||||
const roster = new CodexSubagentRoster({
|
||||
turnScopeFor: () => AGENT_JOURNAL_THREAD_SCOPE,
|
||||
sink: {
|
||||
appendItem: () => {},
|
||||
appendTombstone: () => {},
|
||||
@@ -721,6 +725,7 @@ describe('CodexSubagentRoster', () => {
|
||||
const appended: Appended[] = []
|
||||
const published: number[] = []
|
||||
const roster = new CodexSubagentRoster({
|
||||
turnScopeFor: () => AGENT_JOURNAL_THREAD_SCOPE,
|
||||
sink: {
|
||||
appendItem: () => {},
|
||||
appendTombstone: () => {},
|
||||
@@ -765,6 +770,7 @@ describe('CodexSubagentRoster', () => {
|
||||
|
||||
it('propagates sink backpressure instead of reporting the row as written', () => {
|
||||
const roster = new CodexSubagentRoster({
|
||||
turnScopeFor: () => AGENT_JOURNAL_THREAD_SCOPE,
|
||||
sink: {
|
||||
appendItem: () => {},
|
||||
appendTombstone: () => {},
|
||||
|
||||
@@ -13,12 +13,9 @@
|
||||
// thread, and a real turn id is assumed freshly minted per turn. Seeding from
|
||||
// the journal is the fix.
|
||||
|
||||
import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types'
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session-journal-types'
|
||||
import { isTerminalSubagentState } from '../../shared/native-chat-subagent-summary'
|
||||
import type {
|
||||
NativeChatSubagentEntry,
|
||||
NativeChatSubagentState
|
||||
} from '../../shared/native-chat-types'
|
||||
import type { NativeChatSubagentState } from '../../shared/native-chat-types'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionSinkAdmission
|
||||
@@ -40,6 +37,12 @@ import { readCodexTurnId } from './codex-structured-thread-facts'
|
||||
import { codexSubagentGroupBody } from './codex-subagent-group-body'
|
||||
import { CodexSubagentLinkage } from './codex-subagent-linkage'
|
||||
export { codexSubagentGroupBody } from './codex-subagent-group-body'
|
||||
export { codexSubagentGroupId, codexSubagentGroupIdentity } from './codex-subagent-roster-state'
|
||||
import {
|
||||
codexSubagentGroupId,
|
||||
codexSubagentGroupIdentity,
|
||||
type RosterGroup
|
||||
} from './codex-subagent-roster-state'
|
||||
import type { CodexThreadItem } from './codex-structured-item-translation'
|
||||
import {
|
||||
MAX_CODEX_SUBAGENT_GROUPS,
|
||||
@@ -49,38 +52,12 @@ import {
|
||||
|
||||
const ADMITTED: StructuredAgentSessionSinkAdmission = { accepted: true }
|
||||
|
||||
/** The turn a group belongs to when Codex reports activity outside any turn.
|
||||
* Mirrors the generic-frame bucket name so the two read alike in the journal. */
|
||||
type RosterGroup = {
|
||||
groupId: string
|
||||
identity: AgentJournalItemIdentity
|
||||
/** Insertion order is the display order; the map holds the state. */
|
||||
entries: Map<string, NativeChatSubagentEntry>
|
||||
executionTurns: Map<string, string | null>
|
||||
/** Times each label has been claimed, so a repeat gets an ordinal suffix. */
|
||||
labelCounts: Map<string, number>
|
||||
/** Last body written, so an idempotent replay writes no new revision. */
|
||||
lastSerialized: string | null
|
||||
}
|
||||
|
||||
/** Group identity: the parent turn that spawned the children. `agentPath` is a
|
||||
* tree rooted at the parent thread, so every child of one turn shares a row
|
||||
* no matter which thread's stream carried its activity item. */
|
||||
export function codexSubagentGroupId(threadId: string, turnId: string | null): string {
|
||||
return `${threadId}:${turnId ?? 'outside-turn'}`
|
||||
}
|
||||
|
||||
/** Durable journal identity for the group's row — stable across revisions and
|
||||
* across a restart, so replay finds the same row instead of appending a new one. */
|
||||
export function codexSubagentGroupIdentity(groupId: string): AgentJournalItemIdentity {
|
||||
return { provider: 'orca', clientMessageId: `codex-subagents:${groupId}` }
|
||||
}
|
||||
|
||||
export type CodexSubagentRosterDeps = {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
/** The thread that owns the agent tree; falls back to the event's thread. */
|
||||
primaryThreadId: () => string | null
|
||||
activeTurn: (threadId: string) => string | null
|
||||
turnScopeFor: (threadId: string, turnId: string | null) => AgentJournalTurnScope
|
||||
now?: () => number
|
||||
executions?: CodexSubagentExecutions
|
||||
}
|
||||
@@ -280,6 +257,7 @@ export class CodexSubagentRoster {
|
||||
const group: RosterGroup = {
|
||||
groupId,
|
||||
identity: codexSubagentGroupIdentity(groupId),
|
||||
turnScope: this.deps.turnScopeFor(ownerThreadId, ownerTurnId),
|
||||
entries: new Map(),
|
||||
executionTurns: new Map(),
|
||||
labelCounts: new Map(),
|
||||
@@ -361,7 +339,10 @@ export class CodexSubagentRoster {
|
||||
// The publish must NOT reuse that key: the queue coalesces by key alone,
|
||||
// with no op-kind check, so a publish carrying it would splice out the
|
||||
// still-queued append and the row would never reach the journal.
|
||||
const options = { coalescingKey: `codex-subagents:${group.groupId}` }
|
||||
const options = {
|
||||
coalescingKey: `codex-subagents:${group.groupId}`,
|
||||
turnScope: group.turnScope
|
||||
}
|
||||
const admission = this.deps.sink.tryAppendItem
|
||||
? this.deps.sink.tryAppendItem(group.identity, body, options)
|
||||
: (this.deps.sink.appendItem(group.identity, body, options), ADMITTED)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types'
|
||||
// A repair drops what it cannot replay, and says so.
|
||||
//
|
||||
// Two things make a suffix unreplayable: a row this build cannot parse, and a
|
||||
@@ -102,9 +103,18 @@ afterEach(async () => {
|
||||
describe('a malformed row', () => {
|
||||
it('keeps the readable prefix live and drops the rest of the epoch', async () => {
|
||||
const journal = await open()
|
||||
await journal.appendItem(item(0), body('readable'), { fence: 1 })
|
||||
await journal.appendItem(item(1), body('unreadable'), { fence: 1 })
|
||||
await journal.appendItem(item(2), body('after the fault'), { fence: 1 })
|
||||
await journal.appendItem(item(0), body('readable'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await journal.appendItem(item(1), body('unreadable'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await journal.appendItem(item(2), body('after the fault'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await journal.close()
|
||||
await withJournalDatabase((db) => {
|
||||
db.prepare('UPDATE journal_rows SET row_json = ? WHERE seq = ?').run('{"not":"a row"}', 3)
|
||||
@@ -118,8 +128,14 @@ describe('a malformed row', () => {
|
||||
|
||||
it('discloses the line it could not read', async () => {
|
||||
const journal = await open()
|
||||
await journal.appendItem(item(0), body('readable'), { fence: 1 })
|
||||
await journal.appendItem(item(1), body('later'), { fence: 1 })
|
||||
await journal.appendItem(item(0), body('readable'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await journal.appendItem(item(1), body('later'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await journal.close()
|
||||
await withJournalDatabase((db) => {
|
||||
db.prepare('UPDATE journal_rows SET row_json = ? WHERE seq = ?').run('}{', 2)
|
||||
@@ -141,7 +157,10 @@ describe('a sequence gap', () => {
|
||||
it('drops every row after the hole and reports the epoch corrupt', async () => {
|
||||
const journal = await open()
|
||||
for (let ordinal = 0; ordinal < 5; ordinal += 1) {
|
||||
await journal.appendItem(item(ordinal), body(`m${ordinal}`), { fence: 1 })
|
||||
await journal.appendItem(item(ordinal), body(`m${ordinal}`), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
}
|
||||
await journal.close()
|
||||
// Sequence 1 is the epoch row, so the items occupy 2..6. Removing 4 leaves
|
||||
@@ -163,7 +182,10 @@ describe('a sequence gap', () => {
|
||||
it('still reports corrupt on the next probe, with the deleted suffix unrebuilt', async () => {
|
||||
const journal = await open()
|
||||
for (let ordinal = 0; ordinal < 5; ordinal += 1) {
|
||||
await journal.appendItem(item(ordinal), body(`m${ordinal}`), { fence: 1 })
|
||||
await journal.appendItem(item(ordinal), body(`m${ordinal}`), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
}
|
||||
await journal.close()
|
||||
await withJournalDatabase((db) => {
|
||||
@@ -177,7 +199,10 @@ describe('a sequence gap', () => {
|
||||
// Same policy the emptied-epoch repair takes: a session that writes into the
|
||||
// epoch owns it, and a later import must not replace rows the user has seen.
|
||||
const writable = await open()
|
||||
await writable.appendItem(item(9), body('typed after the repair'), { fence: 1 })
|
||||
await writable.appendItem(item(9), body('typed after the repair'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await writable.close()
|
||||
expect(loadJournal(root, IDENTITY.sessionId)).toMatchObject({ corrupt: false })
|
||||
})
|
||||
@@ -187,7 +212,10 @@ describe('a sequence gap', () => {
|
||||
it('is not settled by the repair disclosure it appends for a malformed row', async () => {
|
||||
const journal = await open()
|
||||
for (let ordinal = 0; ordinal < 3; ordinal += 1) {
|
||||
await journal.appendItem(item(ordinal), body(`m${ordinal}`), { fence: 1 })
|
||||
await journal.appendItem(item(ordinal), body(`m${ordinal}`), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
}
|
||||
await journal.close()
|
||||
await withJournalDatabase((db) => {
|
||||
@@ -207,7 +235,10 @@ describe('a missing epoch row', () => {
|
||||
// renders a repaired journal as a clean timeline.
|
||||
it('rejects the whole surviving range rather than declaring it contiguous', async () => {
|
||||
const journal = await open()
|
||||
await journal.appendItem(item(0), body('anchor'), { fence: 1 })
|
||||
await journal.appendItem(item(0), body('anchor'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await journal.appendSubmission({
|
||||
clientMessageId: 'client-message-1',
|
||||
payloadFingerprint: 'fingerprint-1',
|
||||
@@ -245,7 +276,10 @@ describe('a missing epoch row', () => {
|
||||
// consulted again and the dropped rows never come back.
|
||||
it('keeps asking for provider history until the epoch has content of its own', async () => {
|
||||
const journal = await open()
|
||||
await journal.appendItem(item(0), body('anchor'), { fence: 1 })
|
||||
await journal.appendItem(item(0), body('anchor'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await journal.close()
|
||||
await withJournalDatabase((db) => {
|
||||
db.prepare('DELETE FROM journal_rows WHERE seq = ?').run(1)
|
||||
@@ -258,7 +292,10 @@ describe('a missing epoch row', () => {
|
||||
// A session that writes into the epoch owns it: its own rows are not a
|
||||
// repair placeholder, and a later import must not replace them.
|
||||
const writable = await open()
|
||||
await writable.appendItem(item(1), body('typed after the repair'), { fence: 1 })
|
||||
await writable.appendItem(item(1), body('typed after the repair'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await writable.close()
|
||||
expect(loadJournal(root, IDENTITY.sessionId)).toMatchObject({ corrupt: false })
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types'
|
||||
// The crash boundary: the host wrote a submission row, dispatched, and died
|
||||
// before it learned whether the provider took the message. Replay must reconcile
|
||||
// without duplicating the user's message and without losing it.
|
||||
@@ -138,7 +139,10 @@ describe('crash between provider accept and journal commit', () => {
|
||||
})
|
||||
// The provider's own copy of the message arrives next, under the identity
|
||||
// reconciliation adopted. It must land in the bubble the user already sees.
|
||||
await restarted.appendItem(outcome.identity, userMessage('deploy the thing'), { fence: 2 })
|
||||
await restarted.appendItem(outcome.identity, userMessage('deploy the thing'), {
|
||||
fence: 2,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
|
||||
const items = restarted.snapshot().items
|
||||
expect(items).toHaveLength(1)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// The turn scope of a row written before rows stated one: the root turn that was open when the
|
||||
// row was created. Hosts now state a scope on every item they write, so this reads only legacy
|
||||
// rows, and rows an older host writes into a newer journal after a downgrade. It needs no
|
||||
// persisted state: the journal is replayed in full on every open, in creation order.
|
||||
//
|
||||
// A root turn record created running opens a span, which closes when a revision ends it or
|
||||
// removes its turn body — a legacy `/compact` row was created as a running turn carrier and then
|
||||
// overwritten with plain status. A turn record created already settled (rebuilt history) stays
|
||||
// open until the next root turn record: that is its position within the provider's history.
|
||||
// Rows created in the window between a crash and the stale-turn sweep land in the dead turn,
|
||||
// which is where their position puts them too.
|
||||
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalItemBody,
|
||||
type AgentJournalTurnScope
|
||||
} from '../../../shared/agent-session-journal-types'
|
||||
import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record'
|
||||
|
||||
export class JournalDerivedTurnScope {
|
||||
private openTurnItemId: string | null = null
|
||||
|
||||
/** The scope for a row being created now that states none. A turn record belongs to no turn. */
|
||||
scopeFor(body: AgentJournalItemBody): AgentJournalTurnScope {
|
||||
return this.openTurnItemId === null || readAgentJournalTurn(body)
|
||||
? AGENT_JOURNAL_THREAD_SCOPE
|
||||
: { kind: 'turn', turnItemId: this.openTurnItemId }
|
||||
}
|
||||
|
||||
/** Every change to an item, from any row, after it is applied. `before` is undefined when the
|
||||
* row created the item, `after` when it removed it. Only the session's own turns open a span. */
|
||||
observe(
|
||||
itemId: string,
|
||||
root: boolean,
|
||||
before: AgentJournalItemBody | undefined,
|
||||
after: AgentJournalItemBody | undefined
|
||||
): void {
|
||||
const turn = readAgentJournalTurn(after)
|
||||
if (before === undefined && turn && root) {
|
||||
this.openTurnItemId = itemId
|
||||
return
|
||||
}
|
||||
if (
|
||||
itemId === this.openTurnItemId &&
|
||||
readAgentJournalTurn(before)?.state === 'running' &&
|
||||
turn?.state !== 'running'
|
||||
) {
|
||||
this.openTurnItemId = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from '../../../shared/agent-session-failure'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key'
|
||||
import type { JournalReducerState } from './journal-reducer'
|
||||
import { placeHandedOverMessage } from './journal-submission-fold'
|
||||
import type { JournalRow } from './journal-row-schema'
|
||||
|
||||
export function applyJournalDispatchRow(
|
||||
@@ -39,6 +40,7 @@ export function applyJournalDispatchRow(
|
||||
submission.resolvedAt = row.state === 'pending' ? null : row.ts
|
||||
if (row.state === 'pending') {
|
||||
submission.handedOverAt = row.ts
|
||||
placeHandedOverMessage(state, submission, row)
|
||||
}
|
||||
if (row.recovered) {
|
||||
submission.recovered = row.recovered
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types'
|
||||
// Republishing an epoch is ONE transaction.
|
||||
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
@@ -86,8 +87,16 @@ describe('journal epoch replacement', () => {
|
||||
|
||||
it('discards every superseded row in the same transaction', async () => {
|
||||
const journal = await journals.open({ identity: IDENTITY, journalDir: root })
|
||||
await journal.appendItem(item(1), { kind: 'status', text: 'old' }, { fence: 1 })
|
||||
await journal.appendItem(item(2), { kind: 'status', text: 'older' }, { fence: 1 })
|
||||
await journal.appendItem(
|
||||
item(1),
|
||||
{ kind: 'status', text: 'old' },
|
||||
{ fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
await journal.appendItem(
|
||||
item(2),
|
||||
{ kind: 'status', text: 'older' },
|
||||
{ fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
const before = journal.epoch
|
||||
|
||||
await journal.replaceEpochItems('legacy_import', 1, [
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalItemIdentity,
|
||||
AgentJournalProducerLinkage,
|
||||
AgentJournalTurnScope,
|
||||
AgentSessionJournalIdentity
|
||||
} from '../../../shared/agent-session-journal-types'
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
@@ -22,10 +24,13 @@ import {
|
||||
import type { AgentJournalEpochReason, JournalRow } from './journal-row-schema'
|
||||
import { assertJournalFence } from './journal-write-guards'
|
||||
|
||||
export type JournalReplacementItem = {
|
||||
export type JournalReplacementItem = AgentJournalProducerLinkage & {
|
||||
identity: AgentJournalItemIdentity
|
||||
body: AgentJournalItemBody
|
||||
observedAt?: number
|
||||
/** Absent for history rebuilt from a source that never stated one: derived from position, as
|
||||
* a legacy row's is, and then written down. */
|
||||
turnScope?: AgentJournalTurnScope
|
||||
}
|
||||
|
||||
export function replaceJournalEpoch(input: {
|
||||
@@ -56,7 +61,9 @@ export function replaceJournalEpoch(input: {
|
||||
body: item.body,
|
||||
seq: state.lastSequence + 1,
|
||||
fence: input.fence,
|
||||
ts: item.observedAt ?? input.now()
|
||||
ts: item.observedAt ?? input.now(),
|
||||
linkage: item,
|
||||
turnScope: item.turnScope ?? state.derivedTurnScope.scopeFor(item.body)
|
||||
})
|
||||
assertJournalFence(row.fence, state.highestFence)
|
||||
applyJournalRow(state, row)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types'
|
||||
// An empty chat beside a pre-SQLite journal explains itself.
|
||||
//
|
||||
// The SQLite move shipped no importer, so a session whose history is a
|
||||
@@ -142,7 +143,7 @@ describe('a chat whose history is still in the pre-SQLite format', () => {
|
||||
await journal.appendItem(
|
||||
{ provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 0 },
|
||||
{ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'history' }] },
|
||||
{ fence: 1 }
|
||||
{ fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
await journal.close()
|
||||
// Deleting the anchor leaves every row unanchored: replay keeps nothing, so
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types'
|
||||
// Every path that can open a SQLite connection releases it.
|
||||
//
|
||||
// Asserting that the happy path closes cleanly proves nothing: these sites are
|
||||
@@ -73,7 +74,11 @@ afterEach(async () => {
|
||||
describe('the standalone probe owns its own connection', () => {
|
||||
it('leaves no handle behind after fifty repeated loads', async () => {
|
||||
const journal = await journals.open({ identity: IDENTITY, journalDir: root })
|
||||
await journal.appendItem(item(1), { kind: 'message', role: 'user', blocks: [] }, { fence: 1 })
|
||||
await journal.appendItem(
|
||||
item(1),
|
||||
{ kind: 'message', role: 'user', blocks: [] },
|
||||
{ fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
await journal.close()
|
||||
|
||||
for (let attempt = 0; attempt < 50; attempt += 1) {
|
||||
@@ -141,7 +146,10 @@ describe('failure paths inside the open call', () => {
|
||||
// connection exists, which is what lets the factory need no `finally`.
|
||||
it('leaves nothing open when a post-connection step of open() throws', async () => {
|
||||
const journal = await journals.open({ identity: IDENTITY, journalDir: root })
|
||||
await journal.appendItem(item(1), runningTool(), { fence: 1 })
|
||||
await journal.appendItem(item(1), runningTool(), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await journal.close()
|
||||
|
||||
// Replay runs after the connection is open, so a read it cannot serve
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// Folding one item write into the render model: the revision, tombstone and creating-write rules
|
||||
// the reducer header states. Turn scope is the creating write's too, with one exception, which the
|
||||
// submission fold owns: a queued message's scope and position are its handover's.
|
||||
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalRenderItem,
|
||||
AgentJournalTurnScope
|
||||
} from '../../../shared/agent-session-journal-types'
|
||||
import { parseAgentJournalItemKey } from '../../../shared/agent-session-journal-item-key'
|
||||
import {
|
||||
agentJournalLinkageFields,
|
||||
isRootAgentJournalItem,
|
||||
namesAgentJournalProducer
|
||||
} from '../../../shared/agent-session-journal-producer'
|
||||
import type { JournalReducerState } from './journal-reducer'
|
||||
|
||||
export function statedOrDerivedTurnScope(
|
||||
state: JournalReducerState,
|
||||
write: { body: AgentJournalItemBody; turnScope?: AgentJournalTurnScope }
|
||||
): AgentJournalTurnScope {
|
||||
return write.turnScope ?? state.derivedTurnScope.scopeFor(write.body)
|
||||
}
|
||||
|
||||
export function upsertJournalItem(
|
||||
state: JournalReducerState,
|
||||
itemId: string,
|
||||
revision: number,
|
||||
next: AgentJournalRenderItem,
|
||||
/** The creating write's fence: the generation a running turn belongs to. */
|
||||
fence: number
|
||||
): void {
|
||||
const tombstoned = state.tombstones.get(itemId)
|
||||
if (tombstoned !== undefined && revision <= tombstoned) {
|
||||
return
|
||||
}
|
||||
const existing = state.items.get(itemId)
|
||||
if (existing && revision <= existing.revision) {
|
||||
return
|
||||
}
|
||||
state.derivedTurnScope.observe(itemId, isRootAgentJournalItem(next), existing?.body, next.body)
|
||||
if (!existing) {
|
||||
state.items.set(itemId, next)
|
||||
state.itemFences.set(itemId, fence)
|
||||
state.tombstones.delete(itemId)
|
||||
return
|
||||
}
|
||||
// Creation sequence is the ordering key; a revision refreshes content only.
|
||||
// `observedAt` is pinned with it: clients sort the timeline by that timestamp,
|
||||
// so letting a revision advance it makes the row jump past everything that
|
||||
// landed in between — the provider's own echo of a send revises the submission
|
||||
// row, which relocated the user's bubble below later rows.
|
||||
const submitted =
|
||||
existing.body.kind === 'message' &&
|
||||
existing.body.role === 'user' &&
|
||||
parseAgentJournalItemKey(itemId)?.provider === 'orca'
|
||||
const { sequenceIndex: _revisedAt, ...revised } = next
|
||||
state.items.set(itemId, {
|
||||
...revised,
|
||||
// Settlements, prompt answers and reopen sweeps revise rows any agent wrote
|
||||
// without naming one; each would otherwise hand a subagent's row to the session.
|
||||
...(namesAgentJournalProducer(next) ? {} : agentJournalLinkageFields(existing)),
|
||||
// Provider history may normalize text or omit local attachments from the original send.
|
||||
body: submitted ? existing.body : next.body,
|
||||
sequence: existing.sequence,
|
||||
...(existing.sequenceIndex !== undefined ? { sequenceIndex: existing.sequenceIndex } : {}),
|
||||
observedAt: existing.observedAt,
|
||||
turnScope: existing.turnScope ?? next.turnScope
|
||||
})
|
||||
state.tombstones.delete(itemId)
|
||||
}
|
||||
|
||||
export function removeJournalItem(
|
||||
state: JournalReducerState,
|
||||
itemId: string,
|
||||
revision: number
|
||||
): void {
|
||||
const existing = state.items.get(itemId)
|
||||
if (existing && revision <= existing.revision) {
|
||||
return
|
||||
}
|
||||
const tombstoned = state.tombstones.get(itemId)
|
||||
if (tombstoned !== undefined && revision <= tombstoned) {
|
||||
return
|
||||
}
|
||||
if (existing) {
|
||||
state.derivedTurnScope.observe(
|
||||
itemId,
|
||||
isRootAgentJournalItem(existing),
|
||||
existing.body,
|
||||
undefined
|
||||
)
|
||||
}
|
||||
state.tombstones.set(itemId, revision)
|
||||
state.items.delete(itemId)
|
||||
state.itemFences.delete(itemId)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user