mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 10:58:10 +00:00
Keep inherited fork actions with their original chat
This commit is contained in:
@@ -291,6 +291,8 @@
|
||||
"uncommittedFiles_other": "{{count}} uncommitted"
|
||||
},
|
||||
"failure": {
|
||||
"forkOriginalMissing": "{{agent}} could not find this response in the original chat. Open it and fork from there.",
|
||||
"forkOriginalUnavailable": "{{agent}} cannot fork this response in the original chat right now. Open it and fork from there.",
|
||||
"pluginInputRequired": "{{agent}} stopped because the \"{{plugin}}\" plugin is waiting for input in a terminal pane. Disable the plugin for chat sessions, or run the task in a {{agent}} terminal."
|
||||
},
|
||||
"fileReader": {
|
||||
|
||||
@@ -2547,6 +2547,8 @@
|
||||
"fallback": "Worktree"
|
||||
},
|
||||
"failure": {
|
||||
"forkOriginalMissing": "{{agent}} could not find this response in the original chat. Open it and fork from there.",
|
||||
"forkOriginalUnavailable": "{{agent}} cannot fork this response in the original chat right now. Open it and fork from there.",
|
||||
"backgroundTasksRunning": "Background tasks are still running.",
|
||||
"waitForBackgroundTasks": "Wait for the background tasks to finish.",
|
||||
"agentStarting": "The agent is still starting.",
|
||||
|
||||
@@ -10,6 +10,18 @@ import { SEND_FAILURE_COPY } from './agent-session-send-failure-copy'
|
||||
|
||||
const COPY: Record<AgentSessionFailureCopyId, (values: AgentSessionFailureCopyValues) => string> = {
|
||||
...START_FAILURE_COPY,
|
||||
forkOriginalMissing: (values) =>
|
||||
translate(
|
||||
'session.failure.forkOriginalMissing',
|
||||
AGENT_SESSION_FAILURE_COPY.forkOriginalMissing,
|
||||
values
|
||||
),
|
||||
forkOriginalUnavailable: (values) =>
|
||||
translate(
|
||||
'session.failure.forkOriginalUnavailable',
|
||||
AGENT_SESSION_FAILURE_COPY.forkOriginalUnavailable,
|
||||
values
|
||||
),
|
||||
pluginInputRequired: (values) =>
|
||||
translate(
|
||||
'session.failure.pluginInputRequired',
|
||||
|
||||
@@ -358,3 +358,31 @@ describe('mobile structured agent-session launch', () => {
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('settles a proven missing-original fork refusal but keeps a lost earlier attempt unknown', async () => {
|
||||
const refusal = {
|
||||
ok: true,
|
||||
result: {
|
||||
ok: false,
|
||||
refusal: {
|
||||
code: 'agent_session_identity_required',
|
||||
details: { reason: 'recordMissing' },
|
||||
createAttemptRefusedBeforeCommit: true,
|
||||
message: 'Source chat unavailable'
|
||||
}
|
||||
}
|
||||
}
|
||||
const client = clientReturning({ ok: true, result: { supported: true } }, refusal)
|
||||
const forkFrom = { sessionId: 'copied-chat', throughItemId: 'legacy:opencode:source:reply-1' }
|
||||
expect(
|
||||
(await createMobileStructuredAgentSession(client, 'workspace-1', 'opencode', forkFrom)).kind
|
||||
).toBe('failed')
|
||||
const lost = clientReturning({ ok: true, result: { supported: true } }, refusal)
|
||||
lost.sendRequest
|
||||
.mockImplementationOnce(async () => ({ ok: true, result: { supported: true } }))
|
||||
.mockRejectedValueOnce(markRpcDeliveryUnknown(new Error('reply lost')))
|
||||
.mockResolvedValueOnce(refusal)
|
||||
expect(
|
||||
(await createMobileStructuredAgentSession(lost, 'workspace-1', 'opencode', forkFrom)).kind
|
||||
).toBe('unknown')
|
||||
})
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { agentSessionForkSourceFailureWords } from '../../../src/shared/agent-session/failures/agent-session-failure-copy'
|
||||
import { sayMobileAgentSessionFailure } from './agent-session-failure-copy'
|
||||
import type { AgentSessionHandleProvider } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle'
|
||||
import type {
|
||||
AgentSessionAttachResult,
|
||||
AgentSessionMutationResult
|
||||
} from '../../../src/shared/agent-session/agent-session-wire'
|
||||
import { isDefinitiveAgentSessionCreateRefusal } from '../../../src/shared/agent-session/failures/agent-session-definitive-refusal'
|
||||
import {
|
||||
isDefinitiveAgentSessionCreateRefusal,
|
||||
isAgentSessionForkSourceAdmissionRefusal
|
||||
} from '../../../src/shared/agent-session/failures/agent-session-definitive-refusal'
|
||||
import {
|
||||
createStructuredAgentSessionId,
|
||||
structuredAgentSessionCreateParams,
|
||||
@@ -132,12 +137,14 @@ export async function createMobileStructuredAgentSession(
|
||||
const params = createParamsFor(agent, worktree, forkFrom, tabPlacement)
|
||||
rememberMobileCreatedStructuredSession(params.envelope.sessionId, worktree)
|
||||
let response
|
||||
let priorCreateOutcomeUnknown = false
|
||||
try {
|
||||
response = await structuredAgentSessionCreate.request(client, params, {
|
||||
timeoutMs: 15_000,
|
||||
budgetSpansConnect: true
|
||||
})
|
||||
} catch {
|
||||
priorCreateOutcomeUnknown = true
|
||||
// Replay the durable envelope once so a lost acknowledgement cannot create a sibling.
|
||||
try {
|
||||
response = await structuredAgentSessionCreate.request(client, params, {
|
||||
@@ -179,6 +186,22 @@ export async function createMobileStructuredAgentSession(
|
||||
) {
|
||||
return unknownCreateResult(agent, new Error(unconfirmedMessage(agent)))
|
||||
}
|
||||
if (
|
||||
forkFrom &&
|
||||
!priorCreateOutcomeUnknown &&
|
||||
result.refusal.createAttemptRefusedBeforeCommit === true &&
|
||||
isAgentSessionForkSourceAdmissionRefusal(result.refusal)
|
||||
) {
|
||||
return {
|
||||
kind: 'failed',
|
||||
message:
|
||||
agentSessionForkSourceFailureWords(
|
||||
result.refusal.message,
|
||||
TUI_AGENT_DISPLAY_NAMES[agent],
|
||||
sayMobileAgentSessionFailure
|
||||
) ?? result.refusal.message
|
||||
}
|
||||
}
|
||||
return classifyCreateRefusal(agent, result.refusal.code, result.refusal.message)
|
||||
}
|
||||
if (
|
||||
|
||||
@@ -193,3 +193,55 @@ it('gives a resumed spell of fork support its own retries, and the reply becomes
|
||||
expect(sendRequest).toHaveBeenCalledTimes(5)
|
||||
expect(latest?.offerFor(message)).toBe('available')
|
||||
})
|
||||
|
||||
it('offers an inherited OpenCode tip after the child advances and submits its displayed key', async () => {
|
||||
const { client, sendRequest } = connection(0)
|
||||
sendRequest.mockResolvedValue({
|
||||
ok: true,
|
||||
result: { agents: [{ agent: 'opencode', capabilities: { fork: 'tip' } }] }
|
||||
})
|
||||
const createFork = vi.fn(async () => {})
|
||||
const copied = { ...message, id: 'legacy:opencode:source:reply-1' }
|
||||
const own = {
|
||||
...message,
|
||||
id: 'legacy:opencode:child:reply-2',
|
||||
journalPosition: { sequence: 4, index: 0 }
|
||||
}
|
||||
function ForkProbe() {
|
||||
latest = useMobileNativeChatFork({
|
||||
client,
|
||||
hostCapabilities: FORK_HOST,
|
||||
agent: 'opencode',
|
||||
sessionId: 'child',
|
||||
messages: [copied, own],
|
||||
turnJournal: {
|
||||
items: [
|
||||
{ ...reply, itemId: copied.id },
|
||||
{
|
||||
...reply,
|
||||
itemId: 'orca:forked-from',
|
||||
body: { kind: 'status', presentation: 'forked-from', text: 'Forked from source' }
|
||||
},
|
||||
{ ...reply, itemId: own.id, sequence: 4 }
|
||||
],
|
||||
submissions: []
|
||||
},
|
||||
agentWorking: false,
|
||||
sessionForkSupport: 'supported',
|
||||
createFork
|
||||
})
|
||||
return null
|
||||
}
|
||||
await act(async () => {
|
||||
renderer = create(createElement(ForkProbe))
|
||||
})
|
||||
await settle()
|
||||
expect(latest?.offerFor(copied)).toBe('available')
|
||||
await act(async () => {
|
||||
latest?.fork(copied)
|
||||
})
|
||||
expect(createFork).toHaveBeenCalledWith('opencode', {
|
||||
sessionId: 'child',
|
||||
throughItemId: 'legacy:opencode:source:reply-1'
|
||||
})
|
||||
})
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
import type { StructuredAgentSessionForkSource } from '../../../../src/shared/agent-session/structured-agent-session-create'
|
||||
import type { StructuredAgentSessionHostCapabilityState } from '../../../../src/shared/agent-session/structured-agent-session-host-capability'
|
||||
import {
|
||||
nativeChatForkableItemIds,
|
||||
nativeChatForkInventory,
|
||||
nativeChatForkSupport,
|
||||
nativeChatRowOffersFork
|
||||
} from '../../../../src/shared/native-chat/native-chat-fork-offer'
|
||||
@@ -191,8 +191,8 @@ export function useMobileNativeChatFork(input: {
|
||||
}, [messages, turnJournal])
|
||||
const contextFloorSequence = latestAgentSessionContextClearSequence(turnJournal?.items ?? [])
|
||||
// The sheet's row is a display projection; only one naming the agent's own message forks.
|
||||
const forkableItemIds = useMemo(
|
||||
() => nativeChatForkableItemIds(turnJournal?.items ?? []),
|
||||
const { forkableItemIds, inheritedThroughSequence } = useMemo(
|
||||
() => nativeChatForkInventory(turnJournal?.items ?? []),
|
||||
[turnJournal]
|
||||
)
|
||||
// Reserved at the press, before any await, so a second press never starts a second fork.
|
||||
@@ -214,7 +214,7 @@ export function useMobileNativeChatFork(input: {
|
||||
turnWorking: agentWorking && (turnKey === undefined || turnKey === turns.liveTurnKey),
|
||||
inLatestTurn: turnKey !== undefined && turnKey === turns.latestTurnKey
|
||||
},
|
||||
{ support, contextFloorSequence, forkableItemIds }
|
||||
{ support, contextFloorSequence, forkableItemIds, inheritedThroughSequence }
|
||||
)
|
||||
return !offered
|
||||
? 'reserved'
|
||||
@@ -222,7 +222,17 @@ export function useMobileNativeChatFork(input: {
|
||||
? 'disabled'
|
||||
: 'available'
|
||||
},
|
||||
[agent, agentWorking, contextFloorSequence, forkableItemIds, pending, sessionId, support, turns]
|
||||
[
|
||||
agent,
|
||||
agentWorking,
|
||||
contextFloorSequence,
|
||||
forkableItemIds,
|
||||
inheritedThroughSequence,
|
||||
pending,
|
||||
sessionId,
|
||||
support,
|
||||
turns
|
||||
]
|
||||
)
|
||||
const fork = useCallback(
|
||||
(message: NativeChatMessage) => {
|
||||
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
import { isInheritedAgentSessionItem } from '../../../../shared/agent-session/agent-session-fork'
|
||||
import {
|
||||
agentJournalItemKey,
|
||||
parseAgentJournalItemKey
|
||||
} from '../../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { activeProviderContext } from '../../../../shared/agent-session/agent-session-provider-context'
|
||||
import {
|
||||
agentSessionExecutionLocationsEqual,
|
||||
type AgentSessionExecutionLocation
|
||||
} from '../../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle'
|
||||
import { isAgentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals'
|
||||
import { isAgentSessionForkSourceAdmissionRefusal } from '../../../../shared/agent-session/failures/agent-session-definitive-refusal'
|
||||
import { AGENT_SESSION_FAILURE_COPY } from '../../../../shared/agent-session/failures/agent-session-failure-copy'
|
||||
import {
|
||||
AgentConversationCopyError,
|
||||
agentConversationCopyRefusal
|
||||
} from '../../agent-conversation-copy-error'
|
||||
import { acpAgentName } from '../../../acp/acp-structured-agent-definitions'
|
||||
import { structuredAgentRuntimeMetadata } from '../../../runtime/agent-session/installation/structured-agent-runtime-metadata'
|
||||
import type { StructuredAgentSessionHost } from '../host/structured-agent-session-host'
|
||||
import type { AgentSessionAttachParams } from './structured-agent-session-attach'
|
||||
import { importedAgentSessionForkTipSettled } from './imported-agent-session-fork-tip'
|
||||
import { structuredAgentSessionForkBoundary } from './structured-agent-session-fork-boundary'
|
||||
|
||||
export type StructuredAgentSessionForkInput = {
|
||||
host: StructuredAgentSessionHost
|
||||
sessionId: string
|
||||
throughItemId: string
|
||||
agent: StructuredAgentId
|
||||
location: AgentSessionExecutionLocation
|
||||
envelope: AgentSessionAttachParams['envelope']
|
||||
}
|
||||
|
||||
/** This catch ends before native copying begins; only authored admission failures prove no copy. */
|
||||
export async function admitStructuredAgentSessionFork(input: StructuredAgentSessionForkInput) {
|
||||
try {
|
||||
return await resolveForkSource(input)
|
||||
} catch (error) {
|
||||
if (
|
||||
isAgentSessionRefusalError(error) &&
|
||||
error.cause instanceof AgentConversationCopyError &&
|
||||
isAgentSessionForkSourceAdmissionRefusal(error.refusal)
|
||||
) {
|
||||
error.refusal.createAttemptRefusedBeforeCommit = true
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveForkSource(input: StructuredAgentSessionForkInput) {
|
||||
const { host } = input
|
||||
let original = false
|
||||
for (;;) {
|
||||
const name = acpAgentName(input.agent)
|
||||
if (host.deps.store.selectWritableRecord(input.sessionId).kind === 'missing') {
|
||||
throw agentConversationCopyRefusal(
|
||||
'agent_session_identity_required',
|
||||
{ reason: 'recordMissing' },
|
||||
original
|
||||
? AGENT_SESSION_FAILURE_COPY.forkOriginalMissing.replace('{{agent}}', name)
|
||||
: `${name} could not find the source chat. Open the chat again, then try again.`
|
||||
)
|
||||
}
|
||||
const record = host.deps.store.requireWritableRecord(input.sessionId)
|
||||
const metadata = structuredAgentRuntimeMetadata(input.agent)
|
||||
const capability = host.deps.agents.capabilities(input.agent)?.fork
|
||||
const { head, pendingClear } = activeProviderContext(record)
|
||||
const fail = (
|
||||
message: string,
|
||||
reason:
|
||||
| 'conversationCleared'
|
||||
| 'rewindUnconfirmed'
|
||||
| 'turnActive'
|
||||
| 'savedConversationMissing'
|
||||
| 'providerRejected'
|
||||
| 'launchFolderMissing' = 'savedConversationMissing'
|
||||
): never => {
|
||||
const refusal = agentConversationCopyRefusal(
|
||||
'agent_session_operation_invalid',
|
||||
{ reason },
|
||||
message
|
||||
)
|
||||
if (original) {
|
||||
refusal.refusal.message = AGENT_SESSION_FAILURE_COPY[
|
||||
reason === 'savedConversationMissing' ? 'forkOriginalMissing' : 'forkOriginalUnavailable'
|
||||
].replace('{{agent}}', name)
|
||||
refusal.cause = new AgentConversationCopyError(refusal.refusal.message)
|
||||
}
|
||||
throw refusal
|
||||
}
|
||||
if (!capability || !metadata?.transcriptImport || !host.deps.adapter.copyConversation) {
|
||||
throw agentConversationCopyRefusal(
|
||||
'structured_agent_session_unsupported',
|
||||
{ reason: 'hostUnsupported' },
|
||||
`${name} cannot copy a chat. Update ${name}, then try again.`
|
||||
)
|
||||
}
|
||||
if (
|
||||
record.provider !== input.agent ||
|
||||
!agentSessionExecutionLocationsEqual(record.location, input.location) ||
|
||||
input.sessionId === input.envelope.sessionId
|
||||
) {
|
||||
fail(`${name} could not open the source chat in this workspace. Open it again and try again.`)
|
||||
}
|
||||
if (
|
||||
!head ||
|
||||
pendingClear ||
|
||||
(record.conversationCommand?.command === 'clear' &&
|
||||
(record.conversationCommand.phase === 'prepared' ||
|
||||
record.conversationCommand.state === 'unknown')) ||
|
||||
record.rewind?.phase === 'prepared' ||
|
||||
record.rewind?.phase === 'provider-succeeded'
|
||||
) {
|
||||
fail(
|
||||
`${name} has no confirmed saved context to copy. Finish the rewind or send a message, then try again.`,
|
||||
pendingClear || !head ? 'conversationCleared' : 'rewindUnconfirmed'
|
||||
)
|
||||
}
|
||||
const sourceHead = head ?? fail(`${name} has no saved context. Send a message, then try again.`)
|
||||
const snapshot = await host.journalSnapshot(record.sessionId)
|
||||
const boundary = structuredAgentSessionForkBoundary(
|
||||
snapshot,
|
||||
record,
|
||||
input.throughItemId,
|
||||
capability
|
||||
)
|
||||
const selected =
|
||||
boundary ??
|
||||
fail(
|
||||
`${name} could not find this response in the current chat. Open the chat again and try again.`
|
||||
)
|
||||
if (
|
||||
record.forkedFrom &&
|
||||
isInheritedAgentSessionItem(
|
||||
snapshot.items,
|
||||
record.forkedFrom.childBoundary,
|
||||
input.throughItemId
|
||||
)
|
||||
) {
|
||||
const ancestor = host.deps.store.getRecord(record.forkedFrom.sessionId)
|
||||
const originalHead = ancestor && activeProviderContext(ancestor).head
|
||||
const key = parseAgentJournalItemKey(input.throughItemId)
|
||||
input = {
|
||||
...input,
|
||||
sessionId: record.forkedFrom.sessionId,
|
||||
throughItemId:
|
||||
key?.provider === 'codex' && key.threadId === sourceHead.handle.nativeId && originalHead
|
||||
? agentJournalItemKey({
|
||||
provider: 'codex',
|
||||
threadId: originalHead.handle.nativeId,
|
||||
turnId: key.turnId,
|
||||
ordinal: key.ordinal
|
||||
})
|
||||
: input.throughItemId
|
||||
}
|
||||
original = true
|
||||
continue
|
||||
}
|
||||
const admissions = host.deps.store.admittedSendCount(record.sessionId)
|
||||
const dispatch = JSON.stringify(snapshot.submissions)
|
||||
const cwd =
|
||||
record.launchDirectory ??
|
||||
(await host.deps.resolveWorkspacePath?.(record.location.workspaceId))
|
||||
if (!cwd) {
|
||||
fail(
|
||||
`${name} could not open the source workspace. Open it again and try again.`,
|
||||
'launchFolderMissing'
|
||||
)
|
||||
}
|
||||
const workspaceCwd =
|
||||
cwd ??
|
||||
fail(
|
||||
`${name} could not open the source workspace. Open it again and try again.`,
|
||||
'launchFolderMissing'
|
||||
)
|
||||
const launchEnv = { ...process.env, ...(await host.deps.resolveLaunchEnv?.(input.agent)) }
|
||||
const providerSessionId = metadata.sessionHistory.rowSessionId(sourceHead)
|
||||
if (capability === 'tip' && selected.latest && !selected.checkpoint.settled) {
|
||||
selected.checkpoint.settled = await importedAgentSessionForkTipSettled({
|
||||
record,
|
||||
providerSessionId,
|
||||
selectedItemId: selected.checkpoint.selectedItemId,
|
||||
workspaceCwd,
|
||||
launchEnv
|
||||
})
|
||||
}
|
||||
if (capability === 'tip' && (!selected.latest || !selected.checkpoint.settled)) {
|
||||
fail(
|
||||
`${name} can only fork its latest finished response. Wait for it to finish, then try again.`,
|
||||
'turnActive'
|
||||
)
|
||||
}
|
||||
const throughItemId = input.throughItemId
|
||||
const requireCurrent = async () => {
|
||||
const current = host.deps.store.requireWritableRecord(record.sessionId)
|
||||
const currentSnapshot = await host.journalSnapshot(record.sessionId)
|
||||
const context = activeProviderContext(current)
|
||||
const transitionPending =
|
||||
context.pendingClear ||
|
||||
current.rewind?.phase === 'prepared' ||
|
||||
current.rewind?.phase === 'provider-succeeded' ||
|
||||
(current.conversationCommand?.command === 'clear' &&
|
||||
(current.conversationCommand.phase === 'prepared' ||
|
||||
current.conversationCommand.state === 'unknown'))
|
||||
const currentBoundary = transitionPending
|
||||
? null
|
||||
: structuredAgentSessionForkBoundary(currentSnapshot, current, throughItemId, capability)
|
||||
if (
|
||||
!agentSessionExecutionLocationsEqual(current.location, record.location) ||
|
||||
currentBoundary?.retained !== selected.retained ||
|
||||
(capability === 'tip' &&
|
||||
(host.deps.store.admittedSendCount(record.sessionId) !== admissions ||
|
||||
JSON.stringify(currentSnapshot.submissions) !== dispatch ||
|
||||
!currentBoundary.latest))
|
||||
) {
|
||||
fail(`${name} could not finish the copy because the source context changed. Try again.`)
|
||||
}
|
||||
return { snapshot: currentSnapshot, boundary: currentBoundary! }
|
||||
}
|
||||
await requireCurrent()
|
||||
return {
|
||||
record,
|
||||
metadata,
|
||||
transcriptImport: metadata.transcriptImport,
|
||||
selected,
|
||||
sourceHead,
|
||||
providerSessionId,
|
||||
requireCurrent,
|
||||
fail,
|
||||
throughItemId
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
-215
@@ -1,238 +1,74 @@
|
||||
import { isInheritedAgentSessionItem } from '../../../../shared/agent-session/agent-session-fork'
|
||||
import {
|
||||
agentJournalItemKey,
|
||||
parseAgentJournalItemKey
|
||||
} from '../../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
admitStructuredAgentSessionFork,
|
||||
type StructuredAgentSessionForkInput
|
||||
} from './structured-agent-session-fork-source'
|
||||
import { prepareForkSnapshot } from './structured-agent-session-fork-snapshot'
|
||||
import { agentSessionJournalProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
|
||||
import { importedAgentSessionForkTipSettled } from './imported-agent-session-fork-tip'
|
||||
import { defaultAgentChatLabel } from '../../../../shared/agent-session/agent-session-chat-label'
|
||||
import {
|
||||
normalizeAgentSessionConversationName,
|
||||
AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH
|
||||
} from '../../../../shared/agent-session/agent-session-conversation-name'
|
||||
import { sliceAtCodeUnitLimit } from '../../../../shared/surrogate-safe-text-slice'
|
||||
import {
|
||||
AgentConversationCopyError,
|
||||
agentConversationCopyRefusal
|
||||
} from '../../agent-conversation-copy-error'
|
||||
import { structuredAgentSessionForkBoundary } from './structured-agent-session-fork-boundary'
|
||||
import { AgentConversationCopyError } from '../../agent-conversation-copy-error'
|
||||
import { acpAgentName } from '../../../acp/acp-structured-agent-definitions'
|
||||
import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode'
|
||||
import { activeProviderContext } from '../../../../shared/agent-session/agent-session-provider-context'
|
||||
import { isAgentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals'
|
||||
import {
|
||||
agentSessionExecutionLocationsEqual,
|
||||
type AgentSessionExecutionLocation
|
||||
} from '../../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle'
|
||||
import { requireUnownedStructuredAgentSessionAdoption } from '../../../runtime/agent-session/structured-agent-session-create-adoption'
|
||||
import { structuredAgentRuntimeMetadata } from '../../../runtime/agent-session/installation/structured-agent-runtime-metadata'
|
||||
import type { StructuredAgentSessionHost } from '../host/structured-agent-session-host'
|
||||
import type { AgentSessionAttachParams } from './structured-agent-session-attach'
|
||||
|
||||
export async function prepareStructuredAgentSessionFork(input: {
|
||||
host: StructuredAgentSessionHost
|
||||
sessionId: string
|
||||
throughItemId: string
|
||||
agent: StructuredAgentId
|
||||
location: AgentSessionExecutionLocation
|
||||
envelope: AgentSessionAttachParams['envelope']
|
||||
}): Promise<AgentSessionAttachParams> {
|
||||
export async function prepareStructuredAgentSessionFork(
|
||||
input: StructuredAgentSessionForkInput
|
||||
): Promise<AgentSessionAttachParams> {
|
||||
const { host } = input
|
||||
const name = acpAgentName(input.agent)
|
||||
if (host.deps.store.selectWritableRecord(input.sessionId).kind === 'missing') {
|
||||
throw agentConversationCopyRefusal(
|
||||
'agent_session_identity_required',
|
||||
{ reason: 'recordMissing' },
|
||||
`${name} could not find the source chat. Open the chat again, then try again.`
|
||||
)
|
||||
}
|
||||
const record = host.deps.store.requireWritableRecord(input.sessionId)
|
||||
const metadata = structuredAgentRuntimeMetadata(input.agent)
|
||||
const capability = host.deps.agents.capabilities(input.agent)?.fork
|
||||
const { head, pendingClear } = activeProviderContext(record)
|
||||
const fail = (
|
||||
message: string,
|
||||
reason:
|
||||
| 'conversationCleared'
|
||||
| 'rewindUnconfirmed'
|
||||
| 'turnActive'
|
||||
| 'savedConversationMissing'
|
||||
| 'providerRejected'
|
||||
| 'launchFolderMissing' = 'savedConversationMissing'
|
||||
): never => {
|
||||
throw agentConversationCopyRefusal('agent_session_operation_invalid', { reason }, message)
|
||||
}
|
||||
if (!capability || !metadata?.transcriptImport || !host.deps.adapter.copyConversation) {
|
||||
throw agentConversationCopyRefusal(
|
||||
'structured_agent_session_unsupported',
|
||||
{ reason: 'hostUnsupported' },
|
||||
`${name} cannot copy a chat. Update ${name}, then try again.`
|
||||
)
|
||||
}
|
||||
if (
|
||||
record.provider !== input.agent ||
|
||||
!agentSessionExecutionLocationsEqual(record.location, input.location) ||
|
||||
input.sessionId === input.envelope.sessionId
|
||||
) {
|
||||
fail(`${name} could not open the source chat in this workspace. Open it again and try again.`)
|
||||
}
|
||||
if (
|
||||
!head ||
|
||||
pendingClear ||
|
||||
(record.conversationCommand?.command === 'clear' &&
|
||||
(record.conversationCommand.phase === 'prepared' ||
|
||||
record.conversationCommand.state === 'unknown')) ||
|
||||
record.rewind?.phase === 'prepared' ||
|
||||
record.rewind?.phase === 'provider-succeeded'
|
||||
) {
|
||||
fail(
|
||||
`${name} has no confirmed saved context to copy. Finish the rewind or send a message, then try again.`,
|
||||
pendingClear || !head ? 'conversationCleared' : 'rewindUnconfirmed'
|
||||
)
|
||||
}
|
||||
const sourceHead = head ?? fail(`${name} has no saved context. Send a message, then try again.`)
|
||||
const snapshot = await host.journalSnapshot(record.sessionId)
|
||||
const boundary = structuredAgentSessionForkBoundary(
|
||||
snapshot,
|
||||
const {
|
||||
record,
|
||||
input.throughItemId,
|
||||
capability
|
||||
)
|
||||
const selected =
|
||||
boundary ??
|
||||
fail(
|
||||
`${name} could not find this response in the current chat. Open the chat again and try again.`
|
||||
)
|
||||
if (
|
||||
record.forkedFrom &&
|
||||
isInheritedAgentSessionItem(
|
||||
snapshot.items,
|
||||
record.forkedFrom.childBoundary,
|
||||
input.throughItemId
|
||||
)
|
||||
) {
|
||||
const original = host.deps.store.getRecord(record.forkedFrom.sessionId)
|
||||
const originalHead = original && activeProviderContext(original).head
|
||||
const key = parseAgentJournalItemKey(input.throughItemId)
|
||||
return prepareStructuredAgentSessionFork({
|
||||
...input,
|
||||
sessionId: record.forkedFrom.sessionId,
|
||||
throughItemId:
|
||||
key?.provider === 'codex' && key.threadId === sourceHead.handle.nativeId && originalHead
|
||||
? agentJournalItemKey({
|
||||
provider: 'codex',
|
||||
threadId: originalHead.handle.nativeId,
|
||||
turnId: key.turnId,
|
||||
ordinal: key.ordinal
|
||||
})
|
||||
: input.throughItemId
|
||||
})
|
||||
}
|
||||
const admissions = host.deps.store.admittedSendCount(record.sessionId)
|
||||
const dispatch = JSON.stringify(snapshot.submissions)
|
||||
const cwd =
|
||||
record.launchDirectory ?? (await host.deps.resolveWorkspacePath?.(record.location.workspaceId))
|
||||
if (!cwd) {
|
||||
fail(
|
||||
`${name} could not open the source workspace. Open it again and try again.`,
|
||||
'launchFolderMissing'
|
||||
)
|
||||
}
|
||||
const workspaceCwd =
|
||||
cwd ??
|
||||
fail(
|
||||
`${name} could not open the source workspace. Open it again and try again.`,
|
||||
'launchFolderMissing'
|
||||
)
|
||||
const launchEnv = { ...process.env, ...(await host.deps.resolveLaunchEnv?.(input.agent)) }
|
||||
const providerSessionId = metadata.sessionHistory.rowSessionId(sourceHead)
|
||||
if (capability === 'tip' && selected.latest && !selected.checkpoint.settled) {
|
||||
selected.checkpoint.settled = await importedAgentSessionForkTipSettled({
|
||||
record,
|
||||
providerSessionId,
|
||||
selectedItemId: selected.checkpoint.selectedItemId,
|
||||
workspaceCwd,
|
||||
launchEnv
|
||||
})
|
||||
}
|
||||
if (capability === 'tip' && (!selected.latest || !selected.checkpoint.settled)) {
|
||||
fail(
|
||||
`${name} can only fork its latest finished response. Wait for it to finish, then try again.`,
|
||||
'turnActive'
|
||||
)
|
||||
}
|
||||
const requireCurrent = async () => {
|
||||
const current = host.deps.store.requireWritableRecord(record.sessionId)
|
||||
const currentSnapshot = await host.journalSnapshot(record.sessionId)
|
||||
const context = activeProviderContext(current)
|
||||
const transitionPending =
|
||||
context.pendingClear ||
|
||||
current.rewind?.phase === 'prepared' ||
|
||||
current.rewind?.phase === 'provider-succeeded' ||
|
||||
(current.conversationCommand?.command === 'clear' &&
|
||||
(current.conversationCommand.phase === 'prepared' ||
|
||||
current.conversationCommand.state === 'unknown'))
|
||||
const currentBoundary = transitionPending
|
||||
? null
|
||||
: structuredAgentSessionForkBoundary(
|
||||
currentSnapshot,
|
||||
current,
|
||||
input.throughItemId,
|
||||
capability
|
||||
)
|
||||
if (
|
||||
!agentSessionExecutionLocationsEqual(current.location, record.location) ||
|
||||
currentBoundary?.retained !== selected.retained ||
|
||||
(capability === 'tip' &&
|
||||
(host.deps.store.admittedSendCount(record.sessionId) !== admissions ||
|
||||
JSON.stringify(currentSnapshot.submissions) !== dispatch ||
|
||||
!currentBoundary.latest))
|
||||
) {
|
||||
fail(`${name} could not finish the copy because the source context changed. Try again.`)
|
||||
}
|
||||
return { snapshot: currentSnapshot, boundary: currentBoundary! }
|
||||
}
|
||||
await requireCurrent()
|
||||
metadata,
|
||||
transcriptImport,
|
||||
selected,
|
||||
sourceHead,
|
||||
providerSessionId,
|
||||
requireCurrent,
|
||||
fail,
|
||||
throughItemId
|
||||
} = await admitStructuredAgentSessionFork(input)
|
||||
const title = normalizeAgentSessionConversationName(
|
||||
`${sliceAtCodeUnitLimit(record.conversationName?.trim() || defaultAgentChatLabel(input.agent), AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH - 5)} fork`
|
||||
)!
|
||||
const copy = await host.deps.adapter
|
||||
.copyConversation({
|
||||
record,
|
||||
checkpoint: selected.checkpoint,
|
||||
title,
|
||||
identity: {
|
||||
sessionId: record.sessionId,
|
||||
workspaceId: record.location.workspaceId,
|
||||
hostId: record.location.executionHostId,
|
||||
agent: input.agent,
|
||||
providerHandle: sourceHead.handle
|
||||
},
|
||||
providerSessionId,
|
||||
accountHome: record.accountHome
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (isAgentSessionRefusalError(error)) {
|
||||
throw error
|
||||
}
|
||||
host.deps.logger.warn('native conversation copy failed', {
|
||||
scope: 'chat-fork',
|
||||
sessionId: record.sessionId,
|
||||
error
|
||||
})
|
||||
return fail(
|
||||
error instanceof AgentConversationCopyError
|
||||
? error.message
|
||||
: error instanceof Error &&
|
||||
(error.name === 'TimeoutError' ||
|
||||
(error.cause instanceof Error && error.cause.name === 'TimeoutError'))
|
||||
? `${name} took too long to copy this chat. Try again.`
|
||||
: `${name} could not copy this conversation. Try again.`,
|
||||
'providerRejected'
|
||||
)
|
||||
const copy = await host.deps.adapter.copyConversation!({
|
||||
record,
|
||||
checkpoint: selected.checkpoint,
|
||||
title,
|
||||
identity: {
|
||||
sessionId: record.sessionId,
|
||||
workspaceId: record.location.workspaceId,
|
||||
hostId: record.location.executionHostId,
|
||||
agent: input.agent,
|
||||
providerHandle: sourceHead.handle
|
||||
},
|
||||
providerSessionId,
|
||||
accountHome: record.accountHome
|
||||
}).catch((error: unknown) => {
|
||||
if (isAgentSessionRefusalError(error)) {
|
||||
throw error
|
||||
}
|
||||
host.deps.logger.warn('native conversation copy failed', {
|
||||
scope: 'chat-fork',
|
||||
sessionId: record.sessionId,
|
||||
error
|
||||
})
|
||||
return fail(
|
||||
error instanceof AgentConversationCopyError
|
||||
? error.message
|
||||
: error instanceof Error &&
|
||||
(error.name === 'TimeoutError' ||
|
||||
(error.cause instanceof Error && error.cause.name === 'TimeoutError'))
|
||||
? `${name} took too long to copy this chat. Try again.`
|
||||
: `${name} could not copy this conversation. Try again.`,
|
||||
'providerRejected'
|
||||
)
|
||||
})
|
||||
const current = await requireCurrent()
|
||||
if (!copy.sessionId.trim() || copy.sessionId === providerSessionId) {
|
||||
fail(`${name} did not save an independent chat copy. Try again.`)
|
||||
@@ -246,7 +82,7 @@ export async function prepareStructuredAgentSessionFork(input: {
|
||||
const providerHandle = {
|
||||
transport: metadata.definition.handleTransport,
|
||||
agent: input.agent,
|
||||
nativeId: metadata.transcriptImport.handleNamesTranscript ? copy.filePath! : copy.sessionId,
|
||||
nativeId: transcriptImport.handleNamesTranscript ? copy.filePath! : copy.sessionId,
|
||||
...(copy.resumeCursor ? { resumeCursor: copy.resumeCursor } : {})
|
||||
}
|
||||
const prepared = prepareForkSnapshot({
|
||||
@@ -260,7 +96,7 @@ export async function prepareStructuredAgentSessionFork(input: {
|
||||
envelope: input.envelope,
|
||||
fork: {
|
||||
sessionId: record.sessionId,
|
||||
itemId: input.throughItemId,
|
||||
itemId: throughItemId,
|
||||
revalidate: async () => {
|
||||
await requireCurrent()
|
||||
},
|
||||
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
import { vi } from 'vitest'
|
||||
import { mkdir, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture'
|
||||
import {
|
||||
claudeProviderHandle,
|
||||
codexProviderHandle
|
||||
} from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
|
||||
import { agentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentJournalSnapshot } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { prepareStructuredAgentSessionFork } from '../structured-agent-session-fork'
|
||||
import type { StructuredAgentSessionHost } from '../../host/structured-agent-session-host'
|
||||
import type { StructuredAgentSessionAdapter } from '../../providers/structured-agent-session-adapter'
|
||||
import type { RestTestRig } from '../../host/testing/structured-agent-session-rest-test-rig'
|
||||
import { structuredAgentSessionCreateParams } from '../../../../../shared/agent-session/structured-agent-session-create'
|
||||
|
||||
const SOURCE = '019e6b26-18e2-7103-b7a0-7ba6bb071123'
|
||||
const COPY = '019e6b26-18e2-7103-b7a0-7ba6bb071124'
|
||||
|
||||
export function forkTestSource(rig: RestTestRig, agent: 'claude' | 'codex' = 'codex') {
|
||||
let admissions = 0
|
||||
let capability: 'checkpoint' | 'tip' = 'checkpoint'
|
||||
const record = agentSessionRecordFixture({
|
||||
sessionId: 'source-chat',
|
||||
provider: agent,
|
||||
accountHome: {
|
||||
variable: agent === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME',
|
||||
path: join(rig.root, 'source-account')
|
||||
},
|
||||
options: { model: 'retired-model', effort: 'high', fastMode: 'false' },
|
||||
permissionMode: 'accept-edits',
|
||||
launchArgs: ['--no-daemon'],
|
||||
launchDirectory: rig.root,
|
||||
providerHandleChain: [
|
||||
{
|
||||
linkId: 'source-head',
|
||||
origin: 'created',
|
||||
mintedAtFence: 1,
|
||||
observedAt: 1,
|
||||
handle:
|
||||
agent === 'claude' ? claudeProviderHandle(SOURCE, 'answer') : codexProviderHandle(SOURCE)
|
||||
}
|
||||
]
|
||||
})
|
||||
const snapshot: AgentJournalSnapshot = {
|
||||
sessionId: record.sessionId,
|
||||
cursor: { epoch: 'source-epoch', sequence: 5 },
|
||||
submissions: [],
|
||||
items: [
|
||||
{
|
||||
itemId: agentJournalItemKey({
|
||||
provider: 'codex',
|
||||
threadId: SOURCE,
|
||||
turnId: 'completed-turn',
|
||||
ordinal: 0
|
||||
}),
|
||||
sequence: 1,
|
||||
revision: 1,
|
||||
observedAt: 1,
|
||||
body: {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'Remember the nonce 57319' }]
|
||||
}
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:codex:source:ended-root',
|
||||
sequence: 2,
|
||||
revision: 1,
|
||||
observedAt: 2,
|
||||
body: { kind: 'turn', turnId: 'completed-turn', state: 'completed' }
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:codex:source:selected-response',
|
||||
sequence: 3,
|
||||
revision: 1,
|
||||
observedAt: 3,
|
||||
turnScope: { kind: 'turn', turnItemId: 'legacy:codex:source:ended-root' },
|
||||
body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Remembered' }] }
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:codex:source:running-root',
|
||||
sequence: 3,
|
||||
revision: 1,
|
||||
observedAt: 3,
|
||||
body: { kind: 'turn', turnId: 'active-turn', state: 'running' }
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:codex:source:ended-child',
|
||||
sequence: 4,
|
||||
revision: 1,
|
||||
observedAt: 4,
|
||||
agentId: 'child',
|
||||
body: { kind: 'turn', turnId: 'child-turn', state: 'completed' }
|
||||
}
|
||||
]
|
||||
}
|
||||
const copy = vi.fn(
|
||||
async (
|
||||
_input: Parameters<NonNullable<StructuredAgentSessionAdapter['copyConversation']>>[0]
|
||||
): ReturnType<NonNullable<StructuredAgentSessionAdapter['copyConversation']>> => {
|
||||
const dir =
|
||||
agent === 'claude'
|
||||
? join(rig.root, 'source-account', 'projects', 'workspace')
|
||||
: join(rig.root, 'source-account', 'sessions', '2026', '11', '03')
|
||||
await mkdir(dir, { recursive: true })
|
||||
const filePath = join(
|
||||
dir,
|
||||
agent === 'claude' ? `${COPY}.jsonl` : `rollout-2026-11-03T19-00-00-${COPY}.jsonl`
|
||||
)
|
||||
if (agent === 'claude') {
|
||||
await writeFile(
|
||||
filePath,
|
||||
`${[
|
||||
{
|
||||
type: 'user',
|
||||
uuid: 'prompt',
|
||||
parentUuid: null,
|
||||
sessionId: COPY,
|
||||
timestamp: '2026-11-03T19:00:00.000Z',
|
||||
cwd: rig.root,
|
||||
message: { role: 'user', content: 'Remember the nonce 57319' }
|
||||
},
|
||||
{
|
||||
type: 'assistant',
|
||||
uuid: 'answer',
|
||||
parentUuid: 'prompt',
|
||||
sessionId: COPY,
|
||||
timestamp: '2026-11-03T19:00:01.000Z',
|
||||
message: {
|
||||
id: 'msg_answer',
|
||||
role: 'assistant',
|
||||
model: 'claude-opus-5-5',
|
||||
content: [{ type: 'text', text: 'Remembered' }],
|
||||
stop_reason: 'end_turn'
|
||||
}
|
||||
}
|
||||
]
|
||||
.map((row) => JSON.stringify(row))
|
||||
.join('\n')}\n`
|
||||
)
|
||||
return {
|
||||
sessionId: COPY,
|
||||
filePath,
|
||||
coverage: {
|
||||
unit: agent === 'claude' ? 'claude-entry' : 'codex-turn',
|
||||
ids: agent === 'claude' ? ['prompt', 'answer'] : ['completed-turn']
|
||||
},
|
||||
...(agent === 'claude' ? { resumeCursor: 'answer' } : {})
|
||||
}
|
||||
}
|
||||
await writeFile(
|
||||
filePath,
|
||||
`${[
|
||||
{
|
||||
type: 'session_meta',
|
||||
payload: { id: COPY, timestamp: '2026-11-03T19:00:00.000Z', cwd: rig.root }
|
||||
},
|
||||
{
|
||||
type: 'response_item',
|
||||
timestamp: '2026-11-03T19:00:01.000Z',
|
||||
payload: { type: 'message', role: 'user', content: 'Remember the nonce 57319' }
|
||||
}
|
||||
]
|
||||
.map((row) => JSON.stringify(row))
|
||||
.join('\n')}\n`
|
||||
)
|
||||
return {
|
||||
sessionId: COPY,
|
||||
filePath,
|
||||
coverage: { unit: 'codex-turn' as const, ids: ['completed-turn'] }
|
||||
}
|
||||
}
|
||||
)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preparation reads only these source/store/adapter facets; destination founding uses the real rig host below.
|
||||
const host = {
|
||||
deps: {
|
||||
store: {
|
||||
selectWritableRecord: () => ({ kind: 'writable' }),
|
||||
requireWritableRecord: () => record,
|
||||
listConversations: () => [],
|
||||
admittedSendCount: () => admissions
|
||||
},
|
||||
agents: { capabilities: () => ({ fork: capability }) },
|
||||
adapter: { copyConversation: copy },
|
||||
logger: { warn: vi.fn() },
|
||||
resolveWorkspacePath: async () => rig.root
|
||||
},
|
||||
journalSnapshot: async () => snapshot
|
||||
} as unknown as StructuredAgentSessionHost
|
||||
const intent = structuredAgentSessionCreateParams({
|
||||
sessionId: `${agent}_independent_child`,
|
||||
agent,
|
||||
worktree: 'id:workspace-1',
|
||||
forkFrom: {
|
||||
sessionId: record.sessionId,
|
||||
throughItemId: 'legacy:codex:source:selected-response'
|
||||
},
|
||||
now: rig.clock.now,
|
||||
randomUuid: () => '00000000-0000-0000-0000-000000000123'
|
||||
})
|
||||
const prepare = () =>
|
||||
prepareStructuredAgentSessionFork({
|
||||
host,
|
||||
sessionId: record.sessionId,
|
||||
throughItemId: 'legacy:codex:source:selected-response',
|
||||
agent,
|
||||
location: record.location,
|
||||
envelope: intent.envelope
|
||||
})
|
||||
return {
|
||||
record,
|
||||
snapshot,
|
||||
copy,
|
||||
host,
|
||||
intent,
|
||||
prepare,
|
||||
admit: () => {
|
||||
admissions++
|
||||
},
|
||||
tip: () => {
|
||||
capability = 'tip'
|
||||
snapshot.items = snapshot.items.filter(
|
||||
(item) => item.itemId !== 'legacy:codex:source:running-root'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
-222
@@ -1,22 +1,17 @@
|
||||
import { forkTestSource } from './structured-agent-session-fork.test-fixture'
|
||||
import { resolveUncommittedStructuredCreate } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal'
|
||||
import { prepareStructuredAgentSessionCreateForWorktree } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create'
|
||||
import { usableJournalHistoryOrigin } from '../../../agent-session-journal/context-epochs/journal-history-origin'
|
||||
import { catchUpCodexThread } from '../../../../codex/structured/threads/codex-structured-thread-catch-up'
|
||||
import { createDeferredStructuredAgentSessionEventSink } from '../../journal-ingress/structured-agent-session-event-sink'
|
||||
import { testEventSinkLogging } from '../../host/testing/structured-agent-session-logger-test-support'
|
||||
import { handleStructuredAgentSessionCreate } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler'
|
||||
import type { StructuredAgentSessionAdapter } from '../../providers/structured-agent-session-adapter'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { appendFile, mkdir, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { appendFile } from 'node:fs/promises'
|
||||
import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture'
|
||||
import {
|
||||
claudeProviderHandle,
|
||||
codexProviderHandle
|
||||
} from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
|
||||
import { agentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentJournalSnapshot } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
|
||||
import { prepareStructuredAgentSessionFork } from '../structured-agent-session-fork'
|
||||
import type { StructuredAgentSessionHost } from '../../host/structured-agent-session-host'
|
||||
import type { StructuredAgentSessionAdapter } from '../../providers/structured-agent-session-adapter'
|
||||
import {
|
||||
createRestTestRig,
|
||||
type RestTestRig
|
||||
@@ -42,215 +37,7 @@ afterEach(async () => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function source(agent: 'claude' | 'codex' = 'codex') {
|
||||
let admissions = 0
|
||||
let capability: 'checkpoint' | 'tip' = 'checkpoint'
|
||||
const record = agentSessionRecordFixture({
|
||||
sessionId: 'source-chat',
|
||||
provider: agent,
|
||||
accountHome: {
|
||||
variable: agent === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME',
|
||||
path: join(rig.root, 'source-account')
|
||||
},
|
||||
options: { model: 'retired-model', effort: 'high', fastMode: 'false' },
|
||||
permissionMode: 'accept-edits',
|
||||
launchArgs: ['--no-daemon'],
|
||||
launchDirectory: rig.root,
|
||||
providerHandleChain: [
|
||||
{
|
||||
linkId: 'source-head',
|
||||
origin: 'created',
|
||||
mintedAtFence: 1,
|
||||
observedAt: 1,
|
||||
handle:
|
||||
agent === 'claude' ? claudeProviderHandle(SOURCE, 'answer') : codexProviderHandle(SOURCE)
|
||||
}
|
||||
]
|
||||
})
|
||||
const snapshot: AgentJournalSnapshot = {
|
||||
sessionId: record.sessionId,
|
||||
cursor: { epoch: 'source-epoch', sequence: 5 },
|
||||
submissions: [],
|
||||
items: [
|
||||
{
|
||||
itemId: agentJournalItemKey({
|
||||
provider: 'codex',
|
||||
threadId: SOURCE,
|
||||
turnId: 'completed-turn',
|
||||
ordinal: 0
|
||||
}),
|
||||
sequence: 1,
|
||||
revision: 1,
|
||||
observedAt: 1,
|
||||
body: {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'Remember the nonce 57319' }]
|
||||
}
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:codex:source:ended-root',
|
||||
sequence: 2,
|
||||
revision: 1,
|
||||
observedAt: 2,
|
||||
body: { kind: 'turn', turnId: 'completed-turn', state: 'completed' }
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:codex:source:selected-response',
|
||||
sequence: 3,
|
||||
revision: 1,
|
||||
observedAt: 3,
|
||||
turnScope: { kind: 'turn', turnItemId: 'legacy:codex:source:ended-root' },
|
||||
body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Remembered' }] }
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:codex:source:running-root',
|
||||
sequence: 3,
|
||||
revision: 1,
|
||||
observedAt: 3,
|
||||
body: { kind: 'turn', turnId: 'active-turn', state: 'running' }
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:codex:source:ended-child',
|
||||
sequence: 4,
|
||||
revision: 1,
|
||||
observedAt: 4,
|
||||
agentId: 'child',
|
||||
body: { kind: 'turn', turnId: 'child-turn', state: 'completed' }
|
||||
}
|
||||
]
|
||||
}
|
||||
const copy = vi.fn(
|
||||
async (
|
||||
_input: Parameters<NonNullable<StructuredAgentSessionAdapter['copyConversation']>>[0]
|
||||
): ReturnType<NonNullable<StructuredAgentSessionAdapter['copyConversation']>> => {
|
||||
const dir =
|
||||
agent === 'claude'
|
||||
? join(rig.root, 'source-account', 'projects', 'workspace')
|
||||
: join(rig.root, 'source-account', 'sessions', '2026', '11', '03')
|
||||
await mkdir(dir, { recursive: true })
|
||||
const filePath = join(
|
||||
dir,
|
||||
agent === 'claude' ? `${COPY}.jsonl` : `rollout-2026-11-03T19-00-00-${COPY}.jsonl`
|
||||
)
|
||||
if (agent === 'claude') {
|
||||
await writeFile(
|
||||
filePath,
|
||||
`${[
|
||||
{
|
||||
type: 'user',
|
||||
uuid: 'prompt',
|
||||
parentUuid: null,
|
||||
sessionId: COPY,
|
||||
timestamp: '2026-11-03T19:00:00.000Z',
|
||||
cwd: rig.root,
|
||||
message: { role: 'user', content: 'Remember the nonce 57319' }
|
||||
},
|
||||
{
|
||||
type: 'assistant',
|
||||
uuid: 'answer',
|
||||
parentUuid: 'prompt',
|
||||
sessionId: COPY,
|
||||
timestamp: '2026-11-03T19:00:01.000Z',
|
||||
message: {
|
||||
id: 'msg_answer',
|
||||
role: 'assistant',
|
||||
model: 'claude-opus-5-5',
|
||||
content: [{ type: 'text', text: 'Remembered' }],
|
||||
stop_reason: 'end_turn'
|
||||
}
|
||||
}
|
||||
]
|
||||
.map((row) => JSON.stringify(row))
|
||||
.join('\n')}\n`
|
||||
)
|
||||
return {
|
||||
sessionId: COPY,
|
||||
filePath,
|
||||
coverage: {
|
||||
unit: agent === 'claude' ? 'claude-entry' : 'codex-turn',
|
||||
ids: agent === 'claude' ? ['prompt', 'answer'] : ['completed-turn']
|
||||
},
|
||||
...(agent === 'claude' ? { resumeCursor: 'answer' } : {})
|
||||
}
|
||||
}
|
||||
await writeFile(
|
||||
filePath,
|
||||
`${[
|
||||
{
|
||||
type: 'session_meta',
|
||||
payload: { id: COPY, timestamp: '2026-11-03T19:00:00.000Z', cwd: rig.root }
|
||||
},
|
||||
{
|
||||
type: 'response_item',
|
||||
timestamp: '2026-11-03T19:00:01.000Z',
|
||||
payload: { type: 'message', role: 'user', content: 'Remember the nonce 57319' }
|
||||
}
|
||||
]
|
||||
.map((row) => JSON.stringify(row))
|
||||
.join('\n')}\n`
|
||||
)
|
||||
return {
|
||||
sessionId: COPY,
|
||||
filePath,
|
||||
coverage: { unit: 'codex-turn' as const, ids: ['completed-turn'] }
|
||||
}
|
||||
}
|
||||
)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preparation reads only these source/store/adapter facets; destination founding uses the real rig host below.
|
||||
const host = {
|
||||
deps: {
|
||||
store: {
|
||||
selectWritableRecord: () => ({ kind: 'writable' }),
|
||||
requireWritableRecord: () => record,
|
||||
listConversations: () => [],
|
||||
admittedSendCount: () => admissions
|
||||
},
|
||||
agents: { capabilities: () => ({ fork: capability }) },
|
||||
adapter: { copyConversation: copy },
|
||||
logger: { warn: vi.fn() },
|
||||
resolveWorkspacePath: async () => rig.root
|
||||
},
|
||||
journalSnapshot: async () => snapshot
|
||||
} as unknown as StructuredAgentSessionHost
|
||||
const intent = structuredAgentSessionCreateParams({
|
||||
sessionId: `${agent}_independent_child`,
|
||||
agent,
|
||||
worktree: 'id:workspace-1',
|
||||
forkFrom: {
|
||||
sessionId: record.sessionId,
|
||||
throughItemId: 'legacy:codex:source:selected-response'
|
||||
},
|
||||
now: rig.clock.now,
|
||||
randomUuid: () => '00000000-0000-0000-0000-000000000123'
|
||||
})
|
||||
const prepare = () =>
|
||||
prepareStructuredAgentSessionFork({
|
||||
host,
|
||||
sessionId: record.sessionId,
|
||||
throughItemId: 'legacy:codex:source:selected-response',
|
||||
agent,
|
||||
location: record.location,
|
||||
envelope: intent.envelope
|
||||
})
|
||||
return {
|
||||
record,
|
||||
snapshot,
|
||||
copy,
|
||||
host,
|
||||
intent,
|
||||
prepare,
|
||||
admit: () => {
|
||||
admissions++
|
||||
},
|
||||
tip: () => {
|
||||
capability = 'tip'
|
||||
snapshot.items = snapshot.items.filter(
|
||||
(item) => item.itemId !== 'legacy:codex:source:running-root'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
const source = (agent: 'claude' | 'codex' = 'codex') => forkTestSource(rig, agent)
|
||||
|
||||
it('copies the selected retained root, founds its relationship, and replays before source discovery', async () => {
|
||||
const test = source()
|
||||
@@ -587,12 +374,14 @@ it('refuses a tip copy after its source head relaunches', async () => {
|
||||
]
|
||||
return nativeCopy(input)
|
||||
})
|
||||
await expect(test.prepare()).rejects.toMatchObject({
|
||||
const result = await resolveUncommittedStructuredCreate(test.prepare)
|
||||
expect(result).toMatchObject({
|
||||
refusal: {
|
||||
code: 'agent_session_operation_invalid',
|
||||
details: { reason: 'savedConversationMissing' }
|
||||
}
|
||||
})
|
||||
expect(result).not.toHaveProperty('refusal.createAttemptRefusedBeforeCommit')
|
||||
})
|
||||
|
||||
it('coalesces concurrent fork create replay and refuses a conflicting fork intent', async () => {
|
||||
@@ -734,10 +523,49 @@ it('forks an inherited Codex reply through its original and refuses it after the
|
||||
])
|
||||
test.host.journalSnapshot = async (id) => retainedCopies.get(id) ?? test.snapshot
|
||||
test.snapshot.items = test.snapshot.items.slice(0, 1)
|
||||
await expect(prepare()).rejects.toMatchObject({
|
||||
expect(await resolveUncommittedStructuredCreate(prepare)).toMatchObject({
|
||||
refusal: {
|
||||
code: 'agent_session_operation_invalid',
|
||||
details: { reason: 'savedConversationMissing' }
|
||||
details: { reason: 'savedConversationMissing' },
|
||||
createAttemptRefusedBeforeCommit: true
|
||||
}
|
||||
})
|
||||
records.delete('source-chat')
|
||||
expect(await resolveUncommittedStructuredCreate(prepare)).toMatchObject({
|
||||
refusal: {
|
||||
code: 'agent_session_identity_required',
|
||||
details: { reason: 'recordMissing' },
|
||||
createAttemptRefusedBeforeCommit: true
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('checks an inherited tip against the original and refuses after the original advances', async () => {
|
||||
const test = source()
|
||||
test.tip()
|
||||
const inherited = structuredClone(test.snapshot)
|
||||
test.record.forkedFrom = {
|
||||
sessionId: 'original',
|
||||
itemId: 'legacy:codex:source:selected-response',
|
||||
childBoundary: { kind: 'item', itemId: 'legacy:codex:source:selected-response' }
|
||||
}
|
||||
const original = { ...test.record, sessionId: 'original', forkedFrom: undefined }
|
||||
test.host.deps.store.requireWritableRecord = (id) => (id === 'original' ? original : test.record)
|
||||
test.host.deps.store.getRecord = (id) => (id === 'original' ? original : test.record)
|
||||
test.host.journalSnapshot = async (id) => (id === 'original' ? test.snapshot : inherited)
|
||||
expect((await test.prepare()).fork?.sessionId).toBe('original')
|
||||
test.snapshot.items.push({
|
||||
itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:later-user:0',
|
||||
sequence: 10,
|
||||
revision: 1,
|
||||
observedAt: 10,
|
||||
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'new original prompt' }] }
|
||||
})
|
||||
expect(await resolveUncommittedStructuredCreate(test.prepare)).toMatchObject({
|
||||
refusal: {
|
||||
code: 'agent_session_operation_invalid',
|
||||
details: { reason: 'turnActive' },
|
||||
createAttemptRefusedBeforeCommit: true
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+77
@@ -1,3 +1,10 @@
|
||||
import { AgentSessionJournal } from '../../../agent-session-journal/journal-store'
|
||||
import { recoverStructuredRewind } from '../../rewind/structured-rewind-recovery'
|
||||
import { persistRewindRecord } from '../../rewind/structured-rewind-record'
|
||||
import {
|
||||
projectForkMarker,
|
||||
readForkMarker
|
||||
} from '../../publication/history/agent-session-fork-marker'
|
||||
import { expectAtomicRewindCompletion } from './structured-agent-session-rewind-replay.test-fixture'
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
@@ -294,3 +301,73 @@ it('refuses inherited rewind and rewinds the first own prompt to the fork point'
|
||||
[{ type: 'text', text: '2' }]
|
||||
])
|
||||
})
|
||||
|
||||
it('completes an inherited rewind saved by the PR1 build with an atomic surviving divider after restart', async () => {
|
||||
const target = await seed()
|
||||
const fence = store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence
|
||||
const journal = host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal
|
||||
await store.commitOperationReceipt(
|
||||
store.conversationReceipts.forkBoundary(HOST_TEST_SESSION, {
|
||||
sessionId: 'original-chat',
|
||||
itemId: 'codex:original-thread:tip:0',
|
||||
childBoundary: { kind: 'item', itemId: 'codex:019fd532-7c11-7a90-b6de-4e1a2c3d5f60:tip:0' }
|
||||
})
|
||||
)
|
||||
await persistRewindRecord(store, HOST_TEST_SESSION, fence, {
|
||||
operationId: hostTestOperationId(),
|
||||
callerKey: 'desktop',
|
||||
itemId: target,
|
||||
expectedEpoch: journal.epoch,
|
||||
phase: 'provider-succeeded',
|
||||
providerRevert: {
|
||||
threadId: '019fd532-7c11-7a90-b6de-4e1a2c3d5f60',
|
||||
beforeTurnId: 'drop',
|
||||
keptTurnId: 'kept'
|
||||
}
|
||||
})
|
||||
await journal.close()
|
||||
store = await openTestAgentSessionRecordStore(directory)
|
||||
const reopened = new AgentSessionJournal({
|
||||
identity: {
|
||||
sessionId: HOST_TEST_SESSION,
|
||||
workspaceId: 'workspace-1',
|
||||
hostId: 'local',
|
||||
agent: 'codex',
|
||||
providerHandle: codexProviderHandle('019fd532-7c11-7a90-b6de-4e1a2c3d5f60')
|
||||
},
|
||||
database: openTestJournalHostDatabase(directory)
|
||||
})
|
||||
await reopened.open()
|
||||
const replace = reopened.replaceEpochItems.bind(reopened)
|
||||
vi.spyOn(reopened, 'replaceEpochItems').mockImplementationOnce(async (...args) => {
|
||||
await replace(...args)
|
||||
throw new Error('crash after atomic completion')
|
||||
})
|
||||
await expect(
|
||||
recoverStructuredRewind(
|
||||
{ store, logger: createStructuredAgentSessionLogger() },
|
||||
HOST_TEST_SESSION,
|
||||
reopened,
|
||||
fence
|
||||
)
|
||||
).rejects.toThrow('crash after atomic completion')
|
||||
await reopened.close()
|
||||
store = await openTestAgentSessionRecordStore(directory)
|
||||
await reopened.open()
|
||||
await recoverStructuredRewind(
|
||||
{ store, logger: createStructuredAgentSessionLogger() },
|
||||
HOST_TEST_SESSION,
|
||||
reopened,
|
||||
fence
|
||||
)
|
||||
expect(store.getRecord(HOST_TEST_SESSION)?.forkedFrom?.childBoundary).toEqual({
|
||||
kind: 'item',
|
||||
itemId: 'codex:019fd532-7c11-7a90-b6de-4e1a2c3d5f60:kept:0'
|
||||
})
|
||||
expect(
|
||||
projectForkMarker(reopened.snapshot(), readForkMarker(store, HOST_TEST_SESSION)).items.map(
|
||||
(item) => item.itemId
|
||||
)
|
||||
).toEqual(['codex:019fd532-7c11-7a90-b6de-4e1a2c3d5f60:kept:0', 'orca:forked-from'])
|
||||
await reopened.close()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentSessionForkedFrom } from '../../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import type { AgentJournalRenderItem } from '../../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type { JournalReplacementItem } from '../../agent-session-journal/context-epochs/journal-epoch-replacement'
|
||||
|
||||
/** Rows below a clear floor survive unchanged; replacement rows keep their actual correspondence. */
|
||||
export function remapForkChildBoundary(
|
||||
boundary: AgentSessionForkedFrom['childBoundary'],
|
||||
old: readonly AgentJournalRenderItem[],
|
||||
kept: readonly JournalReplacementItem[],
|
||||
floor?: number
|
||||
): AgentSessionForkedFrom['childBoundary'] {
|
||||
if (boundary.kind === 'start') {
|
||||
return boundary
|
||||
}
|
||||
const anchorIndex = old.findIndex((row) => row.itemId === boundary.itemId)
|
||||
if (anchorIndex === -1) {
|
||||
return { kind: 'start' }
|
||||
}
|
||||
const keptIds = new Set(kept.map((row) => agentJournalItemKey(row.identity)))
|
||||
const survivor = old
|
||||
.slice(0, anchorIndex + 1)
|
||||
.findLast((row) => (floor !== undefined && row.sequence <= floor) || keptIds.has(row.itemId))
|
||||
return survivor ? { kind: 'item', itemId: survivor.itemId } : { kind: 'start' }
|
||||
}
|
||||
@@ -214,13 +214,14 @@ export async function rewindStructuredAgentSession(
|
||||
journal,
|
||||
fence,
|
||||
undefined,
|
||||
(rewind, currentFence, cursor, cancel) => {
|
||||
(rewind, currentFence, cursor, cancel, childBoundary) => {
|
||||
completionReceipt = store.conversationReceipts.rewind(
|
||||
sessionId,
|
||||
currentFence,
|
||||
rewind,
|
||||
cursor,
|
||||
cancel
|
||||
cancel,
|
||||
childBoundary
|
||||
)
|
||||
return ctx.operationReceipt!
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import { usableJournalHistoryOrigin } from '../../agent-session-journal/context-epochs/journal-history-origin'
|
||||
import { remapForkChildBoundary } from './agent-session-fork-boundary-remap'
|
||||
import {
|
||||
inheritForkName,
|
||||
persistRewindRecord,
|
||||
@@ -60,7 +61,8 @@ export async function recoverStructuredRewind(
|
||||
rewind: AgentSessionRewindRecord,
|
||||
fence: number,
|
||||
cursor: AgentJournalCursor,
|
||||
cancel?: UsageLimitContinueIdentity
|
||||
cancel?: UsageLimitContinueIdentity,
|
||||
childBoundary?: NonNullable<AgentSessionRecord['forkedFrom']>['childBoundary']
|
||||
) => JournalOperationReceipt,
|
||||
signal?: AbortSignal
|
||||
): Promise<void> {
|
||||
@@ -128,7 +130,8 @@ export async function applyStructuredRewindRecovery(
|
||||
rewind: AgentSessionRewindRecord,
|
||||
fence: number,
|
||||
cursor: AgentJournalCursor,
|
||||
cancel?: UsageLimitContinueIdentity
|
||||
cancel?: UsageLimitContinueIdentity,
|
||||
childBoundary?: NonNullable<AgentSessionRecord['forkedFrom']>['childBoundary']
|
||||
) => JournalOperationReceipt
|
||||
): Promise<void> {
|
||||
const { store } = deps
|
||||
@@ -183,6 +186,16 @@ export async function applyStructuredRewindRecovery(
|
||||
if (rewind.phase !== 'provider-succeeded') {
|
||||
return
|
||||
}
|
||||
const oldBoundary = store.getRecord(sessionId)?.forkedFrom?.childBoundary
|
||||
const childBoundary =
|
||||
oldBoundary && !alreadyReplaced && cut
|
||||
? remapForkChildBoundary(
|
||||
oldBoundary,
|
||||
journal.currentRead().items,
|
||||
cut.kept,
|
||||
journal.context.floor()?.sequence
|
||||
)
|
||||
: oldBoundary
|
||||
const completed = rewind
|
||||
const record = store.getRecord(sessionId)!
|
||||
const providerHandle = completed.providerFork
|
||||
@@ -255,8 +268,15 @@ export async function applyStructuredRewindRecovery(
|
||||
write: (db, row) => {
|
||||
// The prepared fold is the result written before this completion receipt.
|
||||
staged =
|
||||
receipt?.(completed, fence, cursor, cancel) ??
|
||||
store.conversationReceipts.rewind(sessionId, fence, completed, cursor, cancel)
|
||||
receipt?.(completed, fence, cursor, cancel, childBoundary) ??
|
||||
store.conversationReceipts.rewind(
|
||||
sessionId,
|
||||
fence,
|
||||
completed,
|
||||
cursor,
|
||||
cancel,
|
||||
childBoundary
|
||||
)
|
||||
staged.write(db, row)
|
||||
},
|
||||
committed: () => staged.committed()
|
||||
|
||||
@@ -47,7 +47,8 @@ export function commitAgentSessionRewindCompletion(
|
||||
fence: number,
|
||||
rewind: AgentSessionRewindRecord,
|
||||
cursor: AgentJournalCursor,
|
||||
cancel?: UsageLimitContinueIdentity
|
||||
cancel?: UsageLimitContinueIdentity,
|
||||
childBoundary?: NonNullable<AgentSessionRecord['forkedFrom']>['childBoundary']
|
||||
): void {
|
||||
const record = draft.records.get(sessionId)
|
||||
if (
|
||||
@@ -71,6 +72,9 @@ export function commitAgentSessionRewindCompletion(
|
||||
}
|
||||
draft.records.set(sessionId, {
|
||||
...(cancel ? cancelAgentSessionUsageLimitContinue(record, cancel) : record),
|
||||
...(childBoundary && record.forkedFrom
|
||||
? { forkedFrom: { ...record.forkedFrom, childBoundary } }
|
||||
: {}),
|
||||
providerHandleChain: rewindProviderChain(record, rewind, fence),
|
||||
rewind: {
|
||||
...current,
|
||||
|
||||
+5
-1
@@ -40,12 +40,16 @@ const PRECOMMIT_REFUSAL_MESSAGE = 'Orca cannot open a structured agent chat for
|
||||
function precommitRefusal(error: unknown, agent?: string): AgentSessionWireRefusal {
|
||||
// A refusal the host raised keeps its situation; a bare code names none.
|
||||
if (isAgentSessionRefusalError(error)) {
|
||||
return agentSessionRefusalFromReference(
|
||||
const refusal = agentSessionRefusalFromReference(
|
||||
error.refusal,
|
||||
error.cause instanceof AgentConversationCopyError
|
||||
? error.cause.message
|
||||
: PRECOMMIT_REFUSAL_MESSAGE
|
||||
)
|
||||
return error.cause instanceof AgentConversationCopyError &&
|
||||
error.refusal.createAttemptRefusedBeforeCommit
|
||||
? { ...refusal, createAttemptRefusedBeforeCommit: true }
|
||||
: refusal
|
||||
}
|
||||
const code = wireRefusalCode(error)
|
||||
if (code) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { agentSessionForkSourceFailureWords } from '../../../../../../shared/agent-session/failures/agent-session-failure-copy'
|
||||
import { sayAgentSessionFailureTranslated } from '../notices/agent-session-failure-words-text'
|
||||
import { toast } from 'sonner'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { useAppStore } from '@/store'
|
||||
@@ -200,6 +202,17 @@ function forkFailureDetail(agentLabel: string, error: unknown): string {
|
||||
if (code === 'structured_agent_session_host_permission') {
|
||||
return hostPermissionRefusedText(agentLabel, 'refused')
|
||||
}
|
||||
const sourceFailure =
|
||||
error instanceof StructuredAgentSessionCreateRefusalError
|
||||
? agentSessionForkSourceFailureWords(
|
||||
error.message,
|
||||
agentLabel,
|
||||
sayAgentSessionFailureTranslated
|
||||
)
|
||||
: null
|
||||
if (sourceFailure) {
|
||||
return sourceFailure
|
||||
}
|
||||
const causeText = structuredLaunchFailure(error)?.causeText
|
||||
if (causeText) {
|
||||
return causeText
|
||||
|
||||
+46
@@ -1,3 +1,4 @@
|
||||
import { nativeChatForkInventory } from '../../../../../../shared/native-chat/native-chat-fork-offer'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
|
||||
@@ -91,3 +92,48 @@ describe('the side chat fork point the transcript finds while laying out', () =>
|
||||
).toEqual({ kind: 'no-reply' })
|
||||
})
|
||||
})
|
||||
|
||||
it('offers the inherited source tip while a later child response is running', () => {
|
||||
const { input, latestTurnKey } = conversation(
|
||||
[
|
||||
{ ask: 'inherited-user', replies: [row('legacy:opencode:source:reply-1', 'assistant', 1)] },
|
||||
{ ask: 'own-user', replies: [row('legacy:opencode:child:reply-2', 'assistant', 4)] }
|
||||
],
|
||||
true
|
||||
)
|
||||
const inventory = nativeChatForkInventory([
|
||||
{
|
||||
itemId: 'legacy:opencode:source:reply-1',
|
||||
sequence: 1,
|
||||
body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'copied' }] }
|
||||
},
|
||||
{
|
||||
itemId: 'orca:forked-from',
|
||||
sequence: 1,
|
||||
body: { kind: 'status', text: 'Forked from source', presentation: 'forked-from' }
|
||||
},
|
||||
{
|
||||
itemId: 'legacy:opencode:child:reply-2',
|
||||
sequence: 4,
|
||||
body: {
|
||||
kind: 'message',
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text: 'local partial' }]
|
||||
}
|
||||
}
|
||||
])
|
||||
const chat = {
|
||||
support: { kind: 'known', fork: 'tip' },
|
||||
contextFloorSequence: 0,
|
||||
...inventory
|
||||
} as const
|
||||
expect(
|
||||
buildNativeChatTranscript({ ...input, forkOffer: { chat, latestTurnKey } }).forkPoint
|
||||
).toEqual({ kind: 'ready', throughItemId: 'legacy:opencode:source:reply-1' })
|
||||
expect(
|
||||
buildNativeChatTranscript({
|
||||
...input,
|
||||
forkOffer: { chat: { ...chat, contextFloorSequence: 2 }, latestTurnKey }
|
||||
}).forkPoint
|
||||
).toEqual({ kind: 'reply-running' })
|
||||
})
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { AgentType } from '../../../../../../shared/agent-status/contracts/
|
||||
import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config'
|
||||
import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target'
|
||||
import {
|
||||
nativeChatForkableItemIds,
|
||||
nativeChatForkInventory,
|
||||
nativeChatForkSupport,
|
||||
nativeChatLatestForkItemId,
|
||||
type NativeChatForkSupport
|
||||
@@ -49,6 +49,7 @@ export type NativeChatForkLatestOutcome = 'started' | 'pending' | 'none'
|
||||
export type NativeChatForkSurface = NativeChatForkRowAction & {
|
||||
contextFloorSequence: number
|
||||
forkableItemIds: ReadonlySet<string>
|
||||
inheritedThroughSequence?: number
|
||||
/** Handed to offered rows, so a change in which rows offer it re-renders only those rows. */
|
||||
rowAction: NativeChatForkRowAction
|
||||
}
|
||||
@@ -122,13 +123,15 @@ export function useNativeChatFork(input: {
|
||||
// Streaming replaces the items array on every commit; keep the set while its members hold, so the
|
||||
// context and every offered row's `fork` stay the same objects.
|
||||
const forkableRef = useRef<ReadonlySet<string>>(new Set())
|
||||
const inventory = useMemo(() => nativeChatForkInventory(input.items), [input.items])
|
||||
const { inheritedThroughSequence } = inventory
|
||||
const forkableItemIds = useMemo(() => {
|
||||
const next = nativeChatForkableItemIds(input.items)
|
||||
const next = inventory.forkableItemIds
|
||||
const previous = forkableRef.current
|
||||
return next.size === previous.size && [...next].every((id) => previous.has(id))
|
||||
? previous
|
||||
: next
|
||||
}, [input.items])
|
||||
}, [inventory])
|
||||
useLayoutEffect(() => {
|
||||
forkableRef.current = forkableItemIds
|
||||
}, [forkableItemIds])
|
||||
@@ -142,7 +145,7 @@ export function useNativeChatFork(input: {
|
||||
latestAgentSessionContextClearSequence(items),
|
||||
agentSessionContextFloorSequence(contextFloor, epoch)
|
||||
),
|
||||
forkableItemIds: nativeChatForkableItemIds(items)
|
||||
forkableItemIds: nativeChatForkInventory(items).forkableItemIds
|
||||
})
|
||||
if (!throughItemId) {
|
||||
return 'none'
|
||||
@@ -164,11 +167,19 @@ export function useNativeChatFork(input: {
|
||||
() =>
|
||||
supportKind === 'none' || !input.worktreeId || !isTuiAgent(input.agent)
|
||||
? undefined
|
||||
: { ...rowAction, contextFloorSequence, forkableItemIds, rowAction, forkLatest },
|
||||
: {
|
||||
...rowAction,
|
||||
contextFloorSequence,
|
||||
forkableItemIds,
|
||||
inheritedThroughSequence,
|
||||
rowAction,
|
||||
forkLatest
|
||||
},
|
||||
[
|
||||
contextFloorSequence,
|
||||
forkableItemIds,
|
||||
forkLatest,
|
||||
inheritedThroughSequence,
|
||||
input.agent,
|
||||
input.worktreeId,
|
||||
rowAction,
|
||||
|
||||
+15
-2
@@ -73,15 +73,28 @@ export function useNativeChatSideChatForkOffer(
|
||||
const mode = fork?.support.kind === 'known' ? fork.support.fork : undefined
|
||||
const forkableItemIds = fork?.forkableItemIds
|
||||
const contextFloorSequence = fork?.contextFloorSequence
|
||||
const inheritedThroughSequence = fork?.inheritedThroughSequence
|
||||
return useMemo(
|
||||
() =>
|
||||
listening && mode && forkableItemIds && contextFloorSequence !== undefined
|
||||
? {
|
||||
chat: { support: { kind: 'known', fork: mode }, contextFloorSequence, forkableItemIds },
|
||||
chat: {
|
||||
support: { kind: 'known', fork: mode },
|
||||
contextFloorSequence,
|
||||
forkableItemIds,
|
||||
inheritedThroughSequence
|
||||
},
|
||||
latestTurnKey
|
||||
}
|
||||
: undefined,
|
||||
[contextFloorSequence, forkableItemIds, latestTurnKey, listening, mode]
|
||||
[
|
||||
contextFloorSequence,
|
||||
forkableItemIds,
|
||||
inheritedThroughSequence,
|
||||
latestTurnKey,
|
||||
listening,
|
||||
mode
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+12
@@ -19,6 +19,18 @@ import { START_FAILURE_PIECES } from './agent-session-start-failure-words-text'
|
||||
const PIECES: Record<AgentSessionFailureCopyId, (values: AgentSessionFailureCopyValues) => string> =
|
||||
{
|
||||
theAgent: () => translate('components.native-chat.failureWords.theAgent', COPY.theAgent),
|
||||
forkOriginalMissing: (values) =>
|
||||
translate(
|
||||
'components.native-chat.failureWords.forkOriginalMissing',
|
||||
COPY.forkOriginalMissing,
|
||||
values
|
||||
),
|
||||
forkOriginalUnavailable: (values) =>
|
||||
translate(
|
||||
'components.native-chat.failureWords.forkOriginalUnavailable',
|
||||
COPY.forkOriginalUnavailable,
|
||||
values
|
||||
),
|
||||
pluginInputRequired: (values) =>
|
||||
translate(
|
||||
'components.native-chat.failureWords.pluginInputRequired',
|
||||
|
||||
+2
@@ -1600,6 +1600,8 @@
|
||||
"couldNotStopTheAgent": "Couldn't stop the agent.",
|
||||
"editSavedArguments": "Edit them in Settings > Agents > Arguments.",
|
||||
"emptyMessage": "This message is empty, so it was not sent.",
|
||||
"forkOriginalMissing": "{{agent}} could not find this response in the original chat. Open it and fork from there.",
|
||||
"forkOriginalUnavailable": "{{agent}} cannot fork this response in the original chat right now. Open it and fork from there.",
|
||||
"fullAccessAsRoot": "{{agent}} won't use Full access while it runs as root. Choose another permission for {{agent}} in Settings → Agents for the computer running this chat, then start a new chat.",
|
||||
"historyInOtherAccount": "This chat's history is in another Claude account. Switch back to that account to continue it.",
|
||||
"historyTooLarge": "This conversation's history is too large to restore here.",
|
||||
|
||||
@@ -19742,6 +19742,8 @@
|
||||
},
|
||||
"reasoning": "Reasoning",
|
||||
"failureWords": {
|
||||
"forkOriginalMissing": "{{agent}} could not find this response in the original chat. Open it and fork from there.",
|
||||
"forkOriginalUnavailable": "{{agent}} cannot fork this response in the original chat right now. Open it and fork from there.",
|
||||
"theAgent": "The agent",
|
||||
"providerStartFailed": "{{agent}} stopped before it finished starting.",
|
||||
"savedConversationMissing": "{{agent}} couldn't find this chat's saved conversation.",
|
||||
|
||||
+3
-1
@@ -11,6 +11,7 @@ import type {
|
||||
import { hasRuntimeRpcErrorCode } from '../../../../../shared/runtime-rpc-error-code'
|
||||
import {
|
||||
isAgentSessionCreateAdmissionRefusal,
|
||||
isAgentSessionForkSourceAdmissionRefusal,
|
||||
isDefinitiveAgentSessionCreateRefusal
|
||||
} from '../../../../../shared/agent-session/failures/agent-session-definitive-refusal'
|
||||
import { readAgentSessionRefusalReference } from '../../../../../shared/agent-session/failures/agent-session-wire-refusals'
|
||||
@@ -233,7 +234,8 @@ export async function launchStructuredAgentSession(
|
||||
!priorCreateOutcomeUnknown &&
|
||||
result.refusal.createAttemptRefusedBeforeCommit === true &&
|
||||
refusal !== undefined &&
|
||||
isAgentSessionCreateAdmissionRefusal(refusal)
|
||||
(isAgentSessionCreateAdmissionRefusal(refusal) ||
|
||||
(!!intent.params.forkFrom && isAgentSessionForkSourceAdmissionRefusal(refusal)))
|
||||
// Attempt proof cannot settle an earlier create whose reply was lost.
|
||||
if (
|
||||
!attemptRefusedBeforeCommit &&
|
||||
|
||||
+196
-1
@@ -1,5 +1,17 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, beforeEach, expect, it } from 'vitest'
|
||||
import '../../../../../types/build-constants.d.ts'
|
||||
import { createRestTestRig } from '../../../../../main/native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig'
|
||||
import { forkTestSource } from '../../../../../main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture'
|
||||
import { agentSessionRecordFixture } from '../../../../../main/native-chat/agent-session-record-test-fixture'
|
||||
import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
|
||||
import { setStructuredAgentSessionHost } from '../../../../../main/native-chat/agent-session-wire/host/structured-agent-session-registry'
|
||||
import type { OrcaRuntimeService } from '../../../../../main/runtime/orca-runtime'
|
||||
import { resolveStructuredAgentSessionForkIntent } from '../../../../../main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent'
|
||||
import { EVERY_AGENT_CHAT } from '../../../../../shared/native-chat/every-agent-chat.test-fixture'
|
||||
import { handleStructuredAgentSessionCreate } from '../../../../../main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler'
|
||||
import { CreateIntentParams } from '../../../../../shared/rpc-contract/structured-agent-session-params'
|
||||
import { getStructuredAgentSessionLaunchLifecycle } from './structured-agent-session-launch-registry'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
mocks,
|
||||
resetCreateMessageFixture,
|
||||
@@ -27,3 +39,186 @@ it('sends no fork to a host that does not advertise forks', async () => {
|
||||
})
|
||||
expect(mocks.call.mock.calls.some(([, method]) => method === 'agentSession.create')).toBe(false)
|
||||
})
|
||||
|
||||
async function forkHost() {
|
||||
vi.useRealTimers()
|
||||
const rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } })
|
||||
const test = forkTestSource(rig)
|
||||
test.snapshot.items[2]!.itemId = 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:completed-turn:1'
|
||||
const child = agentSessionRecordFixture({
|
||||
...test.record,
|
||||
sessionId: 'copied-chat',
|
||||
providerHandleChain: [
|
||||
{
|
||||
...test.record.providerHandleChain[0]!,
|
||||
handle: codexProviderHandle('019e6b26-18e2-7103-b7a0-7ba6bb071124')
|
||||
}
|
||||
],
|
||||
forkedFrom: {
|
||||
sessionId: 'source-chat',
|
||||
itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:completed-turn:1',
|
||||
childBoundary: {
|
||||
kind: 'item',
|
||||
itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071124:completed-turn:1'
|
||||
}
|
||||
}
|
||||
})
|
||||
const childSnapshot = {
|
||||
...structuredClone(test.snapshot),
|
||||
sessionId: child.sessionId,
|
||||
items: test.snapshot.items.map((item) => ({
|
||||
...item,
|
||||
itemId: item.itemId.replace(
|
||||
'019e6b26-18e2-7103-b7a0-7ba6bb071123',
|
||||
'019e6b26-18e2-7103-b7a0-7ba6bb071124'
|
||||
)
|
||||
}))
|
||||
}
|
||||
const records = new Map([
|
||||
['copied-chat', child],
|
||||
['source-chat', test.record]
|
||||
])
|
||||
const getRecord = rig.store.getRecord.bind(rig.store)
|
||||
const select = rig.store.selectWritableRecord.bind(rig.store)
|
||||
const writable = rig.store.requireWritableRecord.bind(rig.store)
|
||||
vi.spyOn(rig.store, 'getRecord').mockImplementation((id) => records.get(id) ?? getRecord(id))
|
||||
vi.spyOn(rig.store, 'requireWritableRecord').mockImplementation(
|
||||
(id) => records.get(id) ?? writable(id)
|
||||
)
|
||||
vi.spyOn(rig.store, 'selectWritableRecord').mockImplementation((id) =>
|
||||
records.has(id) ? { kind: 'writable', record: records.get(id)! } : select(id)
|
||||
)
|
||||
const snapshot = rig.host.journalSnapshot.bind(rig.host)
|
||||
vi.spyOn(rig.host, 'journalSnapshot').mockImplementation((id) =>
|
||||
id === 'copied-chat'
|
||||
? Promise.resolve(childSnapshot)
|
||||
: id === 'source-chat'
|
||||
? Promise.resolve(test.snapshot)
|
||||
: snapshot(id)
|
||||
)
|
||||
const capabilities = rig.host.deps.agents.capabilities.bind(rig.host.deps.agents)
|
||||
vi.spyOn(rig.host.deps.agents, 'capabilities').mockImplementation((agent) => {
|
||||
const supported = capabilities(agent)
|
||||
return supported ? { ...supported, fork: 'checkpoint' } : null
|
||||
})
|
||||
rig.host.deps.adapter.copyConversation = test.copy
|
||||
setStructuredAgentSessionHost(rig.host)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the facade supplies every runtime method used before the fork refuses.
|
||||
const runtime = {
|
||||
getRuntimeId: () => 'runtime-1',
|
||||
getClientSettings: () => ({ nativeChatProviders: EVERY_AGENT_CHAT }),
|
||||
resolveStructuredAgentSessionCreateIntent: async (
|
||||
input: Parameters<OrcaRuntimeService['resolveStructuredAgentSessionCreateIntent']>[0]
|
||||
) => {
|
||||
if (!input.forkFrom) {
|
||||
throw new Error('Expected a fork intent')
|
||||
}
|
||||
return resolveStructuredAgentSessionForkIntent({
|
||||
...input,
|
||||
forkFrom: input.forkFrom,
|
||||
host: rig.host,
|
||||
location: test.record.location
|
||||
})
|
||||
},
|
||||
publishStructuredAgentSessionTab: vi.fn(async () => undefined)
|
||||
} as unknown as OrcaRuntimeService
|
||||
mocks.exactSupport.mockResolvedValue(true)
|
||||
mocks.inventory.mockResolvedValue([])
|
||||
const create = async (_target: unknown, method: string, params: unknown) => {
|
||||
if (method !== 'agentSession.create') {
|
||||
throw new Error('No destination published')
|
||||
}
|
||||
return handleStructuredAgentSessionCreate(CreateIntentParams.parse(params), {
|
||||
runtime,
|
||||
clientId: 'device-1'
|
||||
})
|
||||
}
|
||||
mocks.call.mockImplementation(create)
|
||||
return { rig, test, records, create }
|
||||
}
|
||||
|
||||
const copiedReply = {
|
||||
sessionId: 'copied-chat',
|
||||
throughItemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071124:completed-turn:1'
|
||||
}
|
||||
function forkLaunch(requestId: string) {
|
||||
return startStructuredAgentLaunch('workspace-fork', 'codex', {
|
||||
requestId,
|
||||
executionHostId: 'local',
|
||||
forkFrom: copiedReply
|
||||
})
|
||||
}
|
||||
|
||||
it('settles missing and rewound-original refusals through create without an unknown destination', async () => {
|
||||
const { rig, test, records } = await forkHost()
|
||||
try {
|
||||
records.delete('source-chat')
|
||||
const missing = forkLaunch('missing-original')
|
||||
await expect(missing.launchResult).rejects.toMatchObject({
|
||||
code: 'agent_session_identity_required',
|
||||
refusal: { details: { reason: 'recordMissing' } }
|
||||
})
|
||||
expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', missing.sessionId)).toBe(
|
||||
'failed'
|
||||
)
|
||||
expect(missing.isVisibilityUnknown()).toBe(false)
|
||||
expect(rig.store.getRecord(missing.sessionId)).toBeNull()
|
||||
records.set('source-chat', test.record)
|
||||
test.snapshot.items = test.snapshot.items.slice(0, 1)
|
||||
const removed = forkLaunch('removed-original-reply')
|
||||
await expect(removed.launchResult).rejects.toMatchObject({
|
||||
code: 'agent_session_operation_invalid',
|
||||
refusal: { details: { reason: 'savedConversationMissing' } }
|
||||
})
|
||||
expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', removed.sessionId)).toBe(
|
||||
'failed'
|
||||
)
|
||||
expect(removed.isVisibilityUnknown()).toBe(false)
|
||||
expect(rig.store.getRecord(removed.sessionId)).toBeNull()
|
||||
} finally {
|
||||
setStructuredAgentSessionHost(null)
|
||||
await rig.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a changed source after copying uncertain, despite a later admission refusal', async () => {
|
||||
const { rig, test } = await forkHost()
|
||||
try {
|
||||
const nativeCopy = test.copy.getMockImplementation()!
|
||||
test.copy.mockImplementationOnce(async (input) => {
|
||||
const copy = await nativeCopy(input)
|
||||
test.snapshot.items = test.snapshot.items.slice(0, 1)
|
||||
return copy
|
||||
})
|
||||
const launch = forkLaunch('post-copy-source-change')
|
||||
await expect(launch.launchResult).rejects.toMatchObject({
|
||||
code: 'agent_session_operation_invalid'
|
||||
})
|
||||
expect(launch.isVisibilityUnknown()).toBe(true)
|
||||
expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', launch.sessionId)).toBe(
|
||||
'visibility-unknown'
|
||||
)
|
||||
} finally {
|
||||
setStructuredAgentSessionHost(null)
|
||||
await rig.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps an earlier lost create unknown when the retry proves the original is missing', async () => {
|
||||
const { rig, records, create } = await forkHost()
|
||||
try {
|
||||
records.delete('source-chat')
|
||||
mocks.call.mockRejectedValueOnce(new Error('create reply lost')).mockImplementation(create)
|
||||
const launch = forkLaunch('lost-before-source-refusal')
|
||||
await expect(launch.launchResult).rejects.toMatchObject({
|
||||
code: 'agent_session_identity_required'
|
||||
})
|
||||
expect(launch.isVisibilityUnknown()).toBe(true)
|
||||
expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', launch.sessionId)).toBe(
|
||||
'visibility-unknown'
|
||||
)
|
||||
} finally {
|
||||
setStructuredAgentSessionHost(null)
|
||||
await rig.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -19,6 +19,24 @@ export function isAgentSessionCreateAdmissionRefusal(
|
||||
)
|
||||
}
|
||||
|
||||
/** Source admission can prove these refusals only before the native fork begins. */
|
||||
export function isAgentSessionForkSourceAdmissionRefusal(
|
||||
refusal: Pick<AgentSessionWireRefusal, 'code' | 'details'>
|
||||
): boolean {
|
||||
return (
|
||||
(refusal.code === 'agent_session_identity_required' &&
|
||||
refusal.details?.reason === 'recordMissing') ||
|
||||
(refusal.code === 'agent_session_operation_invalid' &&
|
||||
[
|
||||
'savedConversationMissing',
|
||||
'conversationCleared',
|
||||
'rewindUnconfirmed',
|
||||
'turnActive',
|
||||
'launchFolderMissing'
|
||||
].includes(refusal.details?.reason ?? ''))
|
||||
)
|
||||
}
|
||||
|
||||
/** Proves the host neither created a session nor will on a retry. */
|
||||
const DEFINITIVE_REFUSAL_CODES: ReadonlySet<string> = new Set<AgentSessionWireRefusalCode>([
|
||||
'structured_agent_session_unsupported'
|
||||
|
||||
@@ -20,6 +20,10 @@ export const AGENT_STILL_WORKING = 'The agent is still working.'
|
||||
/** Whole translatable pieces; the host fills agent (name or theAgent) and command (conversation command name) in English. */
|
||||
export const AGENT_SESSION_FAILURE_COPY = {
|
||||
theAgent: 'The agent',
|
||||
forkOriginalMissing:
|
||||
'{{agent}} could not find this response in the original chat. Open it and fork from there.',
|
||||
forkOriginalUnavailable:
|
||||
'{{agent}} cannot fork this response in the original chat right now. Open it and fork from there.',
|
||||
unconfirmed: "Couldn't confirm whether this was sent. It hasn't been resent.",
|
||||
providerStartFailed: '{{agent}} stopped before it finished starting.',
|
||||
savedConversationMissing: "{{agent}} couldn't find this chat's saved conversation.",
|
||||
@@ -259,3 +263,15 @@ export const sayAgentSessionFailureEnglish: AgentSessionFailureSay = (id, values
|
||||
(placeholder, name: string) => filled.get(name) ?? placeholder
|
||||
)
|
||||
}
|
||||
|
||||
/** Translate authored original-chat refusals without changing other fork failures. */
|
||||
export function agentSessionForkSourceFailureWords(
|
||||
message: string,
|
||||
agent: string,
|
||||
say: AgentSessionFailureSay
|
||||
): string | null {
|
||||
const id = (['forkOriginalMissing', 'forkOriginalUnavailable'] as const).find(
|
||||
(piece) => message === sayAgentSessionFailureEnglish(piece, { agent })
|
||||
)
|
||||
return id ? say(id, { agent }) : null
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { StructuredAgentSessionState } from '../structured-agent-session-re
|
||||
import type { AgentJournalCursor } from '../journal/agent-session-journal-identity'
|
||||
import {
|
||||
agentSessionContextFloorSequence,
|
||||
latestAgentSessionContextClearSequence
|
||||
isAgentSessionContextClear
|
||||
} from '../agent-session-context-clear'
|
||||
|
||||
/** User messages past `floor` the host can rewind to. */
|
||||
@@ -43,13 +43,15 @@ export function agentSessionRewindContextFloor(
|
||||
state: Pick<StructuredAgentSessionState, 'items' | 'epoch'>,
|
||||
contextFloor: AgentJournalCursor | undefined
|
||||
): number {
|
||||
return Math.max(
|
||||
latestAgentSessionContextClearSequence(state.items),
|
||||
state.items.find(
|
||||
(item) =>
|
||||
item.body.kind === 'status' &&
|
||||
item.body.presentation === AGENT_SESSION_FORKED_FROM_PRESENTATION
|
||||
)?.sequence ?? 0,
|
||||
agentSessionContextFloorSequence(contextFloor, state.epoch)
|
||||
)
|
||||
let floor = agentSessionContextFloorSequence(contextFloor, state.epoch)
|
||||
for (const item of state.items) {
|
||||
if (
|
||||
isAgentSessionContextClear(item.body) ||
|
||||
(item.body.kind === 'status' &&
|
||||
item.body.presentation === AGENT_SESSION_FORKED_FROM_PRESENTATION)
|
||||
) {
|
||||
floor = Math.max(floor, item.sequence)
|
||||
}
|
||||
}
|
||||
return floor
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { StructuredAgentSessionHostCapabilityState } from '../agent-session
|
||||
import { isRootAgentJournalItem } from '../agent-session/journal/agent-session-journal-producer'
|
||||
import type { AgentJournalRenderItem } from '../agent-session/journal/agent-session-journal-types'
|
||||
import type { AgentSessionOptionsResult } from '../agent-session/options/agent-session-options-result'
|
||||
import { AGENT_SESSION_FORKED_FROM_PRESENTATION } from '../agent-session/agent-session-fork'
|
||||
import type { NativeChatMessage } from './native-chat-types'
|
||||
|
||||
/** What a chat can fork: nothing, not yet known (drawn disabled), or through which turns. */
|
||||
@@ -35,19 +36,27 @@ export function nativeChatForkSupport(
|
||||
|
||||
/** The journal rows a fork can go through: the chat's own agent's messages. A displayed row that only
|
||||
* reads as a response (a tool call, or a status projected as a plan) maps to none of them. */
|
||||
export function nativeChatForkableItemIds(
|
||||
items: readonly Pick<AgentJournalRenderItem, 'itemId' | 'body' | 'agentId'>[]
|
||||
): ReadonlySet<string> {
|
||||
return new Set(
|
||||
items
|
||||
.filter(
|
||||
(item) =>
|
||||
item.body.kind === 'message' &&
|
||||
item.body.role === 'assistant' &&
|
||||
isRootAgentJournalItem(item)
|
||||
)
|
||||
.map((item) => item.itemId)
|
||||
)
|
||||
export function nativeChatForkInventory(
|
||||
items: readonly Pick<AgentJournalRenderItem, 'itemId' | 'body' | 'agentId' | 'sequence'>[]
|
||||
): { forkableItemIds: ReadonlySet<string>; inheritedThroughSequence: number } {
|
||||
const forkableItemIds = new Set<string>()
|
||||
let inheritedThroughSequence = 0
|
||||
for (const item of items) {
|
||||
if (
|
||||
item.body.kind === 'status' &&
|
||||
item.body.presentation === AGENT_SESSION_FORKED_FROM_PRESENTATION
|
||||
) {
|
||||
inheritedThroughSequence = item.sequence
|
||||
}
|
||||
if (
|
||||
item.body.kind === 'message' &&
|
||||
item.body.role === 'assistant' &&
|
||||
isRootAgentJournalItem(item)
|
||||
) {
|
||||
forkableItemIds.add(item.itemId)
|
||||
}
|
||||
}
|
||||
return { forkableItemIds, inheritedThroughSequence }
|
||||
}
|
||||
|
||||
/** The response `/fork` copies through: the chat's newest forkable one still in its current context. */
|
||||
@@ -84,6 +93,7 @@ export function nativeChatRowOffersFork(
|
||||
support: NativeChatForkSupport
|
||||
contextFloorSequence: number
|
||||
forkableItemIds: ReadonlySet<string>
|
||||
inheritedThroughSequence?: number
|
||||
}
|
||||
): boolean {
|
||||
const { message } = row
|
||||
@@ -100,6 +110,9 @@ export function nativeChatRowOffersFork(
|
||||
// Rows above a /clear are no longer in the agent's context.
|
||||
sequence !== undefined &&
|
||||
sequence > chat.contextFloorSequence &&
|
||||
(chat.support.kind === 'unknown' || chat.support.fork === 'checkpoint' || row.inLatestTurn)
|
||||
(chat.support.kind === 'unknown' ||
|
||||
chat.support.fork === 'checkpoint' ||
|
||||
row.inLatestTurn ||
|
||||
sequence <= (chat.inheritedThroughSequence ?? 0))
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user