From bf1eada575c38e7cca9a15e70946668a462033f2 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:57:23 +0800 Subject: [PATCH] fix(webui): navigate complete prompt history with bounded pages --- docs/webui.md | 6 + nanobot/webui/client_contract.py | 3 +- nanobot/webui/transcript.py | 104 +++- nanobot/webui/ws_http.py | 28 ++ tests/webui/test_prompt_index.py | 89 ++++ webui/browser/fixture.tsx | 21 +- webui/browser/prompt-rail.spec.ts | 74 +++ .../src/components/thread/PromptNavigator.tsx | 50 +- webui/src/components/thread/PromptRail.tsx | 472 +++++------------- webui/src/components/thread/ThreadShell.tsx | 15 +- .../src/components/thread/ThreadViewport.tsx | 96 +++- .../src/components/thread/promptNavigation.ts | 1 + webui/src/globals.css | 10 + webui/src/hooks/usePromptHistory.ts | 162 ++++++ webui/src/lib/api.ts | 21 + webui/src/lib/types.ts | 11 + webui/src/tests/prompt-navigator.test.tsx | 15 + webui/src/tests/thread-shell.test.tsx | 41 ++ webui/src/tests/thread-viewport.test.tsx | 31 +- webui/src/tests/usePromptHistory.test.tsx | 100 ++++ 20 files changed, 949 insertions(+), 401 deletions(-) create mode 100644 tests/webui/test_prompt_index.py create mode 100644 webui/browser/prompt-rail.spec.ts create mode 100644 webui/src/hooks/usePromptHistory.ts create mode 100644 webui/src/tests/usePromptHistory.test.tsx diff --git a/docs/webui.md b/docs/webui.md index 4af9220d2..e2609fbaf 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -56,6 +56,12 @@ Manual config still works. Same-machine localhost WebUI access can run without a The WebUI is served by the WebSocket channel on port `8765` by default. The gateway health endpoint, `18790` by default, is not the browser UI. +## Navigate a long conversation + +On wide conversation panes, the left message rail lists all saved prompts independently of the loaded message page. Scroll the rail to browse, hover to preview, and click to jump directly to a prompt; its edges fade without extending the conversation layout. The header's message navigation also supports searching the prompt summaries. Both lists render a visible window rather than thousands of controls. Older compatible hosts without `webui.prompt-navigation.v1` retain navigation within already-loaded messages. + +Jumping reads a bounded page near the selected prompt, not every earlier answer. Browsing keeps at most three server pages, supports scrolling backward and forward, and the bottom arrow returns to the live conversation. A failed read leaves the current content intact and offers retry. The navigation index is a rebuildable, bounded summary cache over the WebUI display transcript; it does not change the SQLite session schema, agent context, configuration, or chat data. On first access to a long uncached conversation, building the summaries requires reading its transcript segments in a worker thread; later accesses reuse unchanged segment summaries. + ## Sharing access The WebUI is an administration interface for one nanobot instance. Signed-in WebUI users can work with its saved topics and manage models, channels, Apps, automations, and settings within the gateway's supported capabilities. There are no per-user roles or private topic ownership boundaries. Remote package installation has an additional restriction described under [LAN Access](#lan-access); that restriction does not turn other WebUI users into read-only users. diff --git a/nanobot/webui/client_contract.py b/nanobot/webui/client_contract.py index 76326ce59..e985285cf 100644 --- a/nanobot/webui/client_contract.py +++ b/nanobot/webui/client_contract.py @@ -18,6 +18,7 @@ SUBAGENT_EVENTS_CAPABILITY = "webui.subagents.events.v1" SUBAGENT_HISTORY_CAPABILITY = "webui.subagents.history.v1" AUTOMATION_CHAT_CAPABILITY = "webui.automation-chat.v1" BINARY_ATTACHMENTS_CAPABILITY = "webui.attachments.binary.v1" +PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1" class Compatibility(TypedDict): @@ -34,7 +35,7 @@ def webui_contract() -> dict[str, object]: "capabilities": [ CORE_CAPABILITY, SUBAGENT_CAPABILITY, SUBAGENT_EVENTS_CAPABILITY, SUBAGENT_HISTORY_CAPABILITY, AUTOMATION_CHAT_CAPABILITY, - BINARY_ATTACHMENTS_CAPABILITY, + BINARY_ATTACHMENTS_CAPABILITY, PROMPT_NAVIGATION_CAPABILITY, ], } diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index a272d4291..7707fc476 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -14,8 +14,9 @@ import time import uuid from dataclasses import dataclass from datetime import datetime +from functools import lru_cache from pathlib import Path -from typing import Any, Callable, Mapping, NamedTuple, Sequence, cast +from typing import Any, Callable, Mapping, NamedTuple, Sequence, TypedDict, cast from urllib.parse import unquote, urlparse from loguru import logger @@ -817,7 +818,7 @@ def _encode_page_cursor(before_turn_ordinal: int) -> str: return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") -def _decode_page_cursor(value: str | None) -> int | None: +def decode_transcript_cursor(value: str | None) -> int | None: if not value: return None try: @@ -931,6 +932,7 @@ def _select_transcript_page( *, limit: int | None, before: str | None, + after: str | None = None, stats: TranscriptReplayStats | None = None, _manifest_rebuilt: bool = False, ) -> tuple[list[dict[str, Any]], dict[str, Any]]: @@ -940,17 +942,20 @@ def _select_transcript_page( turn_cache: dict[str, list[list[dict[str, Any]]]] = {} chunks = _chunk_turn_refs(session_key, turn_cache, stats=stats) total_turns = sum(chunk.turn_count for chunk in chunks) - before_ordinal = _decode_page_cursor(before) + before_ordinal = decode_transcript_cursor(before) upper_ordinal = total_turns if before_ordinal is None else min(before_ordinal, total_turns) + after_ordinal = decode_transcript_cursor(after) selected: list[_TranscriptTurnRef] = [] selected_event_count = 0 selected_record_count = 0 selected_bytes = 0 budget_reached = False - for chunk in reversed(chunks): + for chunk in (chunks if after_ordinal is not None else reversed(chunks)): if chunk.start_ordinal >= upper_ordinal: continue + if after_ordinal is not None and chunk.start_ordinal + chunk.turn_count <= after_ordinal: + continue local_upper = min(chunk.turn_count, upper_ordinal - chunk.start_ordinal) if local_upper <= 0: continue @@ -975,11 +980,14 @@ def _select_transcript_page( session_key, limit=limit, before=before, + after=after, stats=stats, _manifest_rebuilt=True, ) local_upper = min(local_upper, len(turns)) - for turn_index in range(local_upper - 1, -1, -1): + indices = (range(max(0, after_ordinal - chunk.start_ordinal), local_upper) + if after_ordinal is not None else range(local_upper - 1, -1, -1)) + for turn_index in indices: ordinal = chunk.start_ordinal + turn_index trace_details_safe = True turn, compacted_delta_records = _compact_completed_stream_deltas( @@ -1018,7 +1026,7 @@ def _select_transcript_page( if selected_event_count >= page_limit or budget_reached: break - selected_chronological = list(reversed(selected)) + selected_chronological = selected if after_ordinal is not None else list(reversed(selected)) lines = [ record for ref in selected_chronological @@ -1034,6 +1042,8 @@ def _select_transcript_page( return [], { "before_cursor": None, "has_more_before": False, + "after_cursor": None, + "has_more_after": False, "loaded_event_count": 0, "user_message_offset": 0, } @@ -1043,6 +1053,9 @@ def _select_transcript_page( page = { "before_cursor": _encode_page_cursor(first_ref.ordinal) if has_more else None, "has_more_before": has_more, + "after_cursor": _encode_page_cursor(selected_chronological[-1].ordinal + 1) + if selected_chronological[-1].ordinal + 1 < total_turns else None, + "has_more_after": selected_chronological[-1].ordinal + 1 < total_turns, "loaded_event_count": 0, "user_message_offset": _count_user_messages_before_ordinal( session_key, @@ -2506,6 +2519,7 @@ def build_webui_thread_response( limit: int | None = None, direction: str | None = None, before: str | None = None, + after: str | None = None, stats: TranscriptReplayStats | None = None, ) -> dict[str, Any] | None: """Return canonical transcript events for the WebUI projector.""" @@ -2514,6 +2528,7 @@ def build_webui_thread_response( session_key, limit=limit, before=before, + after=after, stats=replay_stats, ) if not lines and active_turn_started_at is None: @@ -2562,3 +2577,80 @@ def build_webui_thread_response( payload["fork_boundary_event_index"] = fork_boundary_event_index payload["page"] = page return payload + + +class PromptSummary(TypedDict): + id: str + preview: str + answerPreview: str + createdAt: int + cursor: str + turnId: str + + +@lru_cache(maxsize=64) +def _chunk_prompt_summaries(path: Path, identity: tuple[int, int, int], start: int) -> tuple[PromptSummary, ...]: + del identity # Part of the cache key, not the contents of the summary. + result: list[PromptSummary] = [] + turns = _split_transcript_turns(_read_transcript_file(path)) + for ordinal, raw_turn in enumerate(turns, start): + turn, _ = _compact_completed_stream_deltas(raw_turn) + if len(turn) > _MAX_TRANSCRIPT_PAGE_RECORDS or _records_bytes(turn) > _MAX_TRANSCRIPT_PAGE_BYTES: + turn = _trim_oversized_turn( + turn, max_records=_MAX_TRANSCRIPT_PAGE_RECORDS, + max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES, + ) + records = _records_with_replay_identity(turn, turn_ordinal=ordinal) + seen_turns: set[str] = set() + seen_messages: set[str] = set() + for index, record in enumerate(records): + if record.get("event") != "user": + continue + turn_id = str(record.get("turn_id") or "") + # Match the client projector's user-message deduplication. + provenance = normalize_session_message_ui_metadata(record.get("session_message")) + if provenance: + message_id = str(provenance["message_id"]) + if message_id in seen_messages: + continue + seen_messages.add(message_id) + elif turn_id and turn_id in seen_turns: + continue + if turn_id: + seen_turns.add(turn_id) + answer = "" + for following in records[index + 1:]: + if following.get("event") == "user": + break + if following.get("event") in {"message", "stream_end"} and not following.get("kind"): + answer = str(following.get("text") or "").strip()[:240] + if answer: + break + result.append({ + "id": _client_projection_event_id(record), + "preview": str(record.get("text") or "").strip()[:320], + "answerPreview": answer, + "createdAt": _valid_created_at_ms(record.get("created_at_ms")) or 0, + "cursor": _encode_page_cursor(ordinal), + "turnId": turn_id, + }) + return tuple(result) + + +def build_prompt_index(session_key: str) -> list[PromptSummary]: + """Read every prompt, without materializing full history or touching SQLite.""" + result: list[PromptSummary] = [] + start = 0 + chunks = [ + (_segment_file_path(session_key, entry["id"]), entry["turn_count"]) + for entry in _read_segment_manifest_entries(session_key) + ] + chunks.append((webui_transcript_path(session_key), 0)) + for path, count in chunks: + try: + stat = path.stat() + except FileNotFoundError: + continue + result.extend(_chunk_prompt_summaries(path, (stat.st_ino, stat.st_mtime_ns, stat.st_size), start)) + start += count + return result diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 8bfa3b948..837bce884 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -808,6 +808,10 @@ class GatewayHTTPHandler: # -- Session routes ----------------------------------------------------- async def _dispatch_session_routes(self, request: WsRequest, got: str) -> Response | None: + m = re.fullmatch(r"/api/sessions/([^/]+)/webui-thread/prompts", got) + if m: + return await asyncio.to_thread(self._handle_prompt_index_get, request, m.group(1)) + m = re.match(r"^/api/sessions/([^/]+)/webui-thread/trace-detail$", got) if m: return await asyncio.to_thread( @@ -1037,6 +1041,22 @@ class GatewayHTTPHandler: cleaned.append(row) return {"sessions": cleaned} + def _handle_prompt_index_get(self, request: WsRequest, key: str) -> Response: + from nanobot.webui.transcript import build_prompt_index + + if not self.check_api_token(request): + return _http_error(401, "Unauthorized") + decoded_key = _decode_api_key(key) + if decoded_key is None: + return _http_error(400, "invalid session key") + if not _is_websocket_channel_session_key(decoded_key): + return _http_error(404, "session not found") + return _http_json_response( + {"prompts": build_prompt_index(decoded_key)}, + accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"), + extra_headers=list(_NO_STORE_HEADERS), + ) + async def _handle_webui_thread_get_async(self, request: WsRequest, key: str) -> Response: diagnostics = _WebUIThreadDiagnostics() loop = asyncio.get_running_loop() @@ -1156,6 +1176,12 @@ class GatewayHTTPHandler: if direction is not None and direction not in {"latest"}: return _http_error(400, "invalid direction") before = _query_first(query, "before") + after = _query_first(query, "after") + if after is not None: + from nanobot.webui.transcript import decode_transcript_cursor + + if before is not None or direction is not None or decode_transcript_cursor(after) is None: + return _http_error(400, "invalid navigation cursor") from nanobot.session.webui_turns import ( websocket_turn_id, websocket_turn_transcript_persistence_failed, @@ -1180,6 +1206,7 @@ class GatewayHTTPHandler: active_turn_transcript_persistence_failed ), "before": before, + "after": after, "direction": direction, "gateway_instance": self.tokens.instance_id, "limit": limit, @@ -1217,6 +1244,7 @@ class GatewayHTTPHandler: limit=limit, direction=direction, before=before, + after=after, stats=diagnostics.transcript if diagnostics is not None else None, ) if diagnostics is not None: diff --git a/tests/webui/test_prompt_index.py b/tests/webui/test_prompt_index.py new file mode 100644 index 000000000..9ec9f0c87 --- /dev/null +++ b/tests/webui/test_prompt_index.py @@ -0,0 +1,89 @@ +"""Complete, lightweight navigation uses the same IDs and cursors as replay.""" + +import json +import time + +import pytest +from websockets.datastructures import Headers +from websockets.http11 import Request + +from nanobot.bus.queue import MessageBus +from nanobot.channels.websocket.runtime import WebSocketConfig +from nanobot.webui import transcript +from nanobot.webui.client_contract import webui_contract +from nanobot.webui.gateway_services import build_gateway_services + + +def test_complete_index_and_bidirectional_pages_without_loading_sqlite(tmp_path, monkeypatch): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + monkeypatch.setattr(transcript, "_ACTIVE_TRANSCRIPT_ROTATE_BYTES", 2000) + monkeypatch.setattr(transcript, "_TARGET_ACTIVE_TRANSCRIPT_BYTES", 1000) + key = "websocket:navigation" + for i in range(120): + transcript.append_transcript_object(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}"}) + transcript.append_transcript_object(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}"}) + transcript.append_transcript_object(key, {"event": "turn_end", "chat_id": "navigation", "turn_id": f"t{i}"}) + index = transcript.build_prompt_index(key) + assert len(index) == 120 + assert not (tmp_path / "sessions" / "sessions.sqlite3").exists() + latest = transcript.build_webui_thread_response(key, limit=3) + assert len(latest["events"]) < len(index) + target = index[42] + stats = transcript.TranscriptReplayStats() + page = transcript.build_webui_thread_response(key, after=target["cursor"], limit=6, stats=stats) + assert page["events"][0]["projection_id"] == target["id"] + assert page["events"][0]["text"] == "question 42" + assert page["page"]["user_message_offset"] == 42 + assert page["page"]["has_more_before"] and page["page"]["has_more_after"] + assert stats.parsed_records < 40 # Not the 360-record transcript. + newer = transcript.build_webui_thread_response(key, after=page["page"]["after_cursor"], limit=6) + older = transcript.build_webui_thread_response(key, before=newer["page"]["before_cursor"], limit=6) + assert older["events"] == page["events"] + # Warm navigation uses file metadata + cached summaries, not replay. + with monkeypatch.context() as patch: + patch.setattr(transcript, "_read_transcript_file", lambda _: (_ for _ in ()).throw(AssertionError("replayed history"))) + assert transcript.build_prompt_index(key) == index + transcript.append_transcript_object(key, {"event": "user", "chat_id": "navigation", "text": "new question"}) + assert len(transcript.build_prompt_index(key)) == 121 + + +def test_oversized_turn_keeps_matching_navigation_identity(tmp_path, monkeypatch): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 6) + key = "websocket:large-turn" + transcript.append_transcript_object(key, {"event": "user", "chat_id": "large-turn", "text": "target"}) + for i in range(20): + transcript.append_transcript_object(key, {"event": "message", "chat_id": "large-turn", "kind": "tool_hint", "text": str(i)}) + transcript.append_transcript_object(key, {"event": "message", "chat_id": "large-turn", "text": "done"}) + transcript.append_transcript_object(key, {"event": "turn_end", "chat_id": "large-turn"}) + target = transcript.build_prompt_index(key)[0] + page = transcript.build_webui_thread_response(key, after=target["cursor"], limit=40) + assert page["page"]["truncated_oversized_turn"] + assert page["events"][0]["projection_id"] == target["id"] + assert len(target["answerPreview"]) <= 240 + + +@pytest.mark.asyncio +async def test_navigation_public_routes_auth_validation_and_old_reads(tmp_path, monkeypatch): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + gateway = build_gateway_services( + config=WebSocketConfig(), bus=MessageBus(), session_manager=None, + static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json", + default_restrict_to_workspace=False, runtime_model_name=None, + runtime_surface="browser", runtime_capabilities_overrides=None, + ) + path = "/api/sessions/websocket%3Atest/webui-thread" + denied = await gateway.http._dispatch_session_routes(Request(path + "/prompts", Headers()), path + "/prompts") + assert denied.status_code == 401 + gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60 + headers = Headers([("Authorization", "Bearer test-token")]) + transcript.append_transcript_object("websocket:test", {"event": "user", "chat_id": "test", "text": "hello"}) + response = await gateway.http._dispatch_session_routes(Request(path + "/prompts", headers), path + "/prompts") + prompt = json.loads(response.body)["prompts"][0] + current = await gateway.http._dispatch_session_routes(Request(path + "?after=" + prompt["cursor"], headers), path) + legacy = await gateway.http._dispatch_session_routes(Request(path + "?direction=latest&limit=40", headers), path) + assert current.status_code == legacy.status_code == 200 + assert json.loads(current.body)["events"] == json.loads(legacy.body)["events"] + invalid = await gateway.http._dispatch_session_routes(Request(path + "?after=bad", headers), path) + assert invalid.status_code == 400 + assert "webui.prompt-navigation.v1" in webui_contract()["capabilities"] diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index 58af3ab41..d1c176983 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -2,6 +2,10 @@ import { useState } from "react"; import { createRoot } from "react-dom/client"; import { MessageBubble } from "@/components/MessageBubble"; import { ThreadMessages } from "@/components/thread/ThreadMessages"; +import { ThreadViewport } from "@/components/thread/ThreadViewport"; +import { usePromptHistory } from "@/hooks/usePromptHistory"; +import { ClientProvider } from "@/providers/ClientProvider"; +import { NanobotClient } from "@/lib/nanobot-client"; import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { TooltipProvider } from "@/components/ui/tooltip"; import { initializeI18n } from "@/i18n"; @@ -46,9 +50,24 @@ function TallDialogFixture({ placement }: { placement: "center" | "bottom" }) { } const parameters = new URLSearchParams(location.search); +const railClient = new NanobotClient({ url: "ws://127.0.0.1:8765", reconnect: false }); +const railHistory: UIMessage[] = Array.from({ length: 5 }, (_, index) => [ + { id: `u${1995 + index}`, role: "user" as const, content: `Question ${1995 + index}`, createdAt: index + 1 }, + { id: `a${1995 + index}`, role: "assistant" as const, content: "A synthetic answer.\n\n".repeat(8), createdAt: index + 1 }, +]).flat(); +function RailFixture() { + const navigation = usePromptHistory("websocket:rail", 1, railHistory); + return
+ Message nanobot} /> +
; +} await initializeI18n(); createRoot(document.getElementById("root")!).render( - {parameters.get("case") === "history" + {parameters.get("case") === "rail" + ? + : parameters.get("case") === "history" ? : } ); diff --git a/webui/browser/prompt-rail.spec.ts b/webui/browser/prompt-rail.spec.ts new file mode 100644 index 000000000..12d7bdd5c --- /dev/null +++ b/webui/browser/prompt-rail.spec.ts @@ -0,0 +1,74 @@ +import { expect, test } from "@playwright/test"; + +test("complete rail scrolls independently, jumps to unloaded history and returns to latest", async ({ page }) => { + const reads: string[] = []; + const prompts = Array.from({ length: 2000 }, (_, index) => ({ id: `u${index}`, preview: `Question ${index}`, + answerPreview: "A synthetic answer", cursor: String(index), turnId: `turn${index}`, createdAt: index + 1 })); + await page.route("**/api/sessions/**", async (route) => { + const url = new URL(route.request().url()); + if (url.pathname.endsWith("/prompts")) return route.fulfill({ json: { prompts } }); + reads.push(url.search); + const start = Number(url.searchParams.get("after") ?? Number(url.searchParams.get("before")) - 10); + await route.fulfill({ json: { schemaVersion: 3, projection: "events", events: Array.from({ length: 10 }, (_, offset) => [ + { event: "user_message", chat_id: "rail", projection_id: `u${start + offset}`, text: `Question ${start + offset}`, starts_turn: true }, + { event: "message", chat_id: "rail", projection_id: `a${start + offset}`, text: "Historical answer.\n\n".repeat(8) }, + ]).flat(), page: { before_cursor: String(start), after_cursor: String(start + 10), user_message_offset: start, + has_more_before: start > 0, has_more_after: start + 10 < 2000 } } }); + }); + await page.setViewportSize({ width: 1440, height: 900 }); + await page.goto("/browser/fixture.html?case=rail"); + const rail = page.getByTestId("prompt-rail-scroll"); + const body = page.getByTestId("thread-message-region"); + await expect(rail).toBeVisible(); + await expect.poll(() => rail.evaluate((node) => node.scrollHeight)).toBe(32024); + expect(reads).toHaveLength(0); + // Lazy markdown and content-visibility can change the scroll range during startup. + await body.evaluate(async (node) => { + let previous = -1; + let stable = 0; + for (let frame = 0; frame < 120 && stable < 12; frame++) { + await new Promise(requestAnimationFrame); + const position = node.scrollTop + node.scrollHeight; + stable = position === previous ? stable + 1 : 0; + previous = position; + } + }); + const initialBodyTop = await body.evaluate((node) => node.scrollTop); + await rail.hover(); + await page.mouse.wheel(0, -10000); + await expect.poll(() => rail.evaluate((node) => node.scrollTop)).toBeLessThan(25000); + expect(await body.evaluate((node) => node.scrollTop)).toBe(initialBodyTop); + expect(await rail.getByRole("button").count()).toBeLessThan(70); + // Keyboard navigation reaches the beginning without mounting the whole list. + await rail.getByRole("button").first().focus(); + await page.keyboard.press("Home"); + const first = rail.getByRole("button", { name: "Jump to message: Question 0", exact: true }); + await expect(first).toBeFocused(); + await first.press("Enter"); + await expect(body.getByText("Question 0", { exact: true })).toBeInViewport(); + expect(reads).toEqual(["?limit=40&after=0"]); + await expect(body.getByText("Question 1999", { exact: true })).toHaveCount(0); + for (const after of [10, 20, 30, 40]) { + await body.hover(); + await page.mouse.wheel(0, 10000); + await expect.poll(() => reads.some((query) => query === `?limit=40&after=${after}`)).toBe(true); + await expect(body.getByText(`Question ${after + 9}`, { exact: true })).toBeAttached(); + } + expect(await body.locator("[data-user-prompt-id]").count()).toBeLessThanOrEqual(30); + await body.hover(); + await page.mouse.wheel(0, -100000); + await expect.poll(() => reads.some((query) => query.startsWith("?limit=40&before="))).toBe(true); + await page.getByRole("button", { name: "Scroll to bottom" }).click(); + await expect(body.getByText("Question 1999", { exact: true })).toBeVisible(); + await expect(rail.locator('[aria-current="location"]')).toBeInViewport(); + expect(await rail.evaluate((node) => getComputedStyle(node).maskImage)).toContain("linear-gradient"); + await page.screenshot({ path: "test-results/prompt-rail-long.png" }); + // Short lists remain centered in the same viewport-relative space. + await page.goto("/browser/fixture.html?case=rail&short=1"); + const markers = page.getByTestId("prompt-rail-marker"); + await expect(markers).toHaveCount(5); + const bounds = await rail.boundingBox(); + const middle = await markers.nth(2).boundingBox(); + expect(Math.abs(middle!.y + middle!.height / 2 - (bounds!.y + bounds!.height / 2))).toBeLessThan(2); + await page.screenshot({ path: "test-results/prompt-rail-short.png" }); +}); diff --git a/webui/src/components/thread/PromptNavigator.tsx b/webui/src/components/thread/PromptNavigator.tsx index 7209ed777..afe4a5bb8 100644 --- a/webui/src/components/thread/PromptNavigator.tsx +++ b/webui/src/components/thread/PromptNavigator.tsx @@ -1,7 +1,7 @@ import { PromptNavigationIcon, } from "@/components/icons/product-icons"; -import { useMemo, useState } from "react"; +import { useMemo, useRef, useState } from "react"; import { Search } from "lucide-react"; import { useTranslation } from "react-i18next"; @@ -22,17 +22,23 @@ import { cn } from "@/lib/utils"; interface PromptNavigatorProps { messages: UIMessage[]; + prompts?: PromptAnchor[]; onJumpToPrompt: (promptId: string) => void; } +const ROW_HEIGHT = 88; + export function PromptNavigator({ messages, + prompts: suppliedPrompts, onJumpToPrompt, }: PromptNavigatorProps) { const { i18n, t } = useTranslation(); - const prompts = useMemo(() => userPromptAnchors(messages), [messages]); + const prompts = useMemo(() => suppliedPrompts ?? userPromptAnchors(messages), [suppliedPrompts, messages]); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); + const listRef = useRef(null); + const [listTop, setListTop] = useState(0); const filteredPrompts = useMemo(() => { const needle = query.trim().toLocaleLowerCase(); @@ -41,6 +47,8 @@ export function PromptNavigator({ `${prompt.label}\n${prompt.preview}`.toLocaleLowerCase().includes(needle), ); }, [prompts, query]); + const firstRow = Math.max(0, Math.floor(listTop / ROW_HEIGHT) - 2); + const lastRow = firstRow + Math.ceil(window.innerHeight / ROW_HEIGHT) + 5; if (prompts.length === 0) return null; @@ -60,7 +68,7 @@ export function PromptNavigator({ "hover:text-foreground", )} aria-label={t("thread.promptNavigator.open")} - onClick={() => setOpen(true)} + onClick={() => { setListTop(0); setOpen(true); }} > @@ -82,7 +90,11 @@ export function PromptNavigator({ /> setQuery(event.target.value)} + onChange={(event) => { + setQuery(event.target.value); + setListTop(0); + if (listRef.current) listRef.current.scrollTop = 0; + }} aria-label={t("thread.promptNavigator.search")} placeholder={t("thread.promptNavigator.search")} className="h-10 rounded-full border-border bg-background pl-9 pr-3 text-sm transition-colors" @@ -90,12 +102,29 @@ export function PromptNavigator({ -
+
setListTop(event.currentTarget.scrollTop)} + onKeyDown={(event) => { + const button = (event.target as HTMLElement).closest("[data-prompt-row]"); + if (!button || !listRef.current) return; + const index = Number(button.dataset.promptRow); + let next = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: filteredPrompts.length - 1 }[event.key]; + if (event.key === "Tab") { + if (!event.shiftKey && index === lastRow - 1) next = index + 1; + if (event.shiftKey && index === firstRow && firstRow > 0) next = index - 1; + } + if (next === undefined || next < 0 || next >= filteredPrompts.length) return; + event.preventDefault(); + listRef.current.scrollTop = next * ROW_HEIGHT; + setListTop(listRef.current.scrollTop); + requestAnimationFrame(() => listRef.current?.querySelector(`[data-prompt-row="${next}"]`)?.focus()); + }}> {filteredPrompts.length > 0 ? ( -
- {filteredPrompts.map((prompt) => ( +
+ {filteredPrompts.slice(firstRow, lastRow).map((prompt, offset) => ( void; prompt: PromptAnchor; } function PromptNavigatorRow({ + row, locale, onJump, prompt, @@ -130,14 +161,15 @@ function PromptNavigatorRow({ return ( -
- {previewVisible ? ( - <> -
- {marker.preview} -
- {marker.answerPreview ? ( -
- - {marker.answerPreview} - -
- ) : null} - - ) : null} -
- - ); - })} -
- ); -} - -function makeInert(node: HTMLDivElement | null): void { - if (node) node.inert = true; -} - -function measurePrompts( - scrollEl: HTMLElement, - anchors: PromptAnchor[], - scrollRange: number, -): MeasuredPrompt[] { - const elements = new Map(); - for (const element of scrollEl.querySelectorAll("[data-user-prompt-id]")) { - const id = element.dataset.userPromptId; - if (id !== undefined && !elements.has(id)) elements.set(id, element); - } - return anchors.flatMap((anchor) => { - const target = elements.get(anchor.id); - if (!target) return []; - const top = Math.max(0, Math.min(scrollRange, promptTop(scrollEl, target) - 16)); - return [{ - ...anchor, - top, - topPercent: clamp((top / scrollRange) * 100, 2, 98), - }]; - }); -} - -function groupPromptMarkers( - measured: MeasuredPrompt[], - railHeight: number, -): PromptMarker[] { - if (measured.length === 0) return []; - if (measured.length >= DENSE_PROMPT_THRESHOLD) { - return bucketPromptMarkers(measured, railHeight); - } - - return measured.map((prompt) => ({ - answerPreview: prompt.answerPreview, - count: 1, - ids: [prompt.id], - label: prompt.label, - preview: prompt.preview, - topPercent: prompt.topPercent, - })); -} - -function bucketPromptMarkers( - measured: MeasuredPrompt[], - railHeight: number, -): PromptMarker[] { - const bucketCount = railHeight > 0 - ? clamp( - Math.floor(railHeight / DENSE_BUCKET_HEIGHT_PX), - 1, - DENSE_BUCKET_MAX_COUNT, - ) - : DENSE_BUCKET_FALLBACK_COUNT; - const buckets = Array.from({ length: bucketCount }, () => [] as MeasuredPrompt[]); - - for (const [index, prompt] of measured.entries()) { - const bucketIndex = Math.floor((index / measured.length) * bucketCount); - buckets[bucketIndex].push(prompt); - } - - return buckets.flatMap((bucket) => { - if (bucket.length === 0) return []; - const latest = bucket[bucket.length - 1]; - const topPercent = - bucket.reduce((sum, prompt) => sum + prompt.topPercent, 0) / bucket.length; - return [{ - count: bucket.length, - ids: bucket.map((prompt) => prompt.id), - label: bucket.length === 1 - ? latest.label - : groupedPromptLabel(bucket.length, latest.label), - answerPreview: latest.answerPreview, - preview: latest.preview, - topPercent, - }]; - }); -} - -function distributeMarkerPositions(markers: PromptMarker[], railHeight: number): PromptMarker[] { - const height = railHeight > 0 ? railHeight : RAIL_FALLBACK_HEIGHT_PX; - if (markers.length <= 1) { - return markers.map((marker) => ({ ...marker, topPercent: 50 })); - } - - const availableHeight = Math.max(0, height - MARKER_STACK_GAP_PX); - const stepPx = Math.min(MARKER_STACK_GAP_PX, availableHeight / (markers.length - 1)); - const stackHeight = stepPx * (markers.length - 1); - const firstMarkerPx = (height - stackHeight) / 2; - - return markers.map((marker, index) => ({ - ...marker, - topPercent: ((firstMarkerPx + stepPx * index) / height) * 100, - })); -} - -function activePromptForScroll( - measured: MeasuredPrompt[], - scrollTop: number, -): string | null { - if (measured.length === 0) return null; - const cursor = scrollTop + 96; - let lower = 0; - let upper = measured.length - 1; - let activeIndex = 0; - while (lower <= upper) { - const middle = Math.floor((lower + upper) / 2); - if (measured[middle].top <= cursor) { - activeIndex = middle; - lower = middle + 1; - } else { - upper = middle - 1; + useEffect(() => { + if (inside.current) return; + const rail = railRef.current; + const index = anchors.findIndex((item) => item.id === activeId); + if (rail && index >= 0) { + rail.scrollTop = Math.max(0, padding + index * GAP - height / 2); + setScrollTop(rail.scrollTop); } - } - return measured[activeIndex].id; -} + }, [activeId, anchors, height, padding]); -function groupedPromptLabel(count: number, latestLabel: string): string { - return `${count} prompts, latest: ${latestLabel}`; -} + if (anchors.length < 2) return null; + const preview = focused === null ? undefined : anchors[focused]; + const moveFocus = (index: number) => { + const rail = railRef.current; + if (!rail) return; + const next = Math.max(0, Math.min(anchors.length - 1, index)); + rail.scrollTop = Math.max(0, padding + next * GAP - height / 2); + setScrollTop(rail.scrollTop); + setFocused(next); + requestAnimationFrame(() => rail.querySelector('[data-prompt-index="' + next + '"]')?.focus()); + }; -function markerWidth(hoverDistance: number | null): number { - if (hoverDistance === null) return MARKER_BASE_WIDTH_PX; - return HOVER_MARKER_WIDTHS_PX[hoverDistance] ?? MARKER_BASE_WIDTH_PX; -} - -function markerHeight(hoverDistance: number | null): number { - return hoverDistance === 0 ? 3 : 2; -} - -function railMarkerTone(hoverDistance: number | null, active: boolean): string { - if (hoverDistance === 0) { - return "bg-[#222222] opacity-100 dark:bg-white"; - } - if (hoverDistance !== null && hoverDistance < HOVER_MARKER_WIDTHS_PX.length) { - return "bg-[#d0d0d0] opacity-100 dark:bg-white/35"; - } - if (active) { - return "bg-[#6f6f6f] opacity-100 dark:bg-white/55"; - } - return "bg-[#d8d8d8] opacity-100 dark:bg-white/25"; -} - -function clamp(value: number, min: number, max: number): number { - return Math.max(min, Math.min(max, value)); + return
{ inside.current = true; }} + onPointerLeave={() => { inside.current = false; setFocused(null); }} + > +
{ setScrollTop(event.currentTarget.scrollTop); setFocused(null); }}> +
+ {anchors.slice(first, end).map((anchor, offset) => { + const index = first + offset; + const distance = focused === null ? null : Math.abs(index - focused); + const active = anchor.id === activeId; + return ; + })} +
+
+ {preview && focused !== null ?
{ if (node) node.inert = true; }} data-testid="prompt-rail-preview" + className={cn("pointer-events-none absolute left-10 z-30 w-[34rem] max-w-[calc(100vw-4rem)] -translate-y-1/2 rounded-panel px-4 py-3 text-left", floatingSurfaceElevationClassName)} + style={{ top: Math.max(60, Math.min(height - 60, padding + focused * GAP - scrollTop)) }}> +
{preview.preview || preview.label}
+ {preview.answerPreview ?
+ {preview.answerPreview} +
: null} +
: null} +
; } diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index c80e8ed58..239bbf053 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -13,6 +13,7 @@ import { parseWebLink } from "@/lib/web-preview"; import { createFilePreviewResource } from "@/lib/file-preview-resource"; import { SessionHandleLabel } from "@/components/SessionHandleLabel"; import { PromptNavigator } from "@/components/thread/PromptNavigator"; +import { usePromptHistory } from "@/hooks/usePromptHistory"; import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice"; import { RecoveryNotice } from "@/components/thread/RecoveryNotice"; import { SubagentTasksProvider } from "@/components/thread/SubagentTasks"; @@ -934,6 +935,9 @@ export function ThreadShell({ } = useNanobotStream( chatId, initial, hasPendingToolCalls, handleTurnEnd, handleStreamDetach, completedTurnIds, ); + const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]); + const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages); + const updateNavigationMessages = promptNavigation.updateMessages; const loadTraceDetails = useCallback(async (refs: string[]) => { const requestKey = historyKey; @@ -950,13 +954,15 @@ export function ThreadShell({ .then((detail) => { if (activeHistoryKeyRef.current !== requestKey) return; const projected = projectThreadEvents(detail.events); - setMessages((current) => current.flatMap((message) => { + const hydrate = (current: UIMessage[]) => current.flatMap((message) => { if (message.traceDetail?.ref !== ref) return [message]; return projected.map((replacement) => ({ ...replacement, activitySegmentId: message.activitySegmentId ?? replacement.activitySegmentId, })); - })); + }); + setMessages(hydrate); + updateNavigationMessages(hydrate); }) .catch((error: unknown) => { if (activeHistoryKeyRef.current !== requestKey) return; @@ -969,7 +975,7 @@ export function ThreadShell({ requests.push(request); } await Promise.all(requests); - }, [getToken, historyKey, setMessages]); + }, [getToken, historyKey, setMessages, updateNavigationMessages]); useEffect(() => () => { activeHistoryKeyRef.current = null; @@ -1033,7 +1039,6 @@ export function ThreadShell({ }; }, []); - const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]); const hasAppMentions = displayMessages.some((message) => message.cliApps?.length || message.mcpPresets?.length); useEffect(() => { if (hasAppMentions) requestMentionCatalogs(); @@ -2008,6 +2013,7 @@ export function ThreadShell({ const promptNavigatorAction = historyKey ? ( viewportRef.current?.jumpToUserPrompt(promptId)} /> ) : undefined; @@ -2070,6 +2076,7 @@ export function ThreadShell({ (function ThreadViewport({ - messages, + messages: latestMessages, + navigation, temporary = false, - isStreaming, + isStreaming: liveStreaming, runStartedAt = null, retryStatus = null, composer, emptyState, scrollToBottomSignal = 0, - activeTurnId = null, + activeTurnId: liveTurnId = null, activeTurnStartedHere = false, conversationKey = null, conversationReady = true, @@ -248,12 +251,12 @@ export const ThreadViewport = forwardRef(null); const viewportFrameRef = useRef(null); const contentRef = useRef(null); @@ -516,13 +529,34 @@ export const ThreadViewport = forwardRef { if (navigateToVisiblePrompt(promptId)) return; + if (navigation?.prompts.some((prompt) => prompt.id === promptId && prompt.cursor)) { + threadMotionRef.current?.takeUserControl(); + navigation.jump(promptId); + return; + } const index = messages.findIndex((message) => message.id === promptId); if (index < 0) return; threadMotionRef.current?.takeUserControl(); pendingPromptJumpRef.current = promptId; setAtBottom(false); setVisibleMessageCount((count) => Math.max(count, messages.length - index)); - }, [messages, navigateToVisiblePrompt]); + }, [messages, navigateToVisiblePrompt, navigation]); + + useLayoutEffect(() => { + if (!navigation?.target) return; + historyScrollAnchorRef.current = null; + restoreScrollAfterPrependRef.current = null; + pendingConversationScrollRef.current = false; + pendingPromptJumpRef.current = navigation.target.id; + threadMotionRef.current?.takeUserControl(); + setAtBottom(false); + const index = messages.findIndex((message) => message.id === navigation.target!.id); + setVisibleMessageCount(Math.max(INITIAL_HISTORY_WINDOW, messages.length - Math.max(0, index))); + }, [navigation?.target]); + + useEffect(() => { + if (activeTurnStartedHere && liveTurnId) navigation?.latest(); + }, [activeTurnStartedHere, liveTurnId, navigation?.latest]); const cancelAutoScroll = useCallback(() => { threadMotionRef.current?.takeUserControl(); @@ -661,16 +695,19 @@ export const ThreadViewport = forwardRef { const promptId = pendingPromptJumpRef.current; const scrollEl = scrollRef.current; if (!promptId || !scrollEl || !findPromptElement(scrollEl, promptId)) return; - pendingPromptJumpRef.current = null; - const frame = window.requestAnimationFrame(() => navigateToVisiblePrompt(promptId)); + const frame = window.requestAnimationFrame(() => { + if (pendingPromptJumpRef.current === promptId && navigateToVisiblePrompt(promptId)) { + pendingPromptJumpRef.current = null; + } + }); return () => window.cancelAnimationFrame(frame); - }, [navigateToVisiblePrompt, visibleMessages.length]); + }, [navigateToVisiblePrompt, visibleMessages, navigation?.target]); useLayoutEffect(() => { if (!pendingConversationScrollRef.current) return; @@ -768,13 +805,15 @@ export const ThreadViewport = forwardRef current === logicallyAtBottom ? current : logicallyAtBottom, ); if (owner === "user") { captureHistoryScrollAnchor(); if (allowHistoryLoad) maybeLoadEarlierFromScroll(); + if (allowHistoryLoad && distance < HISTORY_PREFETCH_MIN_PX + && historyWindow?.hasMoreAfter && !navigation?.loading && !navigation?.error) navigation?.newer(); } else if (near) { historyScrollAnchorRef.current = null; } @@ -789,6 +828,12 @@ export const ThreadViewport = forwardRef { if (!direction) return; + if (direction === "forward" && historyWindow?.hasMoreAfter + && el.scrollHeight - el.scrollTop - el.clientHeight < HISTORY_PREFETCH_MIN_PX + && !navigation?.loading && !navigation?.error) { + captureHistoryScrollAnchor(); + navigation?.newer(); + } // At the top (including a page too short to scroll), backward intent // produces no scroll event. It must still be able to reveal history. if (direction === "backward" && canLoadAtTop()) { @@ -930,6 +975,8 @@ export const ThreadViewport = forwardRef ) : null}
- {hasMessages && conversationReady && nearHistoryTop && hasMoreBefore ? ( + {navigation && (navigation.loading || navigation.error) ? ( + + ) : hasMessages && conversationReady && nearHistoryTop && hasMoreBefore ? ( ) : null} - {showScrollToBottomButton && !atBottom && ( + {showScrollToBottomButton && (!atBottom || historyWindow) && (
scrollToBottom(true, { force: true })} + onClick={() => { + if (historyWindow) { + pendingConversationScrollRef.current = true; + setVisibleMessageCount(INITIAL_HISTORY_WINDOW); + navigation?.latest(); + } else scrollToBottom(true, { force: true }); + }} className={cn( "h-8 w-8 rounded-full", "bg-background/90 backdrop-blur", diff --git a/webui/src/components/thread/promptNavigation.ts b/webui/src/components/thread/promptNavigation.ts index 967576ee7..504bffb9e 100644 --- a/webui/src/components/thread/promptNavigation.ts +++ b/webui/src/components/thread/promptNavigation.ts @@ -7,6 +7,7 @@ export interface PromptAnchor { preview: string; createdAt: number; index: number; + cursor?: string; } export function userPromptAnchors(messages: UIMessage[]): PromptAnchor[] { diff --git a/webui/src/globals.css b/webui/src/globals.css index 41f9aefe6..321aab481 100644 --- a/webui/src/globals.css +++ b/webui/src/globals.css @@ -855,6 +855,16 @@ left: 1.75rem; } + .thread-prompt-rail-scroll { + scrollbar-width: none; + -webkit-mask-image: linear-gradient(to bottom, transparent, #000 16px, #000 calc(100% - 16px), transparent); + mask-image: linear-gradient(to bottom, transparent, #000 16px, #000 calc(100% - 16px), transparent); + } + + .thread-prompt-rail-scroll::-webkit-scrollbar { + display: none; + } + @media (min-width: 768px) { .thread-prompt-rail { display: block; diff --git a/webui/src/hooks/usePromptHistory.ts b/webui/src/hooks/usePromptHistory.ts new file mode 100644 index 000000000..b15c47a80 --- /dev/null +++ b/webui/src/hooks/usePromptHistory.ts @@ -0,0 +1,162 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useClient } from "@/providers/ClientProvider"; +import { fetchPromptIndex, fetchWebuiThread } from "@/lib/api"; +import { projectThreadEvents } from "@/lib/thread-event-projection"; +import { projectWebuiThreadMessages } from "@/lib/thread-display-projection"; +import { isModelCommandText } from "@/lib/format"; +import { isSystemCommandTurnId } from "@/lib/nanobot-client"; +import type { UIMessage, WebuiThreadPersistedPayload } from "@/lib/types"; +import { type PromptAnchor, userPromptAnchors } from "@/components/thread/promptNavigation"; + +interface HistoryPage { + messages: UIMessage[]; + body: WebuiThreadPersistedPayload; +} + +export interface PromptHistoryNavigation { + prompts: PromptAnchor[]; + window: { + messages: UIMessage[]; + userMessageOffset: number; + hasMoreBefore: boolean; + hasMoreAfter: boolean; + forkBoundaryMessageCount: number | null; + } | null; + target: { id: string; sequence: number } | null; + loading: boolean; + error: string | null; + jump: (id: string) => void; + older: () => void; + newer: () => void; + latest: () => void; + retry: () => void; + updateMessages: (update: (messages: UIMessage[]) => UIMessage[]) => void; +} + +/** Browsing pages never replace the canonical latest page or live turn state. */ +export function usePromptHistory(key: string | null, version: number, messages: UIMessage[]): PromptHistoryNavigation { + const { client, getToken, webuiCapabilities } = useClient(); + const enabled = !!key && webuiCapabilities.includes("webui.prompt-navigation.v1"); + const [index, setIndex] = useState<{ key: string; prompts: PromptAnchor[] } | null>(null); + const [pages, setPages] = useState([]); + const [target, setTarget] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [indexError, setIndexError] = useState(null); + const [refresh, setRefresh] = useState(0); + const request = useRef(null); + const sequence = useRef(0); + const retry = useRef<() => void>(() => setRefresh((value) => value + 1)); + const scope = useRef({ key, client }); + const currentScope = scope.current.key === key && scope.current.client === client; + + const latest = useCallback(() => { + request.current?.abort(); + request.current = null; + setPages([]); + setTarget(null); + setLoading(false); + setError(null); + }, []); + + useEffect(() => { + scope.current = { key, client }; + latest(); + setIndex(null); + setIndexError(null); + return () => request.current?.abort(); + }, [key, client, enabled, latest]); + + useEffect(() => { + if (!enabled || !key) return; + const controller = new AbortController(); + void fetchPromptIndex(getToken(), key, controller.signal).then((items) => { + if (controller.signal.aborted) return; + setIndex({ key, prompts: items.filter((item) => !isSystemCommandTurnId(item.turnId) && !isModelCommandText(item.preview)).map((item, position) => ({ ...item, index: position, + label: item.preview.replace(/\s+/g, " ").slice(0, 80) || `Prompt ${position + 1}`, + })) }); + setIndexError(null); + }).catch((cause: unknown) => { + if (controller.signal.aborted) return; + setIndexError(cause instanceof Error ? cause.message : String(cause)); + }); + return () => controller.abort(); + }, [client, enabled, getToken, key, version, refresh]); + + const prompts = useMemo(() => { + if (!enabled) return userPromptAnchors(messages); + if (!currentScope || index?.key !== key) return []; + // Keep live prompts and legacy prompts backfilled by the history reader + // navigable, even when they have no persisted transcript cursor yet. + const ids = new Set(index.prompts.map((prompt) => prompt.id)); + const local = userPromptAnchors(messages).filter((prompt) => !ids.has(prompt.id)); + if (!local.length) return index.prompts; + return [...index.prompts, ...local].sort((a, b) => a.createdAt - b.createdAt) + .map((prompt, position) => ({ ...prompt, index: position })); + }, [currentScope, enabled, index, key, messages]); + + const updateMessages = useCallback((update: (messages: UIMessage[]) => UIMessage[]) => { + setPages((current) => current.map((page) => ({ ...page, messages: update(page.messages) }))); + }, []); + + const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string) => { + if (!key) return; + request.current?.abort(); + const controller = new AbortController(); + request.current = controller; + setLoading(true); + setError(null); + retry.current = () => { void read(cursor, direction, id); }; + try { + const body = await fetchWebuiThread(getToken(), key, { + [direction]: cursor, limit: 40, signal: controller.signal, + }); + if (controller.signal.aborted) return; + if (!body) throw new Error("History is no longer available"); + const page = { body, messages: projectWebuiThreadMessages(projectThreadEvents(body.events)) }; + if (id && !page.messages.some((message) => message.id === id)) { + setRefresh((value) => value + 1); + throw new Error("History changed; select the message again"); + } + // At most three bounded server pages, even after many navigations. + setPages((previous) => id ? [page] : direction === "before" + ? [page, ...previous].slice(0, 3) : [...previous, page].slice(-3)); + if (id) setTarget({ id, sequence: ++sequence.current }); + } catch (cause) { + if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : String(cause)); + } finally { + if (request.current === controller) { + request.current = null; + setLoading(false); + } + } + }, [getToken, key]); + + const first = pages[0]?.body.page; + const last = pages[pages.length - 1]?.body.page; + const window = useMemo(() => { + if (!currentScope || !pages.length) return null; + let count = 0; + let boundary: number | null = null; + for (const page of pages) { + const eventIndex = page.body.fork_boundary_event_index; + if (eventIndex !== undefined) boundary = count + projectWebuiThreadMessages(projectThreadEvents(page.body.events.slice(0, eventIndex))).length; + count += page.messages.length; + } + return { messages: pages.flatMap((page) => page.messages), + userMessageOffset: first?.user_message_offset ?? 0, + hasMoreBefore: first?.has_more_before === true, hasMoreAfter: last?.has_more_after === true, + forkBoundaryMessageCount: boundary }; + }, [currentScope, pages, first, last]); + + return { prompts, window, target: currentScope ? target : null, loading: currentScope && loading, + error: currentScope ? error ?? indexError : null, latest, updateMessages, + retry: () => error ? retry.current() : setRefresh((value) => value + 1), + jump: (id) => { + const prompt = prompts.find((item) => item.id === id); + if (enabled && prompt?.cursor) void read(prompt.cursor, "after", id); + }, + older: () => { if (!loading && first?.before_cursor) void read(first.before_cursor, "before"); }, + newer: () => { if (!loading && last?.after_cursor) void read(last.after_cursor, "after"); }, + }; +} diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index bdfb10307..5ca7477e1 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -21,6 +21,7 @@ import type { ModelConfigurationUpdate, NetworkSafetySettingsUpdate, PairingPayload, + PromptSummary, ProviderCreationUpdate, ProviderModelsPayload, ProviderOAuthCompletionResult, @@ -235,6 +236,7 @@ export interface FetchWebuiThreadOptions { limit?: number; direction?: "latest"; before?: string | null; + after?: string | null; signal?: AbortSignal; revision?: string; cached?: WebuiThreadPersistedPayload; @@ -418,6 +420,7 @@ export async function fetchWebuiThread( if (options?.limit !== undefined) params.set("limit", String(options.limit)); if (options?.direction) params.set("direction", options.direction); if (options?.before) params.set("before", options.before); + if (options?.after) params.set("after", options.after); const query = params.toString(); const suffix = query ? `?${query}` : ""; const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`; @@ -435,6 +438,24 @@ export async function fetchWebuiThread( return parseWebuiThreadPayload(await res.json()); } +export async function fetchPromptIndex(token: string, key: string, signal: AbortSignal): Promise { + const res = await fetchWithTimeout(`/api/sessions/${encodeURIComponent(key)}/webui-thread/prompts`, { + headers: { Authorization: `Bearer ${token}` }, credentials: "same-origin", cache: "no-store", signal, + }); + if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`); + const body: unknown = await res.json(); + if (!isRecord(body) || !Array.isArray(body.prompts)) throw new Error("Invalid prompt index"); + return body.prompts.map((item: unknown) => { + if (!isRecord(item) || typeof item.id !== "string" || typeof item.preview !== "string" + || typeof item.answerPreview !== "string" || typeof item.cursor !== "string" || typeof item.turnId !== "string" + || typeof item.createdAt !== "number" || !Number.isFinite(item.createdAt)) { + throw new Error("Invalid prompt summary"); + } + return { id: item.id, preview: item.preview, answerPreview: item.answerPreview, + cursor: item.cursor, createdAt: item.createdAt, turnId: item.turnId }; + }); +} + export async function fetchWebuiThreadTraceDetail( token: string, key: string, diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index 72772a570..6e4a9230d 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -1690,10 +1690,21 @@ export interface OutboundMcpPresetMention { interface WebuiThreadPagePayload { before_cursor?: string | null; has_more_before?: boolean; + after_cursor?: string | null; + has_more_after?: boolean; user_message_offset?: number; loaded_event_count?: number; } +export interface PromptSummary { + id: string; + preview: string; + answerPreview: string; + createdAt: number; + cursor: string; + turnId: string; +} + export interface WebuiThreadPersistedPayload { schemaVersion: number; sessionKey?: string; diff --git a/webui/src/tests/prompt-navigator.test.tsx b/webui/src/tests/prompt-navigator.test.tsx index c0ba0f2bf..f7ef0037e 100644 --- a/webui/src/tests/prompt-navigator.test.tsx +++ b/webui/src/tests/prompt-navigator.test.tsx @@ -12,6 +12,21 @@ beforeEach(() => { afterEach(() => restoreBrowserFocus()); +it("keeps a long searchable index windowed and keyboard-reachable", async () => { + const user = userEvent.setup(); + const jump = vi.fn(); + render( ({ + id: String(index), role: "user", content: `Question ${index}`, createdAt: index + 1, + }))} onJumpToPrompt={jump} />); + await user.click(screen.getByRole("button", { name: "Message navigation" })); + expect(screen.getAllByRole("button", { name: /Jump to message:/ }).length).toBeLessThan(25); + await user.tab(); + await user.keyboard("{End}"); + await waitFor(() => expect(screen.getByRole("button", { name: "Jump to message: Question 1999" })).toHaveFocus()); + await user.keyboard("{Enter}"); + expect(jump).toHaveBeenCalledWith("1999"); +}); + it("lets users type into prompt search immediately after opening it", async () => { const user = userEvent.setup(); const onJumpToPrompt = vi.fn(); diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 09d3dd1e9..6ad5b7f09 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -720,6 +720,47 @@ describe("ThreadShell", () => { expect(detailCalls).toBe(2); }); + it("hydrates deferred activity in an independently paged navigation window", async () => { + const client = makeClient(); + vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => { + const url = String(input); + if (url.includes("/prompts")) return Promise.resolve(httpJson({ prompts: [{ + id: "old-user", preview: "Old question", answerPreview: "old answer", createdAt: 1, + cursor: "0", turnId: "old-turn", + }] })); + if (url.includes("/trace-detail?")) return Promise.resolve(httpJson({ + message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{ + event: "message", chat_id: "trace-navigation", projection_id: "old-trace", kind: "progress", + text: 'exec({"command":"echo historical"})', + }], + })); + if (url.includes("after=0")) return Promise.resolve(httpJson({ + schemaVersion: 3, projection: "events", events: [ + { event: "user_message", chat_id: "trace-navigation", projection_id: "old-user", text: "Old question", starts_turn: true }, + { event: "message", chat_id: "trace-navigation", projection_id: "old-trace", kind: "progress", text: "exec(…)", + trace_detail: { ref: "1.history-aaaaaaaaaaaaaaaaaaaa", bytes: 40_000, traceCount: 1 } }, + { event: "message", chat_id: "trace-navigation", projection_id: "old-answer", text: "old answer" }, + ], page: { user_message_offset: 0, has_more_before: false, has_more_after: true, after_cursor: "1" }, + })); + if (url.includes("/webui-thread")) return Promise.resolve(httpJson({ + schemaVersion: 3, messages: [{ id: "latest-answer", role: "assistant", content: "latest answer", createdAt: 100 }], + })); + return Promise.resolve({ ok: false, status: 404, json: async () => ({}) }); + })); + render(wrap(client, {}} />, + null, "tok", ["webui.prompt-navigation.v1"])); + await screen.findByText("latest answer"); + fireEvent.click(await screen.findByRole("button", { name: "Message navigation" })); + fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Jump to message: Old question" })); + await screen.findByText("old answer"); + const menu = await openMessageActions("old answer"); + fireEvent.click(within(menu).getByRole("button", { name: /Worked/ })); + await waitFor(() => expect(document.body).toHaveTextContent("echo historical")); + fireEvent.click(screen.getByRole("button", { name: "Scroll to bottom" })); + await screen.findByText("latest answer"); + expect(screen.queryByText("old answer")).not.toBeInTheDocument(); + }); + it("ignores a deferred trace-detail failure after switching sessions", async () => { const client = makeClient(); const detailUrls: string[] = []; diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsx index af4de9d0c..c11b5f1dd 100644 --- a/webui/src/tests/thread-viewport.test.tsx +++ b/webui/src/tests/thread-viewport.test.tsx @@ -1845,9 +1845,9 @@ describe("ThreadViewport", () => { expect(screen.getByLabelText("My message navigation")).toBeInTheDocument(); const promptMarkers = screen.getAllByRole("button", { name: /Jump to message:/ }); const markerTops = promptMarkers.map((marker) => Number.parseFloat(marker.style.top)); - expect(markerTops[2]).toBeCloseTo(50); - expect(markerTops[1] - markerTops[0]).toBeCloseTo(16 / 3); - expect(markerTops[4] - markerTops[0]).toBeCloseTo(64 / 3); + expect(markerTops[2]).toBeCloseTo(150); + expect(markerTops[1] - markerTops[0]).toBeCloseTo(16); + expect(markerTops[4] - markerTops[0]).toBeCloseTo(64); const railMarkers = screen.getAllByTestId("prompt-rail-marker"); expect(railMarkers).toHaveLength(promptMarkers.length); @@ -1983,11 +1983,25 @@ describe("ThreadViewport", () => { fireEvent.click(screen.getByRole("button", { name: "Message navigation" })); const dialog = screen.getByRole("dialog"); + fireEvent.change(within(dialog).getByRole("textbox", { name: "Search messages" }), { target: { value: "message 20" } }); fireEvent.click(within(dialog).getByRole("button", { name: "Jump to message: message 20" })); await waitFor(() => expect(screen.getByText("message 20")).toBeInTheDocument()); }); + it("includes the selected prompt when one server turn exceeds the local render window", async () => { + const history: UIMessage[] = [{ id: "old-user", role: "user", content: "Large old turn", createdAt: 1 }, + ...Array.from({ length: INITIAL_HISTORY_WINDOW + 10 }, (_, index): UIMessage => ({ + id: `old-answer-${index}`, role: "assistant", content: `Answer part ${index}`, createdAt: index + 2, + }))]; + render(} + navigation={{ prompts: [], window: { messages: history, userMessageOffset: 0, + hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null }, + target: { id: "old-user", sequence: 1 }, loading: false, error: null, + jump: vi.fn(), older: vi.fn(), newer: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn() }} />); + await waitFor(() => expect(screen.getByText("Large old turn")).toBeInTheDocument()); + }); + it("renders the prompt rail for compact scroll ranges", async () => { const promptMessages = makeLongMessages(3); const { container } = render( @@ -2072,7 +2086,7 @@ describe("ThreadViewport", () => { expect(navigateTo).toHaveBeenLastCalledWith(312); }); - it("buckets dense prompt rails without rendering every prompt as a marker", async () => { + it("windows dense prompt rails while keeping each individual prompt reachable", async () => { const navigateTo = vi.spyOn(ThreadCameraController.prototype, "navigateTo") .mockReturnValue("started"); const promptMessages = makeLongMessages(100); @@ -2112,13 +2126,8 @@ describe("ThreadViewport", () => { const promptMarkers = screen.getAllByRole("button", { name: /Jump to message:/ }); expect(promptMarkers.length).toBeGreaterThan(3); expect(promptMarkers.length).toBeLessThan(100); - expect( - promptMarkers.some((marker) => - marker.getAttribute("aria-label")?.includes("prompts, latest"), - ), - ).toBe(true); - - fireEvent.click(promptMarkers[promptMarkers.length - 1]); + fireEvent.scroll(screen.getByTestId("prompt-rail-scroll"), { target: { scrollTop: 1500 } }); + fireEvent.click(screen.getByRole("button", { name: "Jump to message: message 99" })); expect(navigateTo).toHaveBeenCalledWith(8862); }); diff --git a/webui/src/tests/usePromptHistory.test.tsx b/webui/src/tests/usePromptHistory.test.tsx new file mode 100644 index 000000000..8d3d04980 --- /dev/null +++ b/webui/src/tests/usePromptHistory.test.tsx @@ -0,0 +1,100 @@ +import { act, renderHook, waitFor } from "@testing-library/react"; +import { type ReactNode } from "react"; +import { beforeEach, expect, it, vi } from "vitest"; +import { usePromptHistory } from "@/hooks/usePromptHistory"; +import * as api from "@/lib/api"; +import { NanobotClient } from "@/lib/nanobot-client"; +import { ClientProvider } from "@/providers/ClientProvider"; +import type { UIMessage, WebuiThreadPersistedPayload } from "@/lib/types"; + +vi.mock("@/lib/api", async (original) => ({ ...await original(), fetchPromptIndex: vi.fn(), fetchWebuiThread: vi.fn() })); +const index = Array.from({ length: 2000 }, (_, index) => ({ id: `u${index}`, preview: `question ${index}`, + answerPreview: "answer", createdAt: index + 1, cursor: String(index), turnId: `turn${index}` })); +const latest: UIMessage[] = [{ id: "u1999", content: "question 1999", role: "user", createdAt: 2000 }]; +function page(start: number): WebuiThreadPersistedPayload { + return { schemaVersion: 3, projection: "events", events: [ + { event: "user_message", chat_id: "a", projection_id: `u${start}`, text: `question ${start}`, starts_turn: true }, + { event: "message", chat_id: "a", projection_id: `a${start}`, text: "answer" }, + ], page: { before_cursor: String(start), after_cursor: String(start + 1), user_message_offset: start, + has_more_before: start > 0, has_more_after: start < 1999 } }; +} +function wrapper(enabled = true) { + const client = new NanobotClient({ url: "ws://localhost:8765", reconnect: false }); + return ({ children }: { children: ReactNode }) => {children}; +} +beforeEach(() => { + vi.mocked(api.fetchPromptIndex).mockReset().mockResolvedValue(index); + vi.mocked(api.fetchWebuiThread).mockReset().mockImplementation(async (_token, _key, options) => { + if (typeof options === "string") throw new Error("expected page options"); + return page(Number(options?.after ?? Number(options?.before) - 1)); + }); +}); + +it("loads the complete index without bodies, reads bounded windows and leaves live history alone", async () => { + const { result, rerender } = renderHook(({ messages }) => usePromptHistory("a", 1, messages), { + wrapper: wrapper(), initialProps: { messages: latest }, + }); + await waitFor(() => expect(result.current.prompts).toHaveLength(2000)); + expect(api.fetchWebuiThread).not.toHaveBeenCalled(); + await act(async () => result.current.jump("u500")); + expect(result.current.window?.userMessageOffset).toBe(500); + expect(result.current.target?.id).toBe("u500"); + rerender({ messages: [...latest, { id: "live", role: "assistant", content: "new output", createdAt: 2001 }] }); + expect(result.current.window?.messages).toHaveLength(2); + for (let i = 0; i < 8; i++) await act(async () => result.current.newer()); + expect(result.current.window?.messages).toHaveLength(6); + expect(result.current.window?.userMessageOffset).toBe(506); + await act(async () => result.current.older()); + expect(result.current.window?.userMessageOffset).toBe(505); + expect(result.current.window?.messages).toHaveLength(6); + expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ before: "506", limit: 40 })); + act(() => result.current.latest()); + expect(result.current.window).toBeNull(); + expect(latest).toHaveLength(1); +}); + +it("keeps the current page on failure and offers retry; superseded jumps and session reads cannot win", async () => { + const { result, rerender } = renderHook(({ key }) => usePromptHistory(key, 1, latest), { + wrapper: wrapper(), initialProps: { key: "a" }, + }); + await waitFor(() => expect(result.current.prompts).toHaveLength(2000)); + await act(async () => result.current.jump("u10")); + vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline")); + await act(async () => result.current.jump("u20")); + expect(result.current.error).toBe("offline"); + expect(result.current.window?.userMessageOffset).toBe(10); + await act(async () => result.current.retry()); + expect(result.current.window?.userMessageOffset).toBe(20); + let resolve!: (body: WebuiThreadPersistedPayload) => void; + vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + act(() => result.current.jump("u30")); + await act(async () => result.current.jump("u40")); + await act(async () => resolve(page(30))); + expect(result.current.window?.userMessageOffset).toBe(40); + vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + act(() => result.current.jump("u50")); + rerender({ key: "b" }); + await act(async () => resolve(page(50))); + expect(result.current.window).toBeNull(); + expect(result.current.loading).toBe(false); +}); + +it("does not request new endpoints from an older compatible host", () => { + const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper(false) }); + expect(result.current.prompts[0].id).toBe("u1999"); + expect(api.fetchPromptIndex).not.toHaveBeenCalled(); + expect(api.fetchWebuiThread).not.toHaveBeenCalled(); +}); + +it("keeps legacy backfilled and newly sent prompts navigable without a transcript cursor", async () => { + vi.mocked(api.fetchPromptIndex).mockResolvedValue([]); + const { result, rerender } = renderHook(({ messages }) => usePromptHistory("a", 1, messages), { + wrapper: wrapper(), initialProps: { messages: latest }, + }); + await waitFor(() => expect(result.current.prompts[0]?.id).toBe("u1999")); + rerender({ messages: [...latest, { id: "live-user", role: "user", content: "new question", createdAt: 2001 }] }); + expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["u1999", "live-user"]); + act(() => result.current.jump("live-user")); + expect(api.fetchWebuiThread).not.toHaveBeenCalled(); +});