diff --git a/src/agent_env/cli/task/run.py b/src/agent_env/cli/task/run.py index 71ef6df67..81b423fe7 100644 --- a/src/agent_env/cli/task/run.py +++ b/src/agent_env/cli/task/run.py @@ -107,6 +107,19 @@ def _format_server_config_changes(changes: list[dict]) -> str: return "\n".join(lines) +def _trajectory_turn_label(pr, turn: int | None) -> str: + """Which turn a listed trajectory is, since the list skips turns that stored none: "turn k of n", with the wake on + an always_on step, whose turns count its nudges too, so turn k needn't be wake k; "last available" for a response + url the per-turn list lacks.""" + if turn is None: + return "last available" + label = f"turn {turn} of {len(pr.target_agent_per_turn_trajectory_object_urls or [])}" + record = next(iter((pr.target_agent_per_turn_trajectories or [])[turn - 1:turn]), None) + if record is None or record.get("wake") is None: + return label + return f"{label} ({'nudge after wake' if record.get('nudge') else 'wake'} {record['wake']})" + + def _format_prompt_response(pr) -> str: indented_response = _indent(pr.response, " ") lines = [ @@ -117,6 +130,9 @@ def _format_prompt_response(pr) -> str: ] if pr.agent_trajectory_object_url: lines.append(f" agent_trajectory_object_url: {pr.agent_trajectory_object_url}") + if len(trajectories := pr.distinct_trajectory_object_urls()) > 1: + lines.append(f" trajectory_object_urls ({len(trajectories)}, in turn order):") + lines.extend(f" - {_trajectory_turn_label(pr, turn)}: {url}" for turn, url in trajectories) if pr.agent_trajectory_object_prefix: lines.append(f" agent_trajectory_object_prefix: {pr.agent_trajectory_object_prefix}") if pr.agent_trajectory_file_path: diff --git a/src/agent_env/explorer/ui/src/components/task-instance-viewer.tsx b/src/agent_env/explorer/ui/src/components/task-instance-viewer.tsx index 9c3a7a52c..8ef497453 100644 --- a/src/agent_env/explorer/ui/src/components/task-instance-viewer.tsx +++ b/src/agent_env/explorer/ui/src/components/task-instance-viewer.tsx @@ -44,9 +44,10 @@ import { renderJudgeOutputFormatVerifier, } from '../lib/verifier-visualizers'; import { + barDownloadFileCount, buildBarDownloads, shouldCollapseBarDownloads, - type BarDownload, + type BarDownloadFile, } from '../lib/bar-downloads'; import { collectedZipFiles, isAbsoluteArtifactPath } from '../lib/collected-zip-files'; @@ -82,8 +83,11 @@ import { parseOtelTrajectory, } from '../lib/parse-trajectory'; import { + type TrajectorySection, type TrajectoryUrlKeys, perTurnTrajectoryUrls, + sectionTurnLabel, + trajectorySections, trajectoryUrl, } from '../lib/trajectory-url'; @@ -113,6 +117,43 @@ interface TrajectoryState { error?: string; } +/** The tab bar's download buttons' look; each adds its own padding and corners. */ +const BAR_BUTTON_CLASS = + 'flex items-center text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:bg-[var(--accent)] transition-colors'; + +/** One file in a tab-bar download menu. */ +function BarDownloadMenuItem({ + file, + onDownload, +}: { + file: BarDownloadFile; + onDownload: (file: BarDownloadFile) => void; +}) { + return ( + onDownload(file)} title={file.title}> + + {file.label} + + ); +} + +/** A turn picker's turns, scrolling on an inner element for the reason the collapsed bar's menu gives. */ +function TurnPickerItems({ + turns, + onDownload, +}: { + turns: BarDownloadFile[]; + onDownload: (file: BarDownloadFile) => void; +}) { + return ( +
+ {turns.map(turn => ( + + ))} +
+ ); +} + export interface TaskStepRef { id: string; prompt_id?: string | null; @@ -152,13 +193,13 @@ export function TaskInstanceViewer({ { label: string; state: TrajectoryState; - // Join keys for the per-turn trigger strip. stepId is the RUN-TIME step id (the ledger's key), not - // the resolved label id, which can diverge. Undefined for combined-only entries (no strip). + // Join key for the per-turn trigger strips. stepId is the RUN-TIME step id (the ledger's key), not + // the resolved label id, which can diverge. stepId?: string; - turnIndex?: number; - // The user message authored after this turn (next turn's prompt) — - // the strip quotes it as the user-sim / trigger-injected reply. - nextTurnPromptText?: string; + // One trigger strip per turn that stored this trajectory: several when turns share one atif/1 + // document, none for a combined-only entry. nextTurnPromptText is the user message authored after + // that turn (the next turn's prompt), which the strip quotes as the user-sim / trigger-injected reply. + strips: { turnIndex: number; nextTurnPromptText?: string }[]; }[] >([]); const [copiedContext, setCopiedContext] = useState(false); @@ -244,28 +285,24 @@ export function TaskInstanceViewer({ const promptResponses = (context.prompt_responses ?? []) as PromptResponseData[]; - // Fan-out: each PromptResponse becomes 1+ entries — one per non-null turn URI for multi-turn, else one. + // Fan-out: each PromptResponse becomes one entry per distinct trajectory (`trajectorySections`): one per + // turn that stored its own, skipping turns that stored none; one for turns that share a document, which + // holds each of those turns' strips; and the response's url when its per-turn list lacks it. type FlatPR = PromptResponseData & { _entryObjectUrl: string; - _turnIndex?: number; - _totalTurns?: number; + _section: TrajectorySection; + _sectionCount: number; }; const flat: FlatPR[] = []; for (const pr of promptResponses) { - const perTurn = perTurnTrajectoryUrls(pr); - const url = trajectoryUrl(pr); - if (perTurn && perTurn.length > 0) { - perTurn.forEach((uri, turnIdx) => { - if (!uri) return; // skip turns whose trajectory upload failed - flat.push({ - ...pr, - _entryObjectUrl: uri, - _turnIndex: turnIdx, - _totalTurns: perTurn.length, - }); + const sections = trajectorySections(pr); + for (const section of sections) { + flat.push({ + ...pr, + _entryObjectUrl: section.url, + _section: section, + _sectionCount: sections.length, }); - } else if (url) { - flat.push({ ...pr, _entryObjectUrl: url }); } } @@ -280,13 +317,12 @@ export function TaskInstanceViewer({ } }); - const ordered = [...flat].sort((a, b) => { - const ai = stepIdxByPrompt[a.prompt_id] ?? Number.MAX_SAFE_INTEGER; - const bi = stepIdxByPrompt[b.prompt_id] ?? Number.MAX_SAFE_INTEGER; - if (ai !== bi) return ai - bi; - // Same step → preserve turn order - return (a._turnIndex ?? 0) - (b._turnIndex ?? 0); - }); + // Same step → `flat`'s order (the sort is stable): its responses in order, each in turn order. + const ordered = [...flat].sort( + (a, b) => + (stepIdxByPrompt[a.prompt_id] ?? Number.MAX_SAFE_INTEGER) - + (stepIdxByPrompt[b.prompt_id] ?? Number.MAX_SAFE_INTEGER), + ); setTrajectories(prev => { // Index prior loaded/loading state by objectUrl so a re-fire (e.g. taskSteps arriving late) doesn't undo @@ -299,50 +335,41 @@ export function TaskInstanceViewer({ const carryover = prevByUri.get(pr._entryObjectUrl); const initialStatus: TrajectoryState['status'] = carryover?.status ?? (ordered.length === 1 ? 'loading' : 'idle'); - const turnSuffix = - pr._turnIndex !== undefined && (pr._totalTurns ?? 0) > 1 - ? ` · Turn ${pr._turnIndex + 1}/${pr._totalTurns}` - : ''; + const { turnIndexes } = pr._section; + // Which turn, as the bar names it: an always_on run's by its wake, a nudge as a nudge. + const turnName = sectionTurnLabel(pr._section, pr._sectionCount); + const turnSuffix = turnName ? ` · ${turnName}` : ''; const stepLabel = resolvedStepId ?? `Prompt ${i + 1}`; const modelSuffix = pr.model ? ` (${pr.model})` : ''; - // Multi-turn: the per-turn prompt is the text sent that turn (initial on turn 1, reply on turn 2+); - // fall back to prompt_text (single-turn) — a null turn-0 entry also means prompt_text. Text parts only. - const perTurnParts = - pr._turnIndex !== undefined - ? pr.source_agent_per_turn_prompt_parts?.[pr._turnIndex] - : undefined; - const perTurnPromptText = perTurnParts - ? perTurnParts - .filter(p => p.kind === 'text' && typeof p.text === 'string') - .map(p => p.text!) - .join('\n') - : undefined; + const textOf = (turnIndex: number) => + pr.source_agent_per_turn_prompt_parts?.[turnIndex] + ?.filter(p => p.kind === 'text' && typeof p.text === 'string') + .map(p => p.text!) + .join('\n'); + // Multi-turn: the per-turn prompt is the text sent that turn (initial on turn 1, reply on turn 2+), the + // first turn's for a document several turns share; fall back to prompt_text (single-turn) — a null + // turn-0 entry also means prompt_text. Text parts only. + const promptTurn = turnIndexes[0]; + const perTurnPromptText = + promptTurn !== undefined ? textOf(promptTurn) : undefined; const promptText = perTurnPromptText !== undefined ? perTurnPromptText - : pr._turnIndex === undefined || pr._turnIndex === 0 + : promptTurn === undefined || promptTurn === 0 ? pr.prompt_text : undefined; - // The reply authored AFTER this turn (user-sim or trigger-injected) - // is the NEXT turn's prompt — surfaced by the trigger strip. - const nextTurnParts = - pr._turnIndex !== undefined - ? pr.source_agent_per_turn_prompt_parts?.[pr._turnIndex + 1] - : undefined; - const nextTurnPromptText = nextTurnParts - ? nextTurnParts - .filter(p => p.kind === 'text' && typeof p.text === 'string') - .map(p => p.text!) - .join('\n') - : undefined; return { label: ordered.length > 1 ? `${stepLabel}${turnSuffix}${modelSuffix}` : `Trajectory${turnSuffix}${modelSuffix}`, stepId: pr.step_id ?? resolvedStepId ?? undefined, - turnIndex: pr._turnIndex, - nextTurnPromptText, + // The reply authored AFTER a turn (user-sim or trigger-injected) is the NEXT turn's prompt — + // surfaced by that turn's trigger strip. + strips: turnIndexes.map(turnIndex => ({ + turnIndex, + nextTurnPromptText: textOf(turnIndex + 1), + })), state: { status: initialStatus, objectUrl: pr._entryObjectUrl, @@ -612,8 +639,10 @@ export function TaskInstanceViewer({ [promptResponses], ); const collapseBarDownloads = shouldCollapseBarDownloads(barDownloads.length); + // Files, not entries: an entry with a turn picker holds several. + const barDownloadFiles = barDownloadFileCount(barDownloads); const runBarDownload = useCallback( - (download: BarDownload) => { + (download: BarDownloadFile) => { void handleDownloadTrajectory(download.objectUrl); }, [handleDownloadTrajectory], @@ -837,11 +866,11 @@ export function TaskInstanceViewer({ @@ -853,31 +882,76 @@ export function TaskInstanceViewer({ the menu's a11y tree; Radix tracks items by context, not DOM parentage, so keyboard navigation is unaffected. */}
- {barDownloads.map(item => ( - runBarDownload(item)} - title={item.title} - > - - {item.label} - - ))} + {barDownloads.map(item => + item.turnPicker ? ( + // A response of several turns is one row, its turns in a submenu. + + + + {item.turnPicker.label} + + + + + + ) : ( + + ), + )}
) : ( - barDownloads.map(item => ( - - )) + barDownloads.map(item => + item.turnPicker ? ( + // A response of several turns: its button downloads the last available trajectory, the chevron picks + // any turn. +
+ + + + + + + + + +
+ ) : ( + + ), + ) )} @@ -974,13 +1048,16 @@ export function TaskInstanceViewer({ )} - + {t.strips.map(strip => ( + + ))} ))} diff --git a/src/agent_env/explorer/ui/src/lib/bar-downloads.smoke.ts b/src/agent_env/explorer/ui/src/lib/bar-downloads.smoke.ts index 01080eb08..2a9e38b4a 100644 --- a/src/agent_env/explorer/ui/src/lib/bar-downloads.smoke.ts +++ b/src/agent_env/explorer/ui/src/lib/bar-downloads.smoke.ts @@ -8,8 +8,11 @@ * directory. The package has no Jest config and `test` is a no-op, so there is * no runner a `.test.ts` file would be picked up by. */ +import { isDeepStrictEqual } from 'node:util'; + import { MAX_INLINE_BAR_DOWNLOADS, + barDownloadFileCount, buildBarDownloads, shouldCollapseBarDownloads, } from './bar-downloads'; @@ -156,6 +159,227 @@ function main(): void { ); } + // A single trajectory keeps its plain entry: no turn in the label, no turn picker. + { + const [only] = buildBarDownloads( + [{ agent_trajectory_s3_uri: 'obj://t/one', target_agent_per_turn_trajectory_s3_uris: ['obj://t/one'], model: 'm' }], + ); + assert( + isDeepStrictEqual(only, { + key: 'obj://t/one', + label: 'Trajectory', + title: 'Download Trajectory (m)', + objectUrl: 'obj://t/one', + }), + 'a one-turn response is the same entry as a response with no per-turn list', + ); + } + + // An always_on step: one entry for the run. Its button downloads the last wake, the picker every wake. + { + const downloads = buildBarDownloads( + [ + { + agent_trajectory_s3_uri: 'obj://w/3', + target_agent_per_turn_trajectory_s3_uris: ['obj://w/1', null, 'obj://w/3'], + step_id: 'week', + model: 'm', + }, + ], + ); + assert(downloads.length === 1, 'an always_on run of several wakes is one entry'); + const [run] = downloads; + assert( + run?.label === 'Trajectory (turn 3 of 3)' && run.objectUrl === 'obj://w/3', + 'its button downloads the last wake, its label naming that turn', + ); + assert(run?.title === 'Download Trajectory, turn 3 of 3 (m)', 'the tooltip names the turn and the model'); + assert( + run?.turnPicker?.turns.map(t => `${t.label}=${t.objectUrl}`).join('|') === + 'turn 1 of 3=obj://w/1|turn 3 of 3=obj://w/3', + 'the turn picker lists every wake that stored a trajectory, in wake order', + ); + assert(run?.turnPicker?.label === 'Trajectory (3 turns)', 'the picker counts the run\'s turns'); + } + + // An always_on run whose turns name their wake: its per-turn list holds wake 1's nudge beside the wakes, so its + // second turn is that nudge, not wake 2. Each wake is labelled by its wake, the nudge as a nudge. + { + const records = [ + { format: 'shots/1', atif: null, wake: 1, nudge: false }, + { format: 'shots/1', atif: null, wake: 1, nudge: true }, + { format: 'shots/1', atif: null, wake: 2, nudge: false }, + { format: 'shots/1', atif: null, wake: 3, nudge: false }, + ]; + const [run] = buildBarDownloads( + [ + { + agent_trajectory_s3_uri: 'obj://w/3', + target_agent_per_turn_trajectory_s3_uris: ['obj://w/1', 'obj://w/1n', 'obj://w/2', 'obj://w/3'], + target_agent_per_turn_trajectories: records, + step_id: 'week', + model: 'm', + }, + ], + ); + assert( + run?.label === 'Trajectory (wake 3 of 3)' && run.title === 'Download Trajectory, wake 3 of 3 (m)', + 'an always_on run\'s button names its last wake, not its fourth turn', + ); + assert( + run?.turnPicker?.turns.map(t => `${t.label}=${t.objectUrl}`).join('|') === + 'wake 1 of 3=obj://w/1|nudge after wake 1=obj://w/1n|wake 2 of 3=obj://w/2|wake 3 of 3=obj://w/3', + 'the picker labels each wake by its wake and the nudge as a nudge, so turn 2 is not read as wake 2', + ); + assert(run?.turnPicker?.label === 'Trajectory (3 wakes)', 'the picker counts the run\'s wakes, not its turns'); + + const [nudgedLast] = buildBarDownloads( + [ + { + agent_trajectory_s3_uri: 'obj://w/1n', + target_agent_per_turn_trajectory_s3_uris: ['obj://w/1', 'obj://w/1n'], + target_agent_per_turn_trajectories: records.slice(0, 2), + step_id: 'week', + }, + ], + ); + assert( + nudgedLast?.label === 'Trajectory (nudge after wake 1)', + 'a run whose last turn was a nudge names it as one', + ); + } + + // A multi-turn prompt_agent step (a user-sim conversation of 20 turns) beside a single-turn step: two entries, not 21. + { + const turns = Array.from({ length: 20 }, (_, i) => `obj://chat/${i + 1}`); + const downloads = buildBarDownloads( + [ + { agent_trajectory_object_url: 'obj://t/setup', step_id: 'setup' }, + { + agent_trajectory_object_url: turns[19], + target_agent_per_turn_trajectory_object_urls: turns, + step_id: 'converse', + }, + ], + ); + assert( + downloads.map(d => d.label).join('|') === 'setup|converse (turn 20 of 20)', + 'one entry per prompt response, the conversation labelled by its last turn', + ); + assert(downloads[0]?.turnPicker === undefined, 'the single-turn step has no turn picker'); + assert( + isDeepStrictEqual(downloads[1]?.turnPicker?.turns.map(t => t.objectUrl), turns) && + downloads[1]?.turnPicker?.turns[0]?.label === 'turn 1 of 20' && + downloads[1]?.turnPicker?.turns[0]?.title === 'Download converse, turn 1 of 20', + 'the conversation\'s picker offers every turn, labelled "turn k of n"', + ); + assert(!shouldCollapseBarDownloads(downloads.length), 'two entries stay inline'); + } + + // A Claude Code atif/1 run's turns share one document: one plain entry, while a step of distinct turns gets a picker. + { + const downloads = buildBarDownloads( + [ + { + agent_trajectory_s3_uri: 'obj://atif/doc', + target_agent_per_turn_trajectory_s3_uris: ['obj://atif/doc', 'obj://atif/doc', 'obj://atif/doc'], + step_id: 'copied', + }, + { + agent_trajectory_object_url: 'obj://w/2', + target_agent_per_turn_trajectory_object_urls: ['obj://w/1', 'obj://w/2'], + step_id: 'week', + }, + ], + ); + assert( + downloads.map(d => `${d.label}:${d.turnPicker ? d.turnPicker.turns.length : 0}`).join('|') === + 'copied:0|week (turn 2 of 2):2', + 'turns sharing a document give one entry and no picker; distinct turns give a picker', + ); + assert(new Set(downloads.map(d => d.key)).size === downloads.length, 'keys stay unique'); + } + + // An atif/1 run whose second turn's copy failed, so that turn kept its native trajectory: per-turn [A, B, A]. The + // button downloads the response's own trajectory, A, which the last turn stored, not the middle turn's B. + { + const [run] = buildBarDownloads( + [ + { + agent_trajectory_s3_uri: 'obj://atif/doc', + target_agent_per_turn_trajectory_s3_uris: ['obj://atif/doc', 'obj://native/2', 'obj://atif/doc'], + step_id: 'copied', + model: 'm', + }, + ], + ); + assert( + run?.objectUrl === 'obj://atif/doc' && run.key === 'obj://atif/doc', + 'a run of [A, B, A] downloads A, the response\'s own trajectory', + ); + assert( + run?.label === 'Trajectory (turn 3 of 3)' && run.title === 'Download Trajectory, turn 3 of 3 (m)', + 'its label names the last turn that stored A', + ); + assert( + run?.turnPicker?.turns.map(t => `${t.label}=${t.objectUrl}`).join('|') === + 'turn 2 of 3=obj://native/2|turn 3 of 3=obj://atif/doc', + 'its picker lists every distinct trajectory, A at the same turn as the button names it', + ); + } + + // A response that records only its per-turn list downloads the last turn that stored one. + { + const [run] = buildBarDownloads( + [{ target_agent_per_turn_trajectory_object_urls: ['obj://w/1', 'obj://w/2', null] }], + ); + assert( + run?.objectUrl === 'obj://w/2' && run.label === 'Trajectory (turn 2 of 3)', + 'with no agent_trajectory url, the button falls back to the run\'s last trajectory', + ); + } + + // A response url the per-turn list lacks can't be placed in a turn, so it isn't called the last turn's. + { + const [run] = buildBarDownloads( + [ + { + agent_trajectory_s3_uri: 'obj://x/final', + target_agent_per_turn_trajectory_s3_uris: ['obj://x/1', 'obj://x/2'], + }, + ], + ); + assert( + run?.objectUrl === 'obj://x/final' && run.label === 'Trajectory (last available)', + 'a url outside the per-turn list is labelled "last available"', + ); + } + + // The collapsed bar's button counts files, not responses: a response with a turn picker is one row of several files. + { + const downloads = buildBarDownloads( + [ + { agent_trajectory_object_url: 'obj://a', step_id: 'a' }, + { agent_trajectory_object_url: 'obj://b', step_id: 'b' }, + { + agent_trajectory_object_url: 'obj://c/7', + target_agent_per_turn_trajectory_object_urls: Array.from({ length: 7 }, (_, i) => `obj://c/${i + 1}`), + step_id: 'c', + }, + { + agent_trajectory_object_url: 'obj://atif/doc', + target_agent_per_turn_trajectory_object_urls: ['obj://atif/doc', 'obj://atif/doc'], + step_id: 'd', + }, + ], + ); + assert( + downloads.length === 4 && barDownloadFileCount(downloads) === 10, + 'four responses, one of seven turns and one of a shared document, are ten files', + ); + assert(barDownloadFileCount([]) === 0, 'no downloads, no files'); + } + if (failures > 0) { console.error(`\n${failures} assertion(s) failed`); process.exit(1); diff --git a/src/agent_env/explorer/ui/src/lib/bar-downloads.ts b/src/agent_env/explorer/ui/src/lib/bar-downloads.ts index 001e43070..4d5ce1185 100644 --- a/src/agent_env/explorer/ui/src/lib/bar-downloads.ts +++ b/src/agent_env/explorer/ui/src/lib/bar-downloads.ts @@ -1,11 +1,17 @@ /** Download entries for the task-instance tab bar. Every prompt_agent step with `trajectory_output_prefix` - * uploads its own trajectory; the bar exposes one per trajectory (the last/solver step is usually most + * uploads its own trajectory; the bar exposes one entry per prompt response (the last/solver step is usually most * interesting). Past MAX_INLINE_BAR_DOWNLOADS the caller collapses them into a dropdown. Built here (not inline) so the row and dropdown share entries/order and the labels are testable. */ /** How many downloads may sit inline in the bar before they collapse. */ export const MAX_INLINE_BAR_DOWNLOADS = 2; -import { type TrajectoryUrlKeys, trajectoryUrl } from './trajectory-url'; +import { + type RunTrajectory, + type TrajectoryUrlKeys, + runTrajectoryUrls, + trajectoryUrl, + turnLabel, +} from './trajectory-url'; /** The subset of a prompt-response the bar needs to label a trajectory. */ export interface BarDownloadTrajectory extends TrajectoryUrlKeys { @@ -14,7 +20,8 @@ export interface BarDownloadTrajectory extends TrajectoryUrlKeys { model?: string; } -export interface BarDownload { +/** One file the bar can download. */ +export interface BarDownloadFile { /** Stable React key. */ key: string; label: string; @@ -23,25 +30,87 @@ export interface BarDownload { objectUrl: string; } -/** Build the bar's download list from a run's prompt responses. - * Trajectories are labelled by step_id, else prompt_id, else "Trajectory N"; a single trajectory gets the bare - * "Trajectory". Entries with no URI are dropped. */ +/** The turn picker of a response whose turns stored distinct trajectories. */ +export interface BarDownloadTurnPicker { + /** The picker's row in the collapsed dropdown, e.g. "week (7 turns)". */ + label: string; + /** The picker's tooltip. */ + title: string; + /** Every turn's trajectory, in turn order, each labelled "turn k of n". */ + turns: BarDownloadFile[]; +} + +/** One prompt response's entry. Its own file is the response's trajectory, the last available one when it has + * several. */ +export interface BarDownload extends BarDownloadFile { + /** Set only when the response's turns stored several distinct trajectories. */ + turnPicker?: BarDownloadTurnPicker; +} + +/** The picker's count: an always_on run's wakes, else its turns. Several runs means the per-turn list named at least + * one, so the first run has the counts. */ +function turnCount(run: RunTrajectory): string { + const [n, noun] = run.wakes !== undefined ? [run.wakes, 'wake'] : [run.turns, 'turn']; + return `${n} ${noun}${n === 1 ? '' : 's'}`; +} + +/** The trajectory a response's own download gets: its `agent_trajectory` url (the last available one), as `runs` + * places and labels it, so the button and the picker name it alike; with no such url, the run's last trajectory. + * `runs` always holds that url: it appends it, with no turn, when the per-turn list lacks it. */ +function mainTrajectory(pr: TrajectoryUrlKeys, runs: RunTrajectory[]): RunTrajectory { + const url = trajectoryUrl(pr); + return runs.find(run => run.url === url) ?? runs[runs.length - 1]!; +} + +/** How many files the bar offers: a response with a turn picker is one entry of several. */ +export function barDownloadFileCount(downloads: BarDownload[]): number { + return downloads.reduce((n, download) => n + (download.turnPicker?.turns.length ?? 1), 0); +} + +/** Build the bar's download list from a run's prompt responses: one entry per response that has a trajectory. + * Trajectories are labelled by step_id, else prompt_id, else "Trajectory N"; a single response gets the bare + * "Trajectory". A response whose turns stored several distinct trajectories (a multi-turn prompt_agent step, an + * always_on step's wakes) downloads its last available trajectory, its label naming that turn, e.g. "Trajectory + * (turn 7 of 7)", or for an always_on step "Trajectory (wake 7 of 7)", and carries a turn picker with every turn's. Turns that share one document (an atif/1 run) are one + * trajectory, so that response gets a plain entry. Responses with no URI are dropped. */ export function buildBarDownloads( promptResponses: BarDownloadTrajectory[], ): BarDownload[] { - const withTrajectory = promptResponses.filter(pr => trajectoryUrl(pr)); + const withTrajectory = promptResponses + .map(pr => ({ pr, runs: runTrajectoryUrls(pr) })) + .filter(({ runs }) => runs.length > 0); const single = withTrajectory.length === 1; - return withTrajectory.map((pr, i) => { - const label = single + return withTrajectory.map(({ pr, runs }, i) => { + const name = single ? 'Trajectory' : pr.step_id || pr.prompt_id || `Trajectory ${i + 1}`; - const objectUrl = trajectoryUrl(pr) as string; + const model = pr.model ? ` (${pr.model})` : ''; + const main = mainTrajectory(pr, runs); + if (runs.length === 1) { + return { + key: main.url, + label: name, + title: `Download ${name}${model}`, + objectUrl: main.url, + }; + } + const turns = runs.map(run => ({ + key: run.url, + label: turnLabel(run), + title: `Download ${name}, ${turnLabel(run)}${model}`, + objectUrl: run.url, + })); return { - key: objectUrl, - label, - title: pr.model ? `Download ${label} (${pr.model})` : `Download ${label}`, - objectUrl, + key: main.url, + label: `${name} (${turnLabel(main)})`, + title: `Download ${name}, ${turnLabel(main)}${model}`, + objectUrl: main.url, + turnPicker: { + label: `${name} (${turnCount(runs[0]!)})`, + title: `Download one turn of ${name}`, + turns, + }, }; }); } diff --git a/src/agent_env/explorer/ui/src/lib/trajectory-url.smoke.ts b/src/agent_env/explorer/ui/src/lib/trajectory-url.smoke.ts index 43a7310e2..90f22fa95 100644 --- a/src/agent_env/explorer/ui/src/lib/trajectory-url.smoke.ts +++ b/src/agent_env/explorer/ui/src/lib/trajectory-url.smoke.ts @@ -4,7 +4,15 @@ * Runner: plain TS, exits non-zero on assertion failure. From this package: * npx tsx src/lib/trajectory-url.smoke.ts */ -import { perTurnTrajectoryUrls, trajectoryUrl } from './trajectory-url'; +import { isDeepStrictEqual } from 'node:util'; + +import { + perTurnTrajectoryUrls, + runTrajectoryUrls, + sectionTurnLabel, + trajectorySections, + trajectoryUrl, +} from './trajectory-url'; let failures = 0; function assert(cond: unknown, msg: string): void { @@ -37,7 +45,7 @@ function main(): void { `${name} keys: the trajectory URL`, ); assert( - JSON.stringify(perTurnTrajectoryUrls(pr)) === JSON.stringify(TURNS), + isDeepStrictEqual(perTurnTrajectoryUrls(pr), TURNS), `${name} keys: the per-turn URLs, a failed turn kept as null`, ); } @@ -78,6 +86,178 @@ function main(): void { ); } + // The whole run, not its last turn: an always_on step's agent_trajectory_s3_uri is its last wake alone. + { + const run = runTrajectoryUrls({ + agent_trajectory_s3_uri: 'obj://w/4.json', + target_agent_per_turn_trajectory_s3_uris: [ + 'obj://w/1.json', + null, + 'obj://w/3.json', + 'obj://w/4.json', + ], + }); + assert( + isDeepStrictEqual(run, [ + { url: 'obj://w/1.json', turn: 1, turns: 4 }, + { url: 'obj://w/3.json', turn: 3, turns: 4 }, + { url: 'obj://w/4.json', turn: 4, turns: 4 }, + ]), + 'every wake in wake order, each with its turn, the failed one left out', + ); + const atif = runTrajectoryUrls({ + agent_trajectory_object_url: 'obj://atif/doc.json', + target_agent_per_turn_trajectory_object_urls: Array(3).fill('obj://atif/doc.json'), + }); + assert( + atif.length === 1 && atif[0]?.url === 'obj://atif/doc.json', + 'turns sharing one document read it once', + ); + assert( + isDeepStrictEqual(runTrajectoryUrls({ agent_trajectory_s3_uri: 'obj://one.json' }), [{ url: 'obj://one.json' }]), + 'a response with no per-turn list has its one trajectory', + ); + assert(runTrajectoryUrls({}).length === 0, 'no key: no trajectories'); + } + + // An atif/1 run whose second turn's copy failed stores [A, B, A]. A is rewritten each turn, so it holds the last + // turn's copy: it is turn 3's, placed and labelled there, as the bar's button names it and core's + // `distinct_trajectory_object_urls` lists it. + { + const run = runTrajectoryUrls({ + agent_trajectory_object_url: 'obj://atif/doc.json', + target_agent_per_turn_trajectory_object_urls: ['obj://atif/doc.json', 'obj://native/2.json', 'obj://atif/doc.json'], + }); + assert( + isDeepStrictEqual(run, [ + { url: 'obj://native/2.json', turn: 2, turns: 3 }, + { url: 'obj://atif/doc.json', turn: 3, turns: 3 }, + ]), + 'a document several turns stored is the last such turn\'s, in turn order', + ); + } + + // The trajectory viewer's sections: one per distinct trajectory, so a document several turns share is shown once, + // holding every turn that stored it (each turn's trigger strip); a response url the list lacks is still shown. + { + const shared = trajectorySections({ + agent_trajectory_object_url: 'obj://atif/doc.json', + target_agent_per_turn_trajectory_object_urls: Array(3).fill('obj://atif/doc.json'), + }); + assert( + isDeepStrictEqual(shared, [{ url: 'obj://atif/doc.json', turn: 3, turns: 3, turnIndexes: [0, 1, 2] }]), + 'turns sharing one document are one section holding all three turns, not three copies of it', + ); + const mixed = trajectorySections({ + agent_trajectory_object_url: 'obj://atif/doc.json', + target_agent_per_turn_trajectory_object_urls: ['obj://atif/doc.json', 'obj://native/2.json', 'obj://atif/doc.json'], + }); + assert( + isDeepStrictEqual(mixed.map(s => [s.url, s.turn, s.turnIndexes]), [ + ['obj://native/2.json', 2, [1]], + ['obj://atif/doc.json', 3, [0, 2]], + ]), + 'a run of [A, B, A] is two sections, A at its last turn with both of its turns', + ); + const lacking = trajectorySections({ + agent_trajectory_s3_uri: 'obj://x/final.json', + target_agent_per_turn_trajectory_s3_uris: ['obj://x/1.json'], + }); + assert( + isDeepStrictEqual(lacking, [ + { url: 'obj://x/1.json', turn: 1, turns: 1, turnIndexes: [0] }, + { url: 'obj://x/final.json', turnIndexes: [] }, + ]), + 'a response url the per-turn list lacks is a section too, with no turn', + ); + assert( + isDeepStrictEqual(trajectorySections({ agent_trajectory_s3_uri: 'obj://one.json' }), [ + { url: 'obj://one.json', turnIndexes: [] }, + ]), + 'a response with no per-turn list is one section with no turn', + ); + } + + // A multi-turn prompt_agent step (a user-sim conversation): agent_trajectory_object_url is its last turn alone. + { + const run = runTrajectoryUrls({ + agent_trajectory_object_url: 'obj://chat/3.json', + target_agent_per_turn_trajectory_object_urls: ['obj://chat/1.json', 'obj://chat/2.json', 'obj://chat/3.json'], + }); + assert( + run.map(r => `${r.turn}/${r.turns}=${r.url}`).join('|') === + '1/3=obj://chat/1.json|2/3=obj://chat/2.json|3/3=obj://chat/3.json', + 'every turn of the conversation in turn order, the last not repeated', + ); + } + + // An always_on step's turns name their wake: a nudge sits beside the wakes in the per-turn list, so turn 2 is wake + // 1's nudge; a turn whose upload failed still counts its wake. A run recorded before turns named their wake reads + // by turn alone. + { + const run = runTrajectoryUrls({ + agent_trajectory_object_url: 'obj://w/2.json', + target_agent_per_turn_trajectory_object_urls: ['obj://w/1.json', 'obj://w/1n.json', null, 'obj://w/2.json'], + target_agent_per_turn_trajectories: [ + { format: null, atif: null, wake: 1, nudge: false }, + { format: null, atif: null, wake: 1, nudge: true }, + { format: null, atif: null, wake: 2, nudge: false }, + { format: null, atif: null, wake: 3, nudge: false }, + ], + }); + assert( + run.map(r => `${r.turn}:${r.wake}/${r.wakes}${r.nudge ? ' nudge' : ''}`).join('|') === + '1:1/3|2:1/3 nudge|4:3/3', + 'each turn carries its wake and the run\'s wake count, a nudge marked', + ); + assert( + runTrajectoryUrls({ + target_agent_per_turn_trajectory_object_urls: ['obj://w/1.json'], + target_agent_per_turn_trajectories: [{ format: null, atif: null }], + })[0]?.wake === undefined, + 'a turn whose record names no wake has none', + ); + } + + // The viewer names a section's turn as the bar does: an always_on run's turns by their wake, a nudge as a nudge (turn + // 2 is wake 1's nudge, not wake 2), and a step whose records name no wake by turn. A response of one section names + // no turn. + { + const wakeRun = { + agent_trajectory_object_url: 'obj://w/3.json', + target_agent_per_turn_trajectory_object_urls: ['obj://w/1.json', 'obj://w/1n.json', 'obj://w/2.json', 'obj://w/3.json'], + target_agent_per_turn_trajectories: [ + { format: null, atif: null, wake: 1, nudge: false }, + { format: null, atif: null, wake: 1, nudge: true }, + { format: null, atif: null, wake: 2, nudge: false }, + { format: null, atif: null, wake: 3, nudge: false }, + ], + }; + const sections = trajectorySections(wakeRun); + assert( + isDeepStrictEqual(sections.map(s => sectionTurnLabel(s, sections.length)), [ + 'wake 1 of 3', + 'nudge after wake 1', + 'wake 2 of 3', + 'wake 3 of 3', + ]), + 'the viewer labels an always_on run\'s sections by wake, the nudge as a nudge', + ); + const chat = trajectorySections({ + agent_trajectory_object_url: 'obj://c/2.json', + target_agent_per_turn_trajectory_object_urls: ['obj://c/1.json', 'obj://c/2.json'], + }); + assert( + isDeepStrictEqual(chat.map(s => sectionTurnLabel(s, chat.length)), ['turn 1 of 2', 'turn 2 of 2']), + 'the viewer labels a step whose turns name no wake by turn', + ); + const [shared] = trajectorySections({ + agent_trajectory_object_url: 'obj://atif/doc.json', + target_agent_per_turn_trajectory_object_urls: Array(3).fill('obj://atif/doc.json'), + }); + assert(shared !== undefined && sectionTurnLabel(shared, 1) === undefined, 'a response of one section names no turn'); + } + if (failures > 0) { console.error(`\n${failures} assertion(s) failed`); process.exit(1); diff --git a/src/agent_env/explorer/ui/src/lib/trajectory-url.ts b/src/agent_env/explorer/ui/src/lib/trajectory-url.ts index 7668e7d7f..508313dd0 100644 --- a/src/agent_env/explorer/ui/src/lib/trajectory-url.ts +++ b/src/agent_env/explorer/ui/src/lib/trajectory-url.ts @@ -7,9 +7,12 @@ export interface TrajectoryUrlKeys { agent_trajectory_object_url?: unknown; target_agent_per_turn_trajectory_s3_uris?: unknown; target_agent_per_turn_trajectory_object_urls?: unknown; + /** Each turn's record, beside the per-turn urls; an always_on step's says which wake the turn is part of. */ + target_agent_per_turn_trajectories?: unknown; } -/** The trajectory of the response's last turn, if it has one. */ +/** The response's last available trajectory, if it has one: its last turn's, or the latest earlier turn's when the + * last turn's upload failed. On an always_on step that is one wake alone: `runTrajectoryUrls` reads the whole run. */ export function trajectoryUrl( pr: TrajectoryUrlKeys | null | undefined, ): string | undefined { @@ -28,3 +31,93 @@ export function perTurnTrajectoryUrls( ? urls.map(url => (typeof url === 'string' && url ? url : null)) : undefined; } + +/** One of a run's trajectories: its url, and the 1-based turn it is the trajectory of among `turns` turns (both + * undefined for a response that keeps no per-turn list). An always_on step's turn also has `wake`, the wake it is + * part of, among `wakes` (the run's last wake that recorded a turn), and `nudge` for the short turn the step gives a + * wake that ended on closing text alone: its per-turn list holds nudges beside the wakes, so turn k needn't be wake k. + * A run recorded before turns named their wake has none of the three. */ +export interface RunTrajectory { + url: string; + turn?: number; + turns?: number; + wake?: number; + wakes?: number; + nudge?: boolean; +} + +/** Turn `index` (0-based) of a per-turn list of `count`: its 1-based turn, and its wake when its record names one. */ +function turnAt( + pr: TrajectoryUrlKeys | null | undefined, + index: number, + count: number, +): Omit { + const records = Array.isArray(pr?.target_agent_per_turn_trajectories) + ? (pr.target_agent_per_turn_trajectories as unknown[]) + : []; + const wakeOf = (record: unknown): number | undefined => { + const wake = (record as { wake?: unknown } | null)?.wake; + return typeof wake === 'number' ? wake : undefined; + }; + const record = records[index] as { nudge?: unknown } | null | undefined; + const wake = wakeOf(record); + if (wake === undefined) return { turn: index + 1, turns: count }; + const wakes = Math.max(...records.map(r => wakeOf(r) ?? 0)); + return { turn: index + 1, turns: count, wake, wakes, nudge: record?.nudge === true }; +} + +/** Which turn a trajectory is: an always_on step's by its wake, "wake k of n" or "nudge after wake k" (its turns + * count nudges too, so turn k needn't be wake k); any other's "turn k of n"; "last available" for a response url the + * per-turn list lacks. The download bar and the trajectory viewer both name turns by it. */ +export function turnLabel(run: RunTrajectory): string { + if (run.wake !== undefined) { + return run.nudge ? `nudge after wake ${run.wake}` : `wake ${run.wake} of ${run.wakes}`; + } + return run.turn !== undefined ? `turn ${run.turn} of ${run.turns}` : 'last available'; +} + +/** Every distinct trajectory of the response, in turn order: the turns that stored none are skipped, a url several + * turns stored (an atif/1 run's turns share one document) is listed once, at the last such turn, since the document + * is rewritten each turn and so holds that turn's copy; then the last available trajectory's url, with no turn, when + * the list lacks it. Core's `PromptResponse.distinct_trajectory_object_urls` reads the same. */ +export function runTrajectoryUrls( + pr: TrajectoryUrlKeys | null | undefined, +): RunTrajectory[] { + const perTurn = perTurnTrajectoryUrls(pr) ?? []; + const lastIndex = new Map(); + perTurn.forEach((url, index) => { + if (url) lastIndex.set(url, index); + }); + const out: RunTrajectory[] = [...lastIndex] + .sort(([, a], [, b]) => a - b) + .map(([url, index]) => ({ url, ...turnAt(pr, index, perTurn.length) })); + const last = trajectoryUrl(pr); + if (last && !lastIndex.has(last)) out.push({ url: last }); + return out; +} + +/** One section of the explorer's trajectory viewer: one of the response's distinct trajectories (`runTrajectoryUrls`) + * and `turnIndexes`, the 0-based turns that stored it, in order, whose prompt and trigger strip the section shows. + * Turns that share one document are one section holding all of them, so the document is shown once, not once per + * turn. A response url the per-turn list lacks is a section with no turns. */ +export interface TrajectorySection extends RunTrajectory { + turnIndexes: number[]; +} + +/** The viewer's name for a section's turn, as the bar names it (`turnLabel`): an always_on run's by its wake, a nudge + * as a nudge. Undefined when the response has one section, so a document its turns share isn't called its last + * turn's alone. */ +export function sectionTurnLabel(section: RunTrajectory, sectionCount: number): string | undefined { + return sectionCount > 1 ? turnLabel(section) : undefined; +} + +/** The viewer's sections of a response, in turn order. */ +export function trajectorySections( + pr: TrajectoryUrlKeys | null | undefined, +): TrajectorySection[] { + const perTurn = perTurnTrajectoryUrls(pr) ?? []; + return runTrajectoryUrls(pr).map(run => ({ + ...run, + turnIndexes: perTurn.flatMap((url, index) => (url === run.url ? [index] : [])), + })); +} diff --git a/src/agent_env/task_step/context.py b/src/agent_env/task_step/context.py index a02304790..2139bcb87 100644 --- a/src/agent_env/task_step/context.py +++ b/src/agent_env/task_step/context.py @@ -8,7 +8,7 @@ from collections.abc import Callable from contextvars import ContextVar from dataclasses import dataclass, field -from typing import Any, Literal, Optional, TypedDict +from typing import Any, Literal, NamedTuple, NotRequired, Optional, TypedDict from agentenv_protocol import client as protocol_v1 @@ -277,20 +277,35 @@ class TurnTrajectory(TypedDict): that url, as its answer named it (None from an agent that names none), and its atif/1 copy, None when the run doesn't prescribe atif/1. In a run that prescribes atif/1 to an agent that offers it, the url is the copy's document and the format ``atif/1``; a turn whose copy couldn't be had, or whose copy's media didn't all arrive, has - its native trajectory there instead.""" + its native trajectory there instead. An always_on step's turn also says which it is, since its per-turn lists hold + a wake's nudge turn beside the wakes and turn k need not be wake k: ``wake``, the wake it is part of, and ``nudge``, + True for the short turn the step gives a wake that ended on closing text alone. Other steps' turns have neither.""" format: Optional[str] atif: Optional[AtifRecord] + wake: NotRequired[int] + nudge: NotRequired[bool] def turn_trajectories(records: Optional[list[dict[str, Any]]]) -> Optional[list[TurnTrajectory]]: - """Stored per-turn records as TurnTrajectory, an older record's ``native_format`` read as its format.""" + """Stored per-turn records as TurnTrajectory, an older record's ``native_format`` read as its format, and an + always_on turn's ``wake`` and ``nudge`` kept when it has them.""" if records is None: return None - return [TurnTrajectory(format=record.get("format", record.get("native_format")), atif=record.get("atif")) + return [TurnTrajectory(format=record.get("format", record.get("native_format")), atif=record.get("atif"), + **{key: record[key] for key in ("wake", "nudge") if key in record}) for record in records] +class TurnTrajectoryUrl(NamedTuple): + """One of a response's distinct trajectories: the 1-based turn of its per-turn list it is the trajectory of, and + its url. A url several turns stored is the last such turn's, since an atif/1 document is rewritten each turn and so + holds that turn's copy. ``turn`` is None for a response url the list lacks.""" + + turn: Optional[int] + url: str + + @dataclass class PromptResponse: prompt_id: str @@ -310,14 +325,32 @@ class PromptResponse: agent_name: str | None = None step_id: str | None = None structured_output: Any = None + # The last AVAILABLE trajectory only: the last turn's unless its upload failed, then the latest earlier turn's that + # stored one. On a step of several turns (a multi-turn prompt_agent step, an always_on step) that is one turn's + # alone: each turn's is in ``target_agent_per_turn_trajectory_object_urls``, and + # ``distinct_trajectory_object_urls()`` reads the whole run. agent_trajectory_object_url: str | None = None agent_trajectory_object_prefix: str | None = None + # One trajectory per turn, in turn order, None for a turn that stored none: a prompt_agent step's turns, or an + # always_on step's wakes with their nudges. target_agent_per_turn_trajectory_object_urls: list[str | None] | None = None # The step's usage, one entry per role that ran turns in it (``task_step.usage``); None before it was recorded. usage: list[dict] | None = None # Each turn's ``TurnTrajectory``, beside ``target_agent_per_turn_trajectory_object_urls``. target_agent_per_turn_trajectories: list[TurnTrajectory] | None = None + def distinct_trajectory_object_urls(self) -> list[TurnTrajectoryUrl]: + """The whole run's distinct trajectories in turn order, each with its turn: turns that stored none are skipped, + a url several turns stored (an atif/1 run's turns share one document) is listed once, at the last such turn, + then ``agent_trajectory_object_url`` (the last available trajectory alone), with no turn, when the list lacks + it. A response with no per-turn list has just that one. The explorer's ``runTrajectoryUrls`` reads the same.""" + last_turn = {url: turn for turn, url in enumerate(self.target_agent_per_turn_trajectory_object_urls or [], 1) + if url} + urls = [TurnTrajectoryUrl(turn, url) for url, turn in sorted(last_turn.items(), key=lambda item: item[1])] + if self.agent_trajectory_object_url and self.agent_trajectory_object_url not in last_turn: + urls.append(TurnTrajectoryUrl(None, self.agent_trajectory_object_url)) + return urls + def to_dict(self) -> dict[str, Any]: """The stored form: every field, plus the legacy key of each renamed one.""" data = dataclasses.asdict(self) diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 73e6f18ee..3c013b8f0 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -1510,7 +1510,8 @@ def record() -> None: await self._read_changes("after_turn") await self._schedule_read() - async def _trajectory(self, task_id: str, msg_id: str, turn: str) -> tuple[Optional[str], dict]: + async def _trajectory(self, task_id: str, msg_id: str, turn: str, *, nudge: bool = False, + ) -> tuple[Optional[str], dict]: """The agent turn's trajectory, its url and record joining the run's per-turn lists. When the run prescribes atif/1 and the agent offers it, the turn's copy is read off the turn's path, and its url and record are filled in when the run ends (``_settle_copies``); otherwise its native one is read within one fetch cap @@ -1518,7 +1519,7 @@ async def _trajectory(self, task_id: str, msg_id: str, turn: str) -> tuple[Optio timeline field that says which turn it is.""" step, card = self.step, self.agent.a2a_card or {} extension = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) - record = TurnTrajectory(format=None, atif=None) + record = TurnTrajectory(format=None, atif=None, wake=self.wakes, nudge=nudge) # which turn: k needn't be wake k native = functools.partial(fetch_native_trajectory, self.target_url, extension, task_id, step._trajectory_prefix(), msg_id, card=card, sandbox_type=self.agent.sandbox_type, headers=self.agent.control_headers) if extension else _no_trajectory @@ -1606,7 +1607,7 @@ def record() -> None: cut_off = TIME_LIMIT if stopped is not None else self._limit_reached(state, term) messages, quiet = await self._take_messages() await self._read_changes("nudge") - traj, which = await self._trajectory(task_id, msg_id, f"nudge after wake {self.wakes}") + traj, which = await self._trajectory(task_id, msg_id, f"nudge after wake {self.wakes}", nudge=True) self.final_task_id = task_id plain = term.response_text or "" outcome = "message_user" if messages else "stay_quiet" if quiet else "neither" diff --git a/tst/unit/cli/always_on_step_output_test.py b/tst/unit/cli/always_on_step_output_test.py index a6d50b52a..86fd98c14 100644 --- a/tst/unit/cli/always_on_step_output_test.py +++ b/tst/unit/cli/always_on_step_output_test.py @@ -5,7 +5,7 @@ from types import SimpleNamespace from agent_env.cli.task.run import _step_output_lines -from agent_env.task_step.context import PromptResponse, TaskStepContext +from agent_env.task_step.context import PromptResponse, TaskStepContext, TurnTrajectory def test_an_always_on_steps_response_is_shown(): @@ -28,3 +28,89 @@ def test_an_always_on_step_shows_its_own_response_when_a_parallel_step_added_a_l [lines] = _step_output_lines(SimpleNamespace(type="always_on", id="loop"), context) assert "Recap sent." in lines and "Side answer." not in lines + + +def test_an_always_on_steps_output_lists_every_wakes_trajectory_not_only_the_last(): + wakes = [f"s3://b/wake-{n}.json" for n in range(1, 4)] + context = TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="loop", response="Recap sent.", step_id="loop", agent_trajectory_object_url=wakes[-1], + target_agent_per_turn_trajectory_object_urls=[wakes[0], None, *wakes[1:]])]) + + [lines] = _step_output_lines(SimpleNamespace(type="always_on", id="loop"), context) + + assert f"agent_trajectory_object_url: {wakes[-1]}" in lines + assert ("trajectory_object_urls (3, in turn order):\n" + f" - turn 1 of 4: {wakes[0]}\n - turn 3 of 4: {wakes[1]}\n - turn 4 of 4: {wakes[2]}") in lines + + +def test_each_listed_trajectory_names_its_turn_since_a_turn_that_stored_none_is_skipped(): + """Turn 2 stored no trajectory, so the second url listed is turn 3's: the line says so rather than leave a reader to + count it as turn 2.""" + context = TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="chat", response="Booked.", step_id="chat", agent_trajectory_object_url="s3://b/3.json", + target_agent_per_turn_trajectory_object_urls=["s3://b/1.json", None, "s3://b/3.json"])]) + + [lines] = _step_output_lines(SimpleNamespace(type="prompt_agent", id="chat"), context) + + assert " - turn 1 of 3: s3://b/1.json\n - turn 3 of 3: s3://b/3.json" in lines + + +def test_an_always_on_steps_listed_trajectories_name_their_wake_and_a_nudge(): + """The per-turn list holds wake 1's nudge beside the wakes, so turn 2 is that nudge and turn 3 is wake 2.""" + urls = ["s3://b/wake-1.json", "s3://b/nudge-1.json", "s3://b/wake-2.json"] + context = TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="loop", response="Recap sent.", step_id="loop", agent_trajectory_object_url=urls[-1], + target_agent_per_turn_trajectory_object_urls=urls, + target_agent_per_turn_trajectories=[TurnTrajectory(format=None, atif=None, wake=1, nudge=False), + TurnTrajectory(format=None, atif=None, wake=1, nudge=True), + TurnTrajectory(format=None, atif=None, wake=2, nudge=False)])]) + + [lines] = _step_output_lines(SimpleNamespace(type="always_on", id="loop"), context) + + assert (f" - turn 1 of 3 (wake 1): {urls[0]}\n - turn 2 of 3 (nudge after wake 1): {urls[1]}\n" + f" - turn 3 of 3 (wake 2): {urls[2]}") in lines + + +def test_a_single_turn_response_lists_no_trajectories_beside_its_one(): + context = TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="loop", response="Recap sent.", step_id="loop", agent_trajectory_object_url="s3://b/only.json", + target_agent_per_turn_trajectory_object_urls=["s3://b/only.json"])]) + + [lines] = _step_output_lines(SimpleNamespace(type="always_on", id="loop"), context) + + assert "agent_trajectory_object_url: s3://b/only.json" in lines and "trajectory_object_urls" not in lines + + +def test_a_multi_turn_prompt_agent_steps_output_lists_every_turns_trajectory(): + turns = [f"s3://b/turn-{n}.json" for n in range(1, 4)] + context = TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="chat", response="Booked.", step_id="chat", agent_trajectory_object_url=turns[-1], + target_agent_per_turn_trajectory_object_urls=turns)]) + + [lines] = _step_output_lines(SimpleNamespace(type="prompt_agent", id="chat"), context) + + assert f"agent_trajectory_object_url: {turns[-1]}" in lines + assert "trajectory_object_urls (3, in turn order):\n" + "\n".join( + f" - turn {n} of 3: {u}" for n, u in enumerate(turns, 1)) in lines + + +def test_turns_sharing_one_atif_document_list_it_once(): + context = TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="chat", response="Booked.", step_id="chat", agent_trajectory_object_url="s3://b/atif.json", + target_agent_per_turn_trajectory_object_urls=["s3://b/atif.json"] * 3)]) + + [lines] = _step_output_lines(SimpleNamespace(type="prompt_agent", id="chat"), context) + + assert "agent_trajectory_object_url: s3://b/atif.json" in lines and "trajectory_object_urls" not in lines + + +def test_a_document_several_turns_stored_is_listed_at_the_last_of_them(): + """An atif/1 run whose second turn's copy failed stores [A, B, A]: A is rewritten each turn, so it is turn 3's.""" + context = TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="chat", response="Booked.", step_id="chat", agent_trajectory_object_url="s3://b/atif.json", + target_agent_per_turn_trajectory_object_urls=["s3://b/atif.json", "s3://b/native-2.json", "s3://b/atif.json"])]) + + [lines] = _step_output_lines(SimpleNamespace(type="prompt_agent", id="chat"), context) + + assert ("trajectory_object_urls (2, in turn order):\n" + " - turn 2 of 3: s3://b/native-2.json\n - turn 3 of 3: s3://b/atif.json") in lines diff --git a/tst/unit/task_step/run_context_object_url_test.py b/tst/unit/task_step/run_context_object_url_test.py index 2689aae09..2d66ddd84 100644 --- a/tst/unit/task_step/run_context_object_url_test.py +++ b/tst/unit/task_step/run_context_object_url_test.py @@ -120,3 +120,30 @@ def keyed(legacy, neutral, value): "stdout_artifact (verifier_id=v): out v1 -> mem://b/stdout.txt", "stderr_artifact (verifier_id=v): err v1 -> mem://b/stderr.txt", ] + + +@pytest.mark.parametrize(("per_turn", "last", "expected"), [ + pytest.param(["mem://w/1.json", None, "mem://w/3.json", "mem://w/4.json"], "mem://w/4.json", + [(1, "mem://w/1.json"), (3, "mem://w/3.json"), (4, "mem://w/4.json")], + id="wakes-in-order-without-the-failed-one-each-with-its-turn"), + pytest.param(["mem://atif/doc.json"] * 3, "mem://atif/doc.json", [(3, "mem://atif/doc.json")], + id="turns-sharing-one-document-read-once-at-the-last"), + pytest.param(["mem://atif/doc.json", "mem://native/2.json", "mem://atif/doc.json"], "mem://atif/doc.json", + [(2, "mem://native/2.json"), (3, "mem://atif/doc.json")], + id="a-repeated-document-is-its-last-turns-as-the-explorer-labels-it"), + pytest.param(None, "mem://one.json", [(None, "mem://one.json")], id="no-per-turn-list"), + pytest.param(["mem://w/1.json"], "mem://w/2.json", [(1, "mem://w/1.json"), (None, "mem://w/2.json")], + id="a-last-url-the-list-lacks-comes-last-with-no-turn"), + pytest.param([None], None, [], id="none-stored"), +]) +def test_distinct_trajectory_object_urls_is_every_turns_trajectory_in_turn_order(per_turn, last, expected): + response = PromptResponse(prompt_id="p1", response="done", agent_trajectory_object_url=last, + target_agent_per_turn_trajectory_object_urls=per_turn) + assert response.distinct_trajectory_object_urls() == expected + + +def test_a_stored_runs_every_turn_reads_back_from_its_s3_named_keys_alone(): + stored = {"prompt_id": "p1", "response": "done", "agent_trajectory_s3_uri": _URL, + "target_agent_per_turn_trajectory_s3_uris": _TURNS} + assert [url for _, url in PromptResponse.from_dict(stored).distinct_trajectory_object_urls()] == [ + "mem://b/t/1.json", "mem://b/t/2.json"] diff --git a/tst/unit/task_step/test_always_on_trajectory_formats.py b/tst/unit/task_step/test_always_on_trajectory_formats.py index 4ef63a5c2..152368279 100644 --- a/tst/unit/task_step/test_always_on_trajectory_formats.py +++ b/tst/unit/task_step/test_always_on_trajectory_formats.py @@ -8,7 +8,7 @@ import pytest from agentenv_protocol.a2a_agent import TRAJECTORY_V1 -from agent_env.task_step.context import AtifRecord +from agent_env.task_step.context import AtifRecord, PromptResponse from agent_env.task_step.snapshot_utils import atif_copies from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.prompt_agent import StoredTrajectory @@ -216,6 +216,53 @@ async def test_a_run_that_prescribes_nothing_reads_native_and_names_no_turn_in_t assert seen["copies"] == [] and seen["native"] assert response.target_agent_per_turn_trajectory_object_urls == [ f"file:///store/native-{task_id}.json" for task_id in seen["native"]] - assert response.target_agent_per_turn_trajectories == [{"format": "shots/1", "atif": None}] * len(seen["native"]) + assert [{k: r[k] for k in ("format", "atif")} for r in response.target_agent_per_turn_trajectories] == [ + {"format": "shots/1", "atif": None}] * len(seen["native"]) ends = [e for e in rig.stored(context)["timeline"] if e["event"] in ("agent_turn_end", "nudge")] assert ends and all("turn" not in e and "trajectory_format" not in e for e in ends) + + +@pytest.mark.asyncio +async def test_the_prompt_response_holds_every_wakes_trajectory_in_wake_order_not_only_the_last(monkeypatch, tmp_path): + """agent_trajectory_object_url is the last wake's alone; every wake's is on the prompt response too, in wake order, + under both stored keys, so a reader of the stored run reads them all without the timeline.""" + seen = _reads(monkeypatch) + rig = Rig(monkeypatch, tmp_path, agent=_quiet) + await rig.arm() + for day in (10, 11): + rig.triggers(rig.notify_at(f"alert-{day}", f"2026-11-{day}T14:00:00Z", "Sam: any news?")) + context = await rig.run(rig.step(max_wakes=3), _offering(rig, prescribed=False, extension=NATIVE_ONLY)) + + [response] = context.prompt_responses + wakes = [f"file:///store/native-{task_id}.json" for task_id in seen["native"]] + assert len(wakes) == len(set(wakes)) == 3 + assert response.target_agent_per_turn_trajectory_object_urls == wakes + assert response.agent_trajectory_object_url == wakes[-1] + assert [url for _, url in response.distinct_trajectory_object_urls()] == wakes + ends = [e["trajectory_url"] for e in rig.stored(context)["timeline"] if e["event"] == "agent_turn_end"] + assert ends == wakes + stored = response.to_dict() + assert stored["target_agent_per_turn_trajectory_s3_uris"] == stored[ + "target_agent_per_turn_trajectory_object_urls"] == wakes + assert stored["agent_trajectory_s3_uri"] == wakes[-1] + legacy_only = {k: v for k, v in stored.items() if not k.endswith(("_object_url", "_object_urls"))} + assert [url for _, url in PromptResponse.from_dict(legacy_only).distinct_trajectory_object_urls()] == wakes + + +@pytest.mark.asyncio +async def test_each_turn_says_which_wake_it_is_and_a_nudge_is_marked_so_turn_k_is_not_read_as_wake_k(monkeypatch, + tmp_path): + """The per-turn lists hold a wake's nudge turn beside the wakes, so the second turn here is wake 1's nudge, not + wake 2: each turn's record names its wake, and marks a nudge, through a stored round trip.""" + _reads(monkeypatch) + rig = Rig(monkeypatch, tmp_path, agent=_nudged) + await rig.arm() + rig.triggers(rig.notify_at("alert-10", "2026-11-10T14:00:00Z", "Sam: any news?")) + context = await rig.run(rig.step(max_wakes=2), _offering(rig, prescribed=False)) + + [response] = context.prompt_responses + turns = [(r["wake"], r["nudge"]) for r in response.target_agent_per_turn_trajectories] + assert turns == [(1, False), (1, True), (2, False)] + assert len(response.target_agent_per_turn_trajectory_object_urls) == 3 + stored = PromptResponse.from_dict(response.to_dict()).target_agent_per_turn_trajectories + assert [(r["wake"], r["nudge"]) for r in stored] == turns