From f829d6df26c8fcd013242d5a1e38f068d50ada4f Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 10:35:41 -0800 Subject: [PATCH 1/6] fix(always_on): readers of a run's trajectory read every wake, not only the last An always_on step's prompt response already records each wake's trajectory, in wake order, under target_agent_per_turn_trajectory_s3_uris / _object_urls. agent_trajectory_s3_uri is the last wake alone (on a 7-wake run, 15 of its 353 tool calls). Every verifier that scores reads the per-turn list or no trajectory, so no score came from one wake. Two readers here did read only the last: - `agent-env task run` printed only agent_trajectory_object_url. It now lists every turn's url too, when there is more than one, and keeps the existing line. - The explorer's download bar offered only the last turn of each prompt response. It now gives one entry per turn, labelled by turn, reading turns that share an atif/1 document once. PromptResponse.trajectory_object_urls() and the UI's runTrajectoryUrls() name the rule once: each turn's url in order, without gaps or repeats, then the last url if the list lacks it. It is the same rule agentenvhub-sdk's trajectory_validation already applies. A test pins that an always_on run's stored prompt response carries every wake under both stored keys. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/cli/task/run.py | 3 ++ .../ui/src/lib/bar-downloads.smoke.ts | 49 +++++++++++++++++++ .../explorer/ui/src/lib/bar-downloads.ts | 33 ++++++++----- .../ui/src/lib/trajectory-url.smoke.ts | 38 +++++++++++++- .../explorer/ui/src/lib/trajectory-url.ts | 31 +++++++++++- src/agent_env/task_step/context.py | 12 +++++ tst/unit/cli/always_on_step_output_test.py | 22 +++++++++ .../task_step/run_context_object_url_test.py | 22 +++++++++ .../test_always_on_trajectory_formats.py | 29 ++++++++++- 9 files changed, 224 insertions(+), 15 deletions(-) diff --git a/src/agent_env/cli/task/run.py b/src/agent_env/cli/task/run.py index 71ef6df67..8ca37c149 100644 --- a/src/agent_env/cli/task/run.py +++ b/src/agent_env/cli/task/run.py @@ -117,6 +117,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(urls := pr.trajectory_object_urls()) > 1: + lines.append(f" trajectory_object_urls ({len(urls)}, in turn order):") + lines.extend(f" - {url}" for url in urls) 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/lib/bar-downloads.smoke.ts b/src/agent_env/explorer/ui/src/lib/bar-downloads.smoke.ts index 01080eb08..15d6208d2 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 @@ -156,6 +156,55 @@ function main(): void { ); } + // An always_on step: its agent_trajectory_s3_uri is the last wake alone, so each wake gets its own download. + { + 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', + }, + ], + ); + assert( + downloads.map(d => d.objectUrl).join(',') === 'obj://w/1,obj://w/3', + 'every wake that stored a trajectory is downloadable, in wake order', + ); + assert( + downloads.map(d => d.label).join('|') === 'Trajectory, turn 1 of 3|Trajectory, turn 3 of 3', + 'each wake is labelled by its turn', + ); + } + + // Beside other steps the wakes keep their step's label; a single-turn step keeps its plain one. + { + const downloads = buildBarDownloads( + [ + { agent_trajectory_s3_uri: 'obj://t/setup', step_id: 'setup' }, + { + agent_trajectory_object_url: 'obj://w/2', + target_agent_per_turn_trajectory_object_urls: ['obj://w/1', 'obj://w/2'], + step_id: 'week', + }, + { + agent_trajectory_s3_uri: 'obj://atif/doc', + target_agent_per_turn_trajectory_s3_uris: ['obj://atif/doc', 'obj://atif/doc'], + step_id: 'copied', + }, + ], + ); + assert( + downloads.map(d => d.label).join('|') === + 'setup|week, turn 1 of 2|week, turn 2 of 2|copied', + 'a multi-turn step gives one entry per turn; turns sharing a document give one', + ); + assert( + new Set(downloads.map(d => d.key)).size === downloads.length, + 'keys stay unique', + ); + } + 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..3f2e9b3a3 100644 --- a/src/agent_env/explorer/ui/src/lib/bar-downloads.ts +++ b/src/agent_env/explorer/ui/src/lib/bar-downloads.ts @@ -5,7 +5,7 @@ /** 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 TrajectoryUrlKeys, runTrajectoryUrls } from './trajectory-url'; /** The subset of a prompt-response the bar needs to label a trajectory. */ export interface BarDownloadTrajectory extends TrajectoryUrlKeys { @@ -25,24 +25,33 @@ export interface BarDownload { /** 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. */ + * "Trajectory". A response of several turns (a multi-turn prompt_agent step, an always_on step's wakes) gives one + * entry per turn's trajectory, in turn order, its label naming the turn: its last turn's alone would leave the + * earlier turns undownloadable. Entries 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.flatMap(({ pr, runs }, i) => { + const base = single ? 'Trajectory' : pr.step_id || pr.prompt_id || `Trajectory ${i + 1}`; - const objectUrl = trajectoryUrl(pr) as string; - return { - key: objectUrl, - label, - title: pr.model ? `Download ${label} (${pr.model})` : `Download ${label}`, - objectUrl, - }; + return runs.map(({ url, turn, turns }) => { + const label = + runs.length > 1 && turn !== undefined + ? `${base}, turn ${turn} of ${turns}` + : base; + return { + key: url, + label, + title: pr.model ? `Download ${label} (${pr.model})` : `Download ${label}`, + objectUrl: url, + }; + }); }); } 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..9087a1723 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,7 @@ * 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 { perTurnTrajectoryUrls, runTrajectoryUrls, trajectoryUrl } from './trajectory-url'; let failures = 0; function assert(cond: unknown, msg: string): void { @@ -78,6 +78,42 @@ 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( + JSON.stringify(run) === + JSON.stringify([ + { 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( + JSON.stringify(runTrajectoryUrls({ agent_trajectory_s3_uri: 'obj://one.json' })) === + JSON.stringify([{ url: 'obj://one.json' }]), + 'a response with no per-turn list has its one trajectory', + ); + assert(runTrajectoryUrls({}).length === 0, 'no key: no trajectories'); + } + 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..9ee10fb4b 100644 --- a/src/agent_env/explorer/ui/src/lib/trajectory-url.ts +++ b/src/agent_env/explorer/ui/src/lib/trajectory-url.ts @@ -9,7 +9,8 @@ export interface TrajectoryUrlKeys { target_agent_per_turn_trajectory_object_urls?: unknown; } -/** The trajectory of the response's last turn, if it has one. */ +/** The trajectory of the response's last turn, if it has one. On an always_on step that is the last wake alone: + * `runTrajectoryUrls` reads the whole run. */ export function trajectoryUrl( pr: TrajectoryUrlKeys | null | undefined, ): string | undefined { @@ -28,3 +29,31 @@ 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). */ +export interface RunTrajectory { + url: string; + turn?: number; + turns?: number; +} + +/** Every trajectory of the response, in turn order: each turn's, skipping the turns that stored none and repeats (an + * atif/1 run's turns share one document), then the last turn's url when the list lacks it. Core's + * `PromptResponse.trajectory_object_urls` reads the same. */ +export function runTrajectoryUrls( + pr: TrajectoryUrlKeys | null | undefined, +): RunTrajectory[] { + const perTurn = perTurnTrajectoryUrls(pr) ?? []; + const out: RunTrajectory[] = []; + const seen = new Set(); + perTurn.forEach((url, index) => { + if (url && !seen.has(url)) { + seen.add(url); + out.push({ url, turn: index + 1, turns: perTurn.length }); + } + }); + const last = trajectoryUrl(pr); + if (last && !seen.has(last)) out.push({ url: last }); + return out; +} diff --git a/src/agent_env/task_step/context.py b/src/agent_env/task_step/context.py index a02304790..133b4e34e 100644 --- a/src/agent_env/task_step/context.py +++ b/src/agent_env/task_step/context.py @@ -310,14 +310,26 @@ class PromptResponse: agent_name: str | None = None step_id: str | None = None structured_output: Any = None + # The LAST turn's trajectory only: a multi-turn prompt_agent step's last turn, an always_on step's last wake. Each + # turn's is in ``target_agent_per_turn_trajectory_object_urls``; ``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 (an always_on step's wakes and nudges), None for a turn that stored none. 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 trajectory_object_urls(self) -> list[str]: + """The whole run's trajectories, in turn order: each turn's, skipping turns that stored none and repeats (an + atif/1 run's turns share one document), then ``agent_trajectory_object_url`` (the last turn's alone, an + always_on step's last wake) when the list lacks it; a response with no per-turn list has just that one.""" + urls = list(dict.fromkeys(url for url in self.target_agent_per_turn_trajectory_object_urls or [] if url)) + if self.agent_trajectory_object_url and self.agent_trajectory_object_url not in urls: + urls.append(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/tst/unit/cli/always_on_step_output_test.py b/tst/unit/cli/always_on_step_output_test.py index a6d50b52a..85335affe 100644 --- a/tst/unit/cli/always_on_step_output_test.py +++ b/tst/unit/cli/always_on_step_output_test.py @@ -28,3 +28,25 @@ 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" + "\n".join(f" - {u}" for u in wakes) 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 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..60e67c269 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,25 @@ 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", + ["mem://w/1.json", "mem://w/3.json", "mem://w/4.json"], id="wakes-in-order-without-the-failed-one"), + pytest.param(["mem://atif/doc.json"] * 3, "mem://atif/doc.json", ["mem://atif/doc.json"], + id="turns-sharing-one-document-read-once"), + pytest.param(None, "mem://one.json", ["mem://one.json"], id="no-per-turn-list"), + pytest.param(["mem://w/1.json"], "mem://w/2.json", ["mem://w/1.json", "mem://w/2.json"], + id="a-last-url-the-list-lacks-comes-last"), + pytest.param([None], None, [], id="none-stored"), +]) +def test_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.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 PromptResponse.from_dict(stored).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..9eef82518 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 @@ -219,3 +219,30 @@ async def test_a_run_that_prescribes_nothing_reads_native_and_names_no_turn_in_t assert 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 response.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 PromptResponse.from_dict(legacy_only).trajectory_object_urls() == wakes From 9c69ac9f742a45b0433707ca986777bb5cc1625c Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 10:59:55 -0800 Subject: [PATCH 2/6] fix(explorer): one download per prompt response, with a turn picker for a multi-turn step Two kinds of step store one trajectory per turn in target_agent_per_turn_trajectory_object_urls: an always_on step, one per wake, and a multi-turn prompt_agent step, one per turn (a user-sim conversation). The previous commit made the download bar offer every turn, but as one button per turn, so a 20-turn conversation put 20 buttons in the bar. The bar now has one entry per prompt response: - A response with one trajectory keeps its label, tooltip and button exactly as before. - A response whose turns stored several distinct trajectories gets a button that downloads its last turn, labelled "Trajectory (turn n of n)" (or " (turn n of n)"), and a chevron that opens a turn picker listing every turn as "turn k of n". In the collapsed dropdown it is one row with the turns in a submenu. - A Claude Code atif/1 run, whose turns share one document, still gets one plain button. Both use the explorer's existing Radix Themes DropdownMenu. The collapse threshold now counts responses. Tests: the bar smoke covers a single trajectory (unchanged), an always_on run of several wakes, a 20-turn prompt_agent conversation beside a single-turn step, and atif shared turns; the trajectory-url smoke and the `task run` CLI tests add a multi-turn prompt_agent case. No grader or score reads any of this. Co-Authored-By: Claude Opus 5.5 --- .../src/components/task-instance-viewer.tsx | 109 ++++++++++++++---- .../ui/src/lib/bar-downloads.smoke.ts | 77 ++++++++++--- .../explorer/ui/src/lib/bar-downloads.ts | 79 +++++++++---- .../ui/src/lib/trajectory-url.smoke.ts | 13 +++ tst/unit/cli/always_on_step_output_test.py | 22 ++++ 5 files changed, 239 insertions(+), 61 deletions(-) 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..287558142 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 @@ -46,7 +46,7 @@ import { import { buildBarDownloads, shouldCollapseBarDownloads, - type BarDownload, + type BarDownloadFile, } from '../lib/bar-downloads'; import { collectedZipFiles, isAbsoluteArtifactPath } from '../lib/collected-zip-files'; @@ -613,7 +613,7 @@ export function TaskInstanceViewer({ ); const collapseBarDownloads = shouldCollapseBarDownloads(barDownloads.length); const runBarDownload = useCallback( - (download: BarDownload) => { + (download: BarDownloadFile) => { void handleDownloadTrajectory(download.objectUrl); }, [handleDownloadTrajectory], @@ -853,31 +853,94 @@ 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} + + +
+ {item.turnPicker.turns.map(turn => ( + runBarDownload(turn)} + title={turn.title} + > + + {turn.label} + + ))} +
+
+
+ ) : ( + runBarDownload(item)} + title={item.title} + > + + {item.label} + + ), + )}
) : ( - barDownloads.map(item => ( - - )) + barDownloads.map(item => + item.turnPicker ? ( + // A response of several turns: its button downloads the last turn, the chevron picks any turn. +
+ + + + + + +
+ {item.turnPicker.turns.map(turn => ( + runBarDownload(turn)} + title={turn.title} + > + + {turn.label} + + ))} +
+
+
+
+ ) : ( + + ), + ) )} 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 15d6208d2..45511c6cd 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 @@ -156,7 +156,19 @@ function main(): void { ); } - // An always_on step: its agent_trajectory_s3_uri is the last wake alone, so each wake gets its own download. + // 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( + JSON.stringify(only) === + JSON.stringify({ 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( [ @@ -164,45 +176,74 @@ function main(): void { 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( - downloads.map(d => d.objectUrl).join(',') === 'obj://w/1,obj://w/3', - 'every wake that stored a trajectory is downloadable, in wake order', + 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( - downloads.map(d => d.label).join('|') === 'Trajectory, turn 1 of 3|Trajectory, turn 3 of 3', - 'each wake is labelled by its turn', + 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'); } - // Beside other steps the wakes keep their step's label; a single-turn step keeps its plain 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_s3_uri: 'obj://t/setup', step_id: 'setup' }, + { agent_trajectory_object_url: 'obj://t/setup', step_id: 'setup' }, { - agent_trajectory_object_url: 'obj://w/2', - target_agent_per_turn_trajectory_object_urls: ['obj://w/1', 'obj://w/2'], - step_id: 'week', + 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( + JSON.stringify(downloads[1]?.turnPicker?.turns.map(t => t.objectUrl)) === JSON.stringify(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'], + 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).join('|') === - 'setup|week, turn 1 of 2|week, turn 2 of 2|copied', - 'a multi-turn step gives one entry per turn; turns sharing a document give one', - ); - assert( - new Set(downloads.map(d => d.key)).size === downloads.length, - 'keys stay unique', + 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'); } if (failures > 0) { 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 3f2e9b3a3..a74604c79 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,11 @@ /** 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, runTrajectoryUrls } from './trajectory-url'; +import { type RunTrajectory, type TrajectoryUrlKeys, runTrajectoryUrls } from './trajectory-url'; /** The subset of a prompt-response the bar needs to label a trajectory. */ export interface BarDownloadTrajectory extends TrajectoryUrlKeys { @@ -14,7 +14,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,11 +24,33 @@ 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". A response of several turns (a multi-turn prompt_agent step, an always_on step's wakes) gives one - * entry per turn's trajectory, in turn order, its label naming the turn: its last turn's alone would leave the - * earlier turns undownloadable. 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, or its last turn's when it has several. */ +export interface BarDownload extends BarDownloadFile { + /** Set only when the response's turns stored several distinct trajectories. */ + turnPicker?: BarDownloadTurnPicker; +} + +/** Which turn a trajectory is: "turn k of n", or "last turn" for a last-turn url the per-turn list lacks. */ +function turnLabel(run: RunTrajectory): string { + return run.turn !== undefined ? `turn ${run.turn} of ${run.turns}` : 'last turn'; +} + +/** 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 turn, its label naming that turn, e.g. "Trajectory (turn 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[] { @@ -36,22 +59,38 @@ export function buildBarDownloads( .filter(({ runs }) => runs.length > 0); const single = withTrajectory.length === 1; - return withTrajectory.flatMap(({ pr, runs }, i) => { - const base = single + return withTrajectory.map(({ pr, runs }, i) => { + const name = single ? 'Trajectory' : pr.step_id || pr.prompt_id || `Trajectory ${i + 1}`; - return runs.map(({ url, turn, turns }) => { - const label = - runs.length > 1 && turn !== undefined - ? `${base}, turn ${turn} of ${turns}` - : base; + const model = pr.model ? ` (${pr.model})` : ''; + const last = runs[runs.length - 1]!; + if (runs.length === 1) { return { - key: url, - label, - title: pr.model ? `Download ${label} (${pr.model})` : `Download ${label}`, - objectUrl: url, + key: last.url, + label: name, + title: `Download ${name}${model}`, + objectUrl: last.url, }; - }); + } + const turns = runs.map(run => ({ + key: run.url, + label: turnLabel(run), + title: `Download ${name}, ${turnLabel(run)}${model}`, + objectUrl: run.url, + })); + return { + key: last.url, + label: `${name} (${turnLabel(last)})`, + title: `Download ${name}, ${turnLabel(last)}${model}`, + objectUrl: last.url, + turnPicker: { + // Several runs means the per-turn list named at least one, so the first run has its turn count. + label: `${name} (${runs[0]!.turns} ${runs[0]!.turns === 1 ? 'turn' : 'turns'})`, + 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 9087a1723..a9058f308 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 @@ -114,6 +114,19 @@ function main(): void { assert(runTrajectoryUrls({}).length === 0, 'no key: no trajectories'); } + // 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', + ); + } + if (failures > 0) { console.error(`\n${failures} assertion(s) failed`); process.exit(1); diff --git a/tst/unit/cli/always_on_step_output_test.py b/tst/unit/cli/always_on_step_output_test.py index 85335affe..dc243c2f9 100644 --- a/tst/unit/cli/always_on_step_output_test.py +++ b/tst/unit/cli/always_on_step_output_test.py @@ -50,3 +50,25 @@ def test_a_single_turn_response_lists_no_trajectories_beside_its_one(): [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" - {u}" for u in turns) 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 From 8eb94b6f7dd3201c98958043497df61a114c4307 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 14:52:48 -0800 Subject: [PATCH 3/6] fix(explorer): a response's download is its own trajectory, not the run list's last entry The bar's main button took the last entry of runTrajectoryUrls. An atif/1 run whose middle turn's copy failed stores per-turn [A, B, A]; the de-duplicated list is [A, B], so the button downloaded B while agent_trajectory_object_url is A. It now downloads the response's own url (trajectoryUrl), labelled by the last turn that stored it, falling back to the list's last entry when the response has none. The picker still lists every distinct trajectory. A url the per-turn list lacks is labelled "last available", not "last turn". agent_trajectory_object_url is the last available trajectory, not always the last turn's: both writers (always_on, prompt_agent) take the last turn that stored one. Say so in PromptResponse, trajectory_object_urls() and the explorer's helpers. Co-Authored-By: Claude Opus 5.5 --- .../src/components/task-instance-viewer.tsx | 3 +- .../ui/src/lib/bar-downloads.smoke.ts | 54 +++++++++++++++++++ .../explorer/ui/src/lib/bar-downloads.ts | 46 +++++++++++----- .../explorer/ui/src/lib/trajectory-url.ts | 6 +-- src/agent_env/task_step/context.py | 9 ++-- 5 files changed, 96 insertions(+), 22 deletions(-) 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 287558142..ff0951511 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 @@ -893,7 +893,8 @@ export function TaskInstanceViewer({ ) : ( barDownloads.map(item => item.turnPicker ? ( - // A response of several turns: its button downloads the last turn, the chevron picks any turn. + // A response of several turns: its button downloads the last available trajectory, the chevron picks + // any turn.
@@ -862,29 +895,18 @@ export function TaskInstanceViewer({ {item.turnPicker.label} -
- {item.turnPicker.turns.map(turn => ( - runBarDownload(turn)} - title={turn.title} - > - - {turn.label} - - ))} -
+
) : ( - runBarDownload(item)} - title={item.title} - > - - {item.label} - + file={item} + onDownload={runBarDownload} + /> ), )}
@@ -899,7 +921,7 @@ export function TaskInstanceViewer({ -
- {item.turnPicker.turns.map(turn => ( - runBarDownload(turn)} - title={turn.title} - > - - {turn.label} - - ))} -
+
@@ -935,7 +949,7 @@ export function TaskInstanceViewer({ key={item.key} onClick={() => runBarDownload(item)} title={item.title} - className="flex items-center gap-1 px-2 py-1 rounded text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:bg-[var(--accent)] transition-colors" + className={`${BAR_BUTTON_CLASS} gap-1 px-2 py-1 rounded`} > {item.label} @@ -1038,13 +1052,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 1f7795320..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'; @@ -162,8 +165,12 @@ function main(): void { [{ agent_trajectory_s3_uri: 'obj://t/one', target_agent_per_turn_trajectory_s3_uris: ['obj://t/one'], model: 'm' }], ); assert( - JSON.stringify(only) === - JSON.stringify({ key: 'obj://t/one', label: 'Trajectory', title: 'Download Trajectory (m)', objectUrl: 'obj://t/one' }), + 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', ); } @@ -261,7 +268,7 @@ function main(): void { ); assert(downloads[0]?.turnPicker === undefined, 'the single-turn step has no turn picker'); assert( - JSON.stringify(downloads[1]?.turnPicker?.turns.map(t => t.objectUrl)) === JSON.stringify(turns) && + 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"', @@ -315,8 +322,9 @@ function main(): void { 'its label names the last turn that stored A', ); assert( - run?.turnPicker?.turns.map(t => t.objectUrl).join('|') === 'obj://atif/doc|obj://native/2', - 'its picker still lists every distinct trajectory', + 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', ); } @@ -347,6 +355,31 @@ function main(): void { ); } + // 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 f91ef0947..3e0775977 100644 --- a/src/agent_env/explorer/ui/src/lib/bar-downloads.ts +++ b/src/agent_env/explorer/ui/src/lib/bar-downloads.ts @@ -8,10 +8,8 @@ export const MAX_INLINE_BAR_DOWNLOADS = 2; import { type RunTrajectory, type TrajectoryUrlKeys, - perTurnTrajectoryUrls, runTrajectoryUrls, trajectoryUrl, - turnAt, } from './trajectory-url'; /** The subset of a prompt-response the bar needs to label a trajectory. */ @@ -65,15 +63,17 @@ function turnCount(run: RunTrajectory): string { return `${n} ${noun}${n === 1 ? '' : 's'}`; } -/** The trajectory a response's own download gets: its `agent_trajectory` url (the last available one), placed at the - * last turn that stored it; with no such url, the run's last trajectory. Not `runs`' last entry: an atif/1 run whose - * middle turn's copy failed stores [A, B, A], which `runs` reads as [A, B], while the response's url is A. */ +/** 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); - if (!url) return runs[runs.length - 1]!; - const perTurn = perTurnTrajectoryUrls(pr) ?? []; - const index = perTurn.lastIndexOf(url); - return index >= 0 ? { url, ...turnAt(pr, index, perTurn.length) } : { url }; + 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. 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 d86c6e36d..08839b7f0 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,9 @@ * Runner: plain TS, exits non-zero on assertion failure. From this package: * npx tsx src/lib/trajectory-url.smoke.ts */ -import { perTurnTrajectoryUrls, runTrajectoryUrls, trajectoryUrl } from './trajectory-url'; +import { isDeepStrictEqual } from 'node:util'; + +import { perTurnTrajectoryUrls, runTrajectoryUrls, trajectorySections, trajectoryUrl } from './trajectory-url'; let failures = 0; function assert(cond: unknown, msg: string): void { @@ -37,7 +39,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`, ); } @@ -90,12 +92,11 @@ function main(): void { ], }); assert( - JSON.stringify(run) === - JSON.stringify([ - { 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 }, - ]), + 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({ @@ -107,13 +108,70 @@ function main(): void { 'turns sharing one document read it once', ); assert( - JSON.stringify(runTrajectoryUrls({ agent_trajectory_s3_uri: 'obj://one.json' })) === - JSON.stringify([{ url: 'obj://one.json' }]), + 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({ 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 208f6f415..e7936a375 100644 --- a/src/agent_env/explorer/ui/src/lib/trajectory-url.ts +++ b/src/agent_env/explorer/ui/src/lib/trajectory-url.ts @@ -47,7 +47,7 @@ export interface RunTrajectory { } /** Turn `index` (0-based) of a per-turn list of `count`: its 1-based turn, and its wake when its record names one. */ -export function turnAt( +function turnAt( pr: TrajectoryUrlKeys | null | undefined, index: number, count: number, @@ -66,22 +66,41 @@ export function turnAt( return { turn: index + 1, turns: count, wake, wakes, nudge: record?.nudge === true }; } -/** Every trajectory of the response, in turn order: each turn's, skipping the turns that stored none and repeats (an - * atif/1 run's turns share one document), then the last available trajectory's url when the list lacks it. Core's - * `PromptResponse.trajectory_object_urls` reads the same. */ +/** 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 out: RunTrajectory[] = []; - const seen = new Set(); + const lastIndex = new Map(); perTurn.forEach((url, index) => { - if (url && !seen.has(url)) { - seen.add(url); - out.push({ url, ...turnAt(pr, index, perTurn.length) }); - } + 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 && !seen.has(last)) out.push({ url: last }); + 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 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 6196ab24e..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, NotRequired, Optional, TypedDict +from typing import Any, Literal, NamedTuple, NotRequired, Optional, TypedDict from agentenv_protocol import client as protocol_v1 @@ -297,6 +297,15 @@ def turn_trajectories(records: Optional[list[dict[str, Any]]]) -> Optional[list[ 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 @@ -316,25 +325,30 @@ 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 (an always_on step's last wake) unless its upload failed, then - # the latest earlier turn's that stored one. Each turn's is in ``target_agent_per_turn_trajectory_object_urls``; - # ``trajectory_object_urls()`` reads the whole run. + # 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 (an always_on step's wakes and nudges), None for a turn that stored 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 trajectory_object_urls(self) -> list[str]: - """The whole run's trajectories, in turn order: each turn's, skipping turns that stored none and repeats (an - atif/1 run's turns share one document), then ``agent_trajectory_object_url`` (the last available trajectory - alone) when the list lacks it; a response with no per-turn list has just that one.""" - urls = list(dict.fromkeys(url for url in self.target_agent_per_turn_trajectory_object_urls or [] if url)) - if self.agent_trajectory_object_url and self.agent_trajectory_object_url not in urls: - urls.append(self.agent_trajectory_object_url) + 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]: diff --git a/tst/unit/cli/always_on_step_output_test.py b/tst/unit/cli/always_on_step_output_test.py index dc243c2f9..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(): @@ -39,7 +39,36 @@ def test_an_always_on_steps_output_lists_every_wakes_trajectory_not_only_the_las [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" + "\n".join(f" - {u}" for u in wakes) 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(): @@ -61,7 +90,8 @@ def test_a_multi_turn_prompt_agent_steps_output_lists_every_turns_trajectory(): [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" - {u}" for u in turns) 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(): @@ -72,3 +102,15 @@ def test_turns_sharing_one_atif_document_list_it_once(): [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 60e67c269..2d66ddd84 100644 --- a/tst/unit/task_step/run_context_object_url_test.py +++ b/tst/unit/task_step/run_context_object_url_test.py @@ -124,21 +124,26 @@ def keyed(legacy, neutral, value): @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", - ["mem://w/1.json", "mem://w/3.json", "mem://w/4.json"], id="wakes-in-order-without-the-failed-one"), - pytest.param(["mem://atif/doc.json"] * 3, "mem://atif/doc.json", ["mem://atif/doc.json"], - id="turns-sharing-one-document-read-once"), - pytest.param(None, "mem://one.json", ["mem://one.json"], id="no-per-turn-list"), - pytest.param(["mem://w/1.json"], "mem://w/2.json", ["mem://w/1.json", "mem://w/2.json"], - id="a-last-url-the-list-lacks-comes-last"), + [(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_trajectory_object_urls_is_every_turns_trajectory_in_turn_order(per_turn, last, expected): +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.trajectory_object_urls() == expected + 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 PromptResponse.from_dict(stored).trajectory_object_urls() == ["mem://b/t/1.json", "mem://b/t/2.json"] + 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 64232c825..152368279 100644 --- a/tst/unit/task_step/test_always_on_trajectory_formats.py +++ b/tst/unit/task_step/test_always_on_trajectory_formats.py @@ -238,7 +238,7 @@ async def test_the_prompt_response_holds_every_wakes_trajectory_in_wake_order_no 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 response.trajectory_object_urls() == wakes + 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() @@ -246,7 +246,7 @@ async def test_the_prompt_response_holds_every_wakes_trajectory_in_wake_order_no "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 PromptResponse.from_dict(legacy_only).trajectory_object_urls() == wakes + assert [url for _, url in PromptResponse.from_dict(legacy_only).distinct_trajectory_object_urls()] == wakes @pytest.mark.asyncio From dd1c6e8cbe4ec2202cc7ab0fa8e1298adffed2c7 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 14:17:25 -0800 Subject: [PATCH 6/6] fix(explorer): the trajectory viewer labels an always_on run's turns by wake, as the bar does The viewer still labelled every section "Turn k/n". On an always_on run the per-turn list holds each wake's nudge beside the wakes, so turn k need not be wake k, and the bar beside it already said "wake k of n". turnLabel moves from bar-downloads to trajectory-url, and the viewer names a section's turn through it (sectionTurnLabel): "wake k of n", "nudge after wake k", "turn k of n" for a step or run whose records name no wake, "last available" for a url the per-turn list lacks, and nothing for a response of one section. Other steps' sections now read "turn k of n" too, the bar's wording. Co-Authored-By: Claude Opus 5.5 --- .../src/components/task-instance-viewer.tsx | 14 ++---- .../explorer/ui/src/lib/bar-downloads.ts | 11 +---- .../ui/src/lib/trajectory-url.smoke.ts | 47 ++++++++++++++++++- .../explorer/ui/src/lib/trajectory-url.ts | 17 +++++++ 4 files changed, 69 insertions(+), 20 deletions(-) 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 a20ae01af..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 @@ -86,6 +86,7 @@ import { type TrajectorySection, type TrajectoryUrlKeys, perTurnTrajectoryUrls, + sectionTurnLabel, trajectorySections, trajectoryUrl, } from '../lib/trajectory-url'; @@ -334,15 +335,10 @@ export function TaskInstanceViewer({ const carryover = prevByUri.get(pr._entryObjectUrl); const initialStatus: TrajectoryState['status'] = carryover?.status ?? (ordered.length === 1 ? 'loading' : 'idle'); - const { turn, turns, turnIndexes } = pr._section; - // Which turn, as the bar names it: only when the response has several distinct trajectories, so a - // document its turns share is not called its last turn's alone. - const turnSuffix = - pr._sectionCount <= 1 - ? '' - : turn !== undefined - ? ` · Turn ${turn}/${turns}` - : ' · last available'; + 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})` : ''; const textOf = (turnIndex: number) => 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 3e0775977..4d5ce1185 100644 --- a/src/agent_env/explorer/ui/src/lib/bar-downloads.ts +++ b/src/agent_env/explorer/ui/src/lib/bar-downloads.ts @@ -10,6 +10,7 @@ import { type TrajectoryUrlKeys, runTrajectoryUrls, trajectoryUrl, + turnLabel, } from './trajectory-url'; /** The subset of a prompt-response the bar needs to label a trajectory. */ @@ -46,16 +47,6 @@ export interface BarDownload extends BarDownloadFile { turnPicker?: BarDownloadTurnPicker; } -/** 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. */ -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'; -} - /** 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 { 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 08839b7f0..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 @@ -6,7 +6,13 @@ */ import { isDeepStrictEqual } from 'node:util'; -import { perTurnTrajectoryUrls, runTrajectoryUrls, trajectorySections, trajectoryUrl } from './trajectory-url'; +import { + perTurnTrajectoryUrls, + runTrajectoryUrls, + sectionTurnLabel, + trajectorySections, + trajectoryUrl, +} from './trajectory-url'; let failures = 0; function assert(cond: unknown, msg: string): void { @@ -213,6 +219,45 @@ function main(): void { ); } + // 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 e7936a375..508313dd0 100644 --- a/src/agent_env/explorer/ui/src/lib/trajectory-url.ts +++ b/src/agent_env/explorer/ui/src/lib/trajectory-url.ts @@ -66,6 +66,16 @@ function turnAt( 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 @@ -94,6 +104,13 @@ 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,