feat(goal): /goal command & long-running tasks (long_task)
* feat(long-task): add LongTaskTool for multi-step agent tasks
Implements a meta-ReAct loop where long-running tasks are broken into
sequential subagent steps, each starting fresh with the original goal
and progress from the previous step. This prevents context drift when
agents work on complex, multi-step tasks.
- Extract build_tool_registry() from SubagentManager for reuse
- Add run_step() for synchronous subagent execution (no bus announcement)
- Add HandoffTool and CompleteTool as signal mechanisms via shared dict
- Add LongTaskTool orchestrator with simplified prompt (8 iterations/step)
- Register LongTaskTool in main agent loop
- Add _extract_handoff_from_messages fallback for robustness
* fix(long-task): add debug logging for step-level observability
* feat(long-task): major overhaul with structured handoffs, validation, and observability
- Structured HandoffState: HandoffTool now accepts files_created,
files_modified, next_step_hint, and verification fields instead of
a plain string. Progress is passed between steps as structured data.
- Completion validation round: After complete() is called, a dedicated
validator step runs to verify the claim against the original goal.
If validation fails, the task continues rather than returning
a false completion.
- Dynamic prompt system: 3 Jinja2 templates (step_start, step_middle,
step_final) selected based on step number. Final steps get tighter
budget and stronger "wrap up" guidance.
- Automatic file change tracking: Extracts write_file/edit_file events
from tool_events and injects them into the next step's context if
the subagent forgot to report them explicitly.
- Budget tracking & adaptive strategy: Cumulative token usage is tracked
across steps. Per-step tool budget drops from 8 to 4 in the last
two steps to force handoff/completion.
- Crash retry with graceful degradation: A step that crashes is retried
once. Persistent crashes terminate the task and return partial progress.
- Full observability hooks for future WebUI integration:
- set_hooks() with on_step_start, on_step_complete, on_handoff,
on_validation_started, on_validation_passed, on_validation_failed,
on_task_complete, on_task_error, and catch-all on_event.
- Readable state properties: current_step, total_steps, status,
last_handoff, cumulative_usage, goal.
- inject_correction() allows external code to send user corrections
that are injected into the next step's prompt.
- run_step() accepts optional max_iterations for dynamic budget control.
All 27 long-task tests and 11 subagent tests pass.
* test(long-task): add boundary tests and fix race conditions
- Add 7 edge-case tests: validation crash resilience, hook exception safety, mid-run correction injection, FIFO correction ordering, explicit file changes overriding auto-detection, final budget for max_steps=1, and dynamic budget switching boundaries
- Fix assertion in test_long_task_completes_after_multiple_handoffs to match exact prompt format
- Remove asyncio timing hack from test_state_exposure
- Add asyncio.sleep(0) yield in test_inject_correction_during_execution to prevent race between signal injection and step continuation
- All 34 tests passing
* fix(long-task): address code review findings
- Declare _scopes = {"core"} explicitly to prevent recursive nesting in subagent scope
- Document fragile coupling in _extract_file_changes: path extraction depends on
write_file/edit_file detail format; add debug log for unexpected formats
- Align final-template threshold (max_steps - 2) with budget switch threshold
- Eliminate hasattr(self, "_state") in _reset_state by initializing in __init__
* fix(long-task): honor final signal and file tracking
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(long-task): improve prompt structure and agent contract
- Expand LongTaskTool.description to instruct parent agent on goal
construction, return value semantics, and how to handle results.
- Expand CompleteTool.description to emphasize that the summary IS the
final answer returned to the parent agent.
- Prefix validated return value with an explicit "final answer" directive
to stop parent agent from re-running work.
- Redesign step_start.md: Step 1 is now explicitly for exploration,
planning, and skeleton-building. complete() is discouraged.
- Remove bulky payload debug logging from _emit(); add targeted
info/warning/error logs at key state transitions instead.
- Add signal_type to HandoffState for cleaner signal detection.
* test(long-task): expect wrapped completion message after validation
Align assertions with LongTaskTool final return shape on main.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(webui): turn timing strip, latency, and session-switch restore
- Agent loop: publish goal_status run/idle for WebSocket turns; attach
wall-clock latency_ms on turn_end and persisted assistant metadata.
- WebSocket channel: forward goal_status and latency fields to clients.
- NanobotClient: track goal_status started_at per chat without requiring
onChat; useNanobotStream restores run strip when returning to a chat.
- Thread UI: composer/shell viewport hooks for run duration and latency;
format helpers and i18n strings.
- MessageBubble: drop trailing StreamCursor (layout artifact vs block markdown).
- Builtin / tests: model command coverage, websocket and loop tests.
Covers multi-session UX and round-trip timing visibility for the WebUI.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: keep message-tool file attachments after canonical history hydrate
- MessageTool records per-turn media paths delivered to the active chat.
- nanobot.utils.session_attachments stages out-of-media-root files and
merges into the last assistant message before save (loop stays a thin call).
- WebUI MediaCell: use a signed URL as a real download link when present.
Fixes attachments flashing then vanishing on turn_end when paths lived
outside get_media_dir (e.g. workspace files).
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(webui): agent activity cluster, stable keys, LTR sheen labels
- Group reasoning and tool traces in AgentActivityCluster with i18n summaries
- Stabilize React list keys for activity clusters (first message id anchor)
- Replace background-clip shimmer with overlay sheen for streaming labels
- ThreadMessages/MessageList integration and locale strings
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(webui): render assistant reasoning with Markdown + deferred stream
- Use MarkdownText for ReasoningBubble body (same GFM/KaTeX path as replies)
- Apply muted/italic prose tokens so thinking stays visually subordinate
- useDeferredValue while reasoningStreaming to ease parser work during deltas
- Preload markdown chunk when trace opens; add regression test with preloaded renderer
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(webui): default-collapse agent activity cluster while Working
Outer fold no longer auto-expands during isTurnStreaming; user opens to see traces.
Header sheen and live summary unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(long_task): cumulative run history, file union, and prompt tuning
Inject cross-step summaries and merged file paths into middle/final step
templates so chains do not lose early context. Strip the last run-history
block when it duplicates Previous Progress to save tokens. Add optional
cumulative_prompt_max_chars and cumulative_step_body_max_chars parameters
with clamped defaults.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(webui): session switch keeps in-flight thread and replays buffered WS
Save the prior chat message list to the per-chat cache in a layout effect
when chatId changes (before stale writes could corrupt another chat).
Skip one post-switch layout cache tick so we do not snapshot the wrong tab.
Buffer inbound events per chat_id when no onChat subscriber is registered
(e.g. user focused another session) and drain on resubscribe up to a cap,
so streaming deltas are not lost while off-tab.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(webui): snap thread scroll to bottom on session open (no smooth glide)
Use scroll-behavior auto on the viewport, instant programmatic scroll when
following new messages and on scrollToBottomSignal. Keep smooth only for
the explicit scroll-to-bottom button.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(webui): respect manual scroll-up after opening a session
Track when the user leaves the bottom with a ref and skip ResizeObserver
and deferred bottom snaps until they return or the conversation is reset.
Remove the time-based force-bottom window that overrode atBottom.
Multi-frame scrollToBottom honours the same guard unless force (scroll button).
Co-authored-by: Cursor <cursoragent@cursor.com>
* Publish long_task UI snapshots on outbound metadata
- Add OUTBOUND_META_AGENT_UI (_agent_ui) for channel-agnostic structured state
- LongTaskTool publishes {kind: long_task, data: snapshot} on the bus with _progress
- WebSocket send forwards metadata as agent_ui for WebUI clients
- Tests for bus payload, WS frame, and progress assertions
- Fix loop progress tests: ignore _goal_status in streaming final filter and
avoid brittle outbound[-1] ordering after goal status idle messages
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: WebUI long_task activity card and resilient history merge
Add optional ui_summary to the long_task tool for one-line UI labels. Stream
long_task agent_ui into a dedicated message row with timeline, markdown peek,
and a right sheet for details. Merge canonical history after turn_end while
re-inserting long_task rows before the final assistant reply. Collapse
duplicate task_start/step_start steps in the timeline and extend i18n.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor: align long_task with thread_goal and drop orchestrator UI
- Persist sustained objectives via session metadata (long_task / complete_goal); no subagent wiring or tool-driven agent_ui payloads.\n- Remove WebUI long-task activity UI, types, and translations; history merge preserves trace replay only, with legacy long_task rows normalized to traces.\n- Drop long_task prompt templates and get_long_task_run_dir; add webui thread disk helper for gateway persistence tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(agent): thread goal runtime context, tools, and skill
- Add thread_goal_state helper and mirror active objectives into Runtime Context
- Wire loop/context/memory/events as needed for goal metadata in turns
- Expand long_task / complete_goal semantics (pivot/cancel/honest recap)
- Add always-on thread-goal SKILL.md; align /goal command prompt
- Tests for context builder and thread goal state
- Remove unused webui ChatPane component
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(thread-goal): add websocket snapshot helper and publish goal updates from long_task
Introduce thread_goal_ws_blob for bounded JSON snapshots, attach snapshots to
websocket turn_end metadata in AgentLoop, and let long_task fan-out dedicated
thread_goal frames on the websocket channel after persisting session metadata.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(channels): websocket thread_goal frames, turn_end replay, and session API scrub for subagent inject
Emit thread_goal events and optional thread_goal on turn_end; scrub persisted
subagent announce blobs on GET /api/sessions/.../messages and shorten session
list previews so WebUI does not surface full Task/Summarize scaffolding.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(webui): merge ephemeral traces per user turn when reconciling canonical history
Preserve disk/live trace rows inside the matching user–assistant segment instead
of stacking every trace before the final assistant reply (fixes inflated tool
counts after refresh or session switch).
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(webui): show assistant reply copy only on the last slice before the next user turn
Avoid duplicate copy affordances on intermediate assistant bubbles that precede
more agent activity in the same turn (tools or further assistant text).
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(webui): thread_goal stream plumbing, composer goal strip, sky glow, and client-side subagent scrub projection
Track thread_goal and turn_goal snapshots in NanobotClient, hydrate React state
from thread_goal frames and turn_end, surface objective/elapsed in the composer,
add breathing sky halo CSS while goals are active, mirror server scrub logic on
history hydration and webui_thread snapshots, and extend tests/client mocks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(channels): add Slack Socket Mode connect timeout with actionable timeout errors
Abort hung websockets.connect handshakes after a bounded wait, log REST-vs-WSS
guidance, surface RuntimeError to channel startup, and log successful WSS setup.
Co-authored-by: Cursor <cursoragent@cursor.com>
* webui: expand thread goal in composer bottom sheet
Add ChevronUp control on the run/goal strip that opens a bottom Sheet
with full ui_summary and objective. Inline preview logic in RunElapsedStrip,
add i18n strings across locales, and a composer unit test.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(webui): widen dedupeToolCallsForUi input for session API typing
fetchSessionMessages types tool_calls as unknown; accept unknown so tsc
build passes when passing message.tool_calls through.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(agent): extract WebSocket turn run status to webui_turn_helpers
* refactor(skills): rename thread-goal to long-task and document idempotent goals
* feat(skills): rename sustained-goal skill to long-goal and tighten long_task guidance
* chore: remove unused subagent/context/router helpers
* feat(session): rename sustained goal to goal_state and align WS/WebUI
- Move helpers from agent/thread_goal_state to session/goal_state:
GOAL_STATE_KEY, goal_state_runtime_lines, goal_state_ws_blob, parse_goal_state.
- Session metadata now uses "goal_state"; still read legacy "thread_goal";
long_task writes drop the legacy key after save.
- WebSocket: event/field goal_state, _goal_state_sync; turn_end carries goal_state;
accept legacy _thread_goal_sync/thread_goal inbound metadata for dispatch.
- WebUI: GoalStateWsPayload, goalState hook/client props, i18n keys goalState*.
- Runtime Context copy uses "Goal (active):" instead of "Thread goal".
* feat(agent): stream Anthropic thinking deltas and fix stream idle timeout
* refactor(webui): transcript jsonl as sole timeline source
* fix(agent): reject mismatched WS message chat_id and stream reasoning deltas
* feat(webui): hydrate sustained goal and run timer after websocket subscribe
* chore(webui,websocket): remove unused fetch helpers and legacy thread_goal WS paths
* Raise default max_tokens and context window in agent schema.
Align AgentDefaults and ModelPresetConfig with typical Claude-scale usage
(32k completion budget, 256k context window) and update migration tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(gateway): bootstrap prefers in-memory model; clarify websocket naming
* fix(websocket): websocket _handle_message passes is_dm; refresh /status test expectations
---------
Co-authored-by: chengyongru <2755839590@qq.com>
Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
chengyongru
chengyongru
parent
2d17a095dc
commit
1c2ea1aad2
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
deleteSession,
|
||||
fetchSessionMessages,
|
||||
fetchWebuiThread,
|
||||
listSessions,
|
||||
listSlashCommands,
|
||||
updateProviderSettings,
|
||||
@@ -21,13 +21,14 @@ describe("webui API helpers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("percent-encodes websocket keys when fetching session history", async () => {
|
||||
await fetchSessionMessages("tok", "websocket:chat-1");
|
||||
it("percent-encodes websocket keys when fetching webui-thread snapshot", async () => {
|
||||
await fetchWebuiThread("tok", "websocket:chat-1");
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Achat-1/messages",
|
||||
"/api/sessions/websocket%3Achat-1/webui-thread",
|
||||
expect.objectContaining({
|
||||
headers: { Authorization: "Bearer tok" },
|
||||
credentials: "same-origin",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import { fmtDateTime, relativeTime } from "@/lib/format";
|
||||
import { fmtDateTime, formatTurnLatency, relativeTime } from "@/lib/format";
|
||||
|
||||
describe("localized format helpers", () => {
|
||||
beforeEach(() => {
|
||||
@@ -61,4 +61,22 @@ describe("localized format helpers", () => {
|
||||
);
|
||||
expect(english).not.toBe(french);
|
||||
});
|
||||
|
||||
it("formats turn latency with locale-aware units", async () => {
|
||||
await setAppLanguage("en");
|
||||
const subMinute = formatTurnLatency(2400, "en");
|
||||
expect(subMinute).toBe(
|
||||
new Intl.NumberFormat("en", {
|
||||
style: "unit",
|
||||
unit: "second",
|
||||
unitDisplay: "narrow",
|
||||
maximumFractionDigits: 1,
|
||||
minimumFractionDigits: 0,
|
||||
}).format(2.4),
|
||||
);
|
||||
|
||||
const minutePlus = formatTurnLatency(90_000, "en");
|
||||
expect(minutePlus).toContain("m");
|
||||
expect(minutePlus).toContain("s");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -59,6 +59,19 @@ describe("MessageBubble", () => {
|
||||
expect(screen.queryByRole("button", { name: "Copy reply" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not show copy when showAssistantCopyAction is false", () => {
|
||||
const message: UIMessage = {
|
||||
id: "a-mid",
|
||||
role: "assistant",
|
||||
content: "Mid-turn snippet.",
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
|
||||
render(<MessageBubble message={message} showAssistantCopyAction={false} />);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Copy reply" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders trace messages as collapsible tool groups", () => {
|
||||
const message: UIMessage = {
|
||||
id: "t1",
|
||||
@@ -118,7 +131,7 @@ describe("MessageBubble", () => {
|
||||
|
||||
expect(screen.getByText("Thinking…")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Step 1: parse intent\./)).toBeInTheDocument();
|
||||
expect(container.querySelector(".reasoning-shimmer")).toBeInTheDocument();
|
||||
expect(container.querySelector(".reasoning-sheen-stripe")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /thinking/i }).parentElement).not.toHaveClass("mb-2");
|
||||
});
|
||||
|
||||
@@ -143,6 +156,27 @@ describe("MessageBubble", () => {
|
||||
expect(screen.getByText("hidden until expanded")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders reasoning body as markdown so headings are not left as raw ###", async () => {
|
||||
await import("@/components/MarkdownTextRenderer");
|
||||
const message: UIMessage = {
|
||||
id: "a-reasoning-md",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
createdAt: Date.now(),
|
||||
reasoning: "### Section title\n\nBody line.",
|
||||
reasoningStreaming: false,
|
||||
};
|
||||
|
||||
const { container } = render(<MessageBubble message={message} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /thinking/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(container.querySelector("h3")?.textContent).toBe("Section title");
|
||||
});
|
||||
expect(container.textContent).not.toContain("###");
|
||||
expect(screen.getByText("Body line.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders assistant image media as a larger generated result", () => {
|
||||
const message: UIMessage = {
|
||||
id: "a-image",
|
||||
|
||||
@@ -89,6 +89,117 @@ describe("NanobotClient", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("buffers chat events while no chat handler is registered and replays on subscribe", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
// Nobody listening yet — deltas must not be dropped (user switched away).
|
||||
lastSocket().fakeMessage({ event: "delta", chat_id: "chat-queue", text: "a" });
|
||||
lastSocket().fakeMessage({ event: "delta", chat_id: "chat-queue", text: "b" });
|
||||
const handler = vi.fn();
|
||||
client.onChat("chat-queue", handler);
|
||||
expect(handler).toHaveBeenCalledTimes(2);
|
||||
expect(handler.mock.calls[0][0]).toMatchObject({ event: "delta", text: "a" });
|
||||
expect(handler.mock.calls[1][0]).toMatchObject({ event: "delta", text: "b" });
|
||||
lastSocket().fakeMessage({ event: "delta", chat_id: "chat-queue", text: "c" });
|
||||
expect(handler).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("records goal_status run strip without an onChat subscriber", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().fakeMessage({
|
||||
event: "goal_status",
|
||||
chat_id: "chat-strip",
|
||||
status: "running",
|
||||
started_at: 12_345,
|
||||
});
|
||||
expect(client.getRunStartedAt("chat-strip")).toBe(12_345);
|
||||
lastSocket().fakeMessage({
|
||||
event: "goal_status",
|
||||
chat_id: "chat-strip",
|
||||
status: "idle",
|
||||
});
|
||||
expect(client.getRunStartedAt("chat-strip")).toBeNull();
|
||||
});
|
||||
|
||||
it("records goal_state per chat_id without an onChat subscriber", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().fakeMessage({
|
||||
event: "goal_state",
|
||||
chat_id: "chat-goal-a",
|
||||
goal_state: { active: true, ui_summary: "Docs" },
|
||||
});
|
||||
lastSocket().fakeMessage({
|
||||
event: "goal_state",
|
||||
chat_id: "chat-goal-b",
|
||||
goal_state: { active: true, objective: "Ship API" },
|
||||
});
|
||||
expect(client.getGoalState("chat-goal-a")).toEqual({ active: true, ui_summary: "Docs" });
|
||||
expect(client.getGoalState("chat-goal-b")).toEqual({
|
||||
active: true,
|
||||
objective: "Ship API",
|
||||
});
|
||||
lastSocket().fakeMessage({
|
||||
event: "goal_state",
|
||||
chat_id: "chat-goal-a",
|
||||
goal_state: { active: false },
|
||||
});
|
||||
expect(client.getGoalState("chat-goal-a")).toEqual({ active: false });
|
||||
});
|
||||
|
||||
it("records goal_state from turn_end payload when present", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().fakeMessage({
|
||||
event: "turn_end",
|
||||
chat_id: "chat-te",
|
||||
goal_state: { active: true, objective: "Long task" },
|
||||
});
|
||||
expect(client.getGoalState("chat-te")).toEqual({ active: true, objective: "Long task" });
|
||||
});
|
||||
|
||||
it("buffers after unsubscribe until the chat is subscribed again", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const h1 = vi.fn();
|
||||
const unsub = client.onChat("chat-rejoin", h1);
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().fakeMessage({ event: "delta", chat_id: "chat-rejoin", text: "live" });
|
||||
expect(h1).toHaveBeenCalledTimes(1);
|
||||
unsub();
|
||||
lastSocket().fakeMessage({ event: "delta", chat_id: "chat-rejoin", text: "queued" });
|
||||
expect(h1).toHaveBeenCalledTimes(1);
|
||||
const h2 = vi.fn();
|
||||
client.onChat("chat-rejoin", h2);
|
||||
expect(h2).toHaveBeenCalledTimes(1);
|
||||
expect(h2.mock.calls[0][0]).toMatchObject({ event: "delta", text: "queued" });
|
||||
});
|
||||
|
||||
it("dispatches runtime model updates globally", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { scrubSubagentAnnounceBody, scrubSubagentUiMessages } from "@/lib/subagent-channel-display";
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
|
||||
describe("subagent-channel-display", () => {
|
||||
it("strips Task and Summarize tail", () => {
|
||||
const raw = `[Subagent 'A' failed]
|
||||
|
||||
Task: do thing
|
||||
|
||||
Result:
|
||||
oops
|
||||
|
||||
Summarize this naturally for the user.`;
|
||||
expect(scrubSubagentAnnounceBody(raw)).toBe("[Subagent 'A' failed]\n\noops");
|
||||
});
|
||||
|
||||
it("handles CRLF", () => {
|
||||
const raw =
|
||||
"[Subagent 'B' failed]\r\n\r\nTask: t\r\n\r\nResult:\r\nok\r\n\r\nSummarize this naturally";
|
||||
expect(scrubSubagentAnnounceBody(raw)).toContain("ok");
|
||||
expect(scrubSubagentAnnounceBody(raw)).not.toContain("Task:");
|
||||
});
|
||||
|
||||
it("scrubs matching assistant rows", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "1", role: "user", content: "hi", createdAt: 1 },
|
||||
{
|
||||
id: "2",
|
||||
role: "assistant",
|
||||
content:
|
||||
"[Subagent 'C' failed]\n\nTask: long\n\nResult:\nshort\n\nSummarize this naturally",
|
||||
createdAt: 2,
|
||||
},
|
||||
];
|
||||
const out = scrubSubagentUiMessages(messages);
|
||||
expect(out[0]).toBe(messages[0]);
|
||||
expect(out[1].content).toBe("[Subagent 'C' failed]\n\nshort");
|
||||
});
|
||||
});
|
||||
@@ -88,6 +88,50 @@ describe("ThreadComposer", () => {
|
||||
expect(screen.getByRole("button", { name: "Send message" }).className).toContain("bg-foreground");
|
||||
});
|
||||
|
||||
it("shows turn run timer when runStartedAt is set", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date((1_000 + 125) * 1000));
|
||||
|
||||
render(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
placeholder="Type your message..."
|
||||
runStartedAt={1000}
|
||||
/>,
|
||||
);
|
||||
|
||||
const status = screen.getByRole("status");
|
||||
expect(status).toHaveTextContent(/Running/);
|
||||
expect(status).toHaveTextContent(/2:05/);
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("opens a bottom sheet with full thread goal when expand is clicked", async () => {
|
||||
const longObjective =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789GoalTail";
|
||||
render(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
placeholder="Type your message..."
|
||||
goalState={{
|
||||
active: true,
|
||||
objective: longObjective,
|
||||
ui_summary: "Short summary for strip",
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show full goal" }));
|
||||
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
expect(dialog).toBeInTheDocument();
|
||||
expect(dialog).toHaveTextContent("Short summary for strip");
|
||||
expect(dialog).toHaveTextContent(longObjective);
|
||||
expect(dialog).toHaveTextContent("Summary");
|
||||
expect(dialog).toHaveTextContent("Objective");
|
||||
});
|
||||
|
||||
it("opens a slash command palette and inserts the selected command", () => {
|
||||
const onSend = vi.fn();
|
||||
render(
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { normalizeLegacyLongTaskMessages } from "@/lib/thread-display-compat";
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
|
||||
describe("normalizeLegacyLongTaskMessages", () => {
|
||||
it("maps legacy long_task rows to trace lines", () => {
|
||||
const legacy = {
|
||||
id: "x",
|
||||
role: "assistant",
|
||||
kind: "long_task",
|
||||
content: "long_task · done",
|
||||
createdAt: 1,
|
||||
} as unknown as UIMessage;
|
||||
const out = normalizeLegacyLongTaskMessages([legacy]);
|
||||
expect(out[0]!.kind).toBe("trace");
|
||||
expect(out[0]!.role).toBe("tool");
|
||||
expect(out[0]!.traces).toEqual(["long_task · done"]);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
|
||||
describe("ThreadMessages", () => {
|
||||
it("uses compact spacing between consecutive auxiliary rows", () => {
|
||||
it("groups consecutive reasoning and tool rows into one cluster before the answer", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{
|
||||
id: "r1",
|
||||
@@ -41,12 +41,52 @@ describe("ThreadMessages", () => {
|
||||
},
|
||||
];
|
||||
|
||||
const { container } = render(<ThreadMessages messages={messages} />);
|
||||
const { container } = render(
|
||||
<ThreadMessages messages={messages} isStreaming={false} />,
|
||||
);
|
||||
const rows = Array.from(container.firstElementChild?.children ?? []);
|
||||
|
||||
expect(rows[0]).not.toHaveClass("mt-2", "mt-5");
|
||||
expect(rows[1]).toHaveClass("mt-2");
|
||||
expect(rows[2]).toHaveClass("mt-2");
|
||||
expect(rows[3]).toHaveClass("mt-5");
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]).not.toHaveClass("mt-2", "mt-4", "mt-5");
|
||||
expect(rows[1]).toHaveClass("mt-4");
|
||||
});
|
||||
|
||||
it("shows copy only on the last assistant slice before the next user turn", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{
|
||||
id: "early",
|
||||
role: "assistant",
|
||||
content: "starting…",
|
||||
createdAt: 1,
|
||||
},
|
||||
{
|
||||
id: "t1",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "search()",
|
||||
traces: ["search()"],
|
||||
createdAt: 2,
|
||||
},
|
||||
{
|
||||
id: "late",
|
||||
role: "assistant",
|
||||
content: "final reply",
|
||||
createdAt: 3,
|
||||
},
|
||||
];
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
|
||||
expect(screen.getAllByRole("button", { name: "Copy reply" })).toHaveLength(1);
|
||||
expect(screen.getByText("final reply")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows copy only on the second assistant when two text slices appear before user", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "a1", role: "assistant", content: "part one", createdAt: 1 },
|
||||
{ id: "a2", role: "assistant", content: "part two", createdAt: 2 },
|
||||
];
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
expect(screen.getAllByRole("button", { name: "Copy reply" })).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,16 +4,19 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ThreadShell } from "@/components/thread/ThreadShell";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
function makeClient() {
|
||||
const errorHandlers = new Set<(err: { kind: string }) => void>();
|
||||
const chatHandlers = new Map<string, Set<(ev: import("@/lib/types").InboundEvent) => void>>();
|
||||
const sessionUpdateHandlers = new Set<(chatId: string) => void>();
|
||||
const goalStateByChatId = new Map<string, import("@/lib/types").GoalStateWsPayload>();
|
||||
return {
|
||||
status: "open" as const,
|
||||
defaultChatId: null as string | null,
|
||||
onStatus: () => () => {},
|
||||
onRuntimeModelUpdate: () => () => {},
|
||||
getRunStartedAt: () => null,
|
||||
getGoalState: (chatId: string) => goalStateByChatId.get(chatId),
|
||||
onChat: (chatId: string, handler: (ev: import("@/lib/types").InboundEvent) => void) => {
|
||||
let handlers = chatHandlers.get(chatId);
|
||||
if (!handlers) {
|
||||
@@ -41,6 +44,9 @@ function makeClient() {
|
||||
for (const h of errorHandlers) h(err);
|
||||
},
|
||||
_emitChat(chatId: string, ev: import("@/lib/types").InboundEvent) {
|
||||
if (ev.event === "goal_state") {
|
||||
goalStateByChatId.set(chatId, ev.goal_state);
|
||||
}
|
||||
for (const h of chatHandlers.get(chatId) ?? []) h(ev);
|
||||
},
|
||||
_emitSessionUpdate(chatId: string) {
|
||||
@@ -77,6 +83,20 @@ function session(chatId: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function transcriptFromSimpleMessages(
|
||||
rows: Array<{ role: "user" | "assistant"; content: string }>,
|
||||
): { schemaVersion: number; messages: UIMessage[] } {
|
||||
return {
|
||||
schemaVersion: 3,
|
||||
messages: rows.map((m, i) => ({
|
||||
id: `m-${i}`,
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
createdAt: 1000 + i,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function httpJson(body: unknown) {
|
||||
return {
|
||||
ok: true,
|
||||
@@ -358,16 +378,13 @@ describe("ThreadShell", () => {
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("websocket%3Achat-a/messages")) {
|
||||
return httpJson({
|
||||
key: "websocket:chat-a",
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
messages: [
|
||||
if (url.includes("websocket%3Achat-a/webui-thread")) {
|
||||
return httpJson(
|
||||
transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "old question" },
|
||||
{ role: "assistant", content: "old answer" },
|
||||
],
|
||||
});
|
||||
]),
|
||||
);
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
@@ -509,15 +526,8 @@ describe("ThreadShell", () => {
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("websocket%3Achat-a/messages")) {
|
||||
return httpJson({
|
||||
key: "websocket:chat-a",
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
// Simulate a stale history response that has not persisted the
|
||||
// just-received assistant reply yet.
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
});
|
||||
if (url.includes("websocket%3Achat-a/webui-thread")) {
|
||||
return httpJson(transcriptFromSimpleMessages([{ role: "user", content: "hello" }]));
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
@@ -590,19 +600,18 @@ describe("ThreadShell", () => {
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("websocket%3Achat-a/messages")) {
|
||||
if (url.includes("websocket%3Achat-a/webui-thread")) {
|
||||
historyCalls += 1;
|
||||
return httpJson({
|
||||
key: "websocket:chat-a",
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
messages: historyCalls === 1
|
||||
? [{ role: "user", content: "question" }]
|
||||
: [
|
||||
{ role: "user", content: "question" },
|
||||
{ role: "assistant", content: "canonical markdown answer" },
|
||||
],
|
||||
});
|
||||
return httpJson(
|
||||
transcriptFromSimpleMessages(
|
||||
historyCalls === 1
|
||||
? [{ role: "user", content: "question" }]
|
||||
: [
|
||||
{ role: "user", content: "question" },
|
||||
{ role: "assistant", content: "canonical markdown answer" },
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
@@ -650,16 +659,13 @@ describe("ThreadShell", () => {
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("websocket%3Achat-a/messages")) {
|
||||
return httpJson({
|
||||
key: "websocket:chat-a",
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
messages: [
|
||||
if (url.includes("websocket%3Achat-a/webui-thread")) {
|
||||
return httpJson(
|
||||
transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "question" },
|
||||
{ role: "assistant", content: "loaded answer" },
|
||||
],
|
||||
});
|
||||
]),
|
||||
);
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
@@ -703,7 +709,7 @@ describe("ThreadShell", () => {
|
||||
await waitFor(() =>
|
||||
expect(scrollIntoView).toHaveBeenCalledWith({
|
||||
block: "end",
|
||||
behavior: "smooth",
|
||||
behavior: "auto",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
@@ -879,17 +885,14 @@ describe("ThreadShell", () => {
|
||||
"fetch",
|
||||
vi.fn((input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("websocket%3Achat-a/messages")) {
|
||||
if (url.includes("websocket%3Achat-a/webui-thread")) {
|
||||
return Promise.resolve(
|
||||
httpJson({
|
||||
key: "websocket:chat-a",
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
messages: [{ role: "assistant", content: "from chat a" }],
|
||||
}),
|
||||
httpJson(
|
||||
transcriptFromSimpleMessages([{ role: "assistant", content: "from chat a" }]),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (url.includes("websocket%3Achat-b/messages")) {
|
||||
if (url.includes("websocket%3Achat-b/webui-thread")) {
|
||||
return new Promise((resolve) => {
|
||||
resolveChatB = resolve;
|
||||
});
|
||||
@@ -937,12 +940,7 @@ describe("ThreadShell", () => {
|
||||
|
||||
await act(async () => {
|
||||
resolveChatB?.(
|
||||
httpJson({
|
||||
key: "websocket:chat-b",
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
messages: [{ role: "assistant", content: "from chat b" }],
|
||||
}),
|
||||
httpJson(transcriptFromSimpleMessages([{ role: "assistant", content: "from chat b" }])),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -154,7 +154,7 @@ describe("ThreadViewport", () => {
|
||||
await waitFor(() =>
|
||||
expect(scrollIntoView).toHaveBeenCalledWith({
|
||||
block: "end",
|
||||
behavior: "smooth",
|
||||
behavior: "auto",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
|
||||
@@ -3,19 +3,48 @@ import type { ReactNode } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { useNanobotStream } from "@/hooks/useNanobotStream";
|
||||
import type { InboundEvent } from "@/lib/types";
|
||||
import type { InboundEvent, GoalStateWsPayload } from "@/lib/types";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
|
||||
const EMPTY_MESSAGES: import("@/lib/types").UIMessage[] = [];
|
||||
|
||||
function fakeClient() {
|
||||
const handlers = new Map<string, Set<(ev: InboundEvent) => void>>();
|
||||
const runStartedAtByChatId = new Map<string, number>();
|
||||
const goalStateByChatId = new Map<string, GoalStateWsPayload>();
|
||||
|
||||
function recordGoalStatusForRunStrip(chatId: string, ev: InboundEvent) {
|
||||
if (ev.event !== "goal_status") return;
|
||||
if (ev.status === "running" && typeof ev.started_at === "number") {
|
||||
runStartedAtByChatId.set(chatId, ev.started_at);
|
||||
} else {
|
||||
runStartedAtByChatId.delete(chatId);
|
||||
}
|
||||
}
|
||||
|
||||
function recordGoalStateSnapshot(chatId: string, ev: InboundEvent) {
|
||||
if (ev.event === "goal_state") {
|
||||
goalStateByChatId.set(chatId, ev.goal_state);
|
||||
return;
|
||||
}
|
||||
if (ev.event === "turn_end" && ev.goal_state != null && typeof ev.goal_state === "object") {
|
||||
goalStateByChatId.set(chatId, ev.goal_state);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
client: {
|
||||
status: "open" as const,
|
||||
defaultChatId: null as string | null,
|
||||
onStatus: () => () => {},
|
||||
onError: () => () => {},
|
||||
getRunStartedAt(chatId: string) {
|
||||
const v = runStartedAtByChatId.get(chatId);
|
||||
return v === undefined ? null : v;
|
||||
},
|
||||
getGoalState(chatId: string) {
|
||||
return goalStateByChatId.get(chatId);
|
||||
},
|
||||
onChat(chatId: string, h: (ev: InboundEvent) => void) {
|
||||
let set = handlers.get(chatId);
|
||||
if (!set) {
|
||||
@@ -33,6 +62,8 @@ function fakeClient() {
|
||||
updateUrl: vi.fn(),
|
||||
},
|
||||
emit(chatId: string, ev: InboundEvent) {
|
||||
recordGoalStatusForRunStrip(chatId, ev);
|
||||
recordGoalStateSnapshot(chatId, ev);
|
||||
const set = handlers.get(chatId);
|
||||
set?.forEach((h) => h(ev));
|
||||
},
|
||||
@@ -113,6 +144,28 @@ describe("useNanobotStream", () => {
|
||||
expect(result.current.messages[1].kind).toBeUndefined();
|
||||
});
|
||||
|
||||
it("treats progress with arbitrary agent_ui like ordinary trace text", () => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(() => useNanobotStream("chat-au", EMPTY_MESSAGES), {
|
||||
wrapper: wrap(fake.client),
|
||||
});
|
||||
act(() => {
|
||||
fake.emit("chat-au", {
|
||||
event: "message",
|
||||
chat_id: "chat-au",
|
||||
text: "progress · panel tick",
|
||||
kind: "progress",
|
||||
agent_ui: {
|
||||
kind: "panel",
|
||||
data: { version: 1, event: "tick", id: "x1" },
|
||||
},
|
||||
});
|
||||
});
|
||||
expect(result.current.messages).toHaveLength(1);
|
||||
expect(result.current.messages[0].kind).toBe("trace");
|
||||
expect(result.current.messages[0].content).toContain("panel tick");
|
||||
});
|
||||
|
||||
it("renders live tool traces from structured tool events", () => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(() => useNanobotStream("chat-tool-events", EMPTY_MESSAGES), {
|
||||
@@ -656,4 +709,137 @@ describe("useNanobotStream", () => {
|
||||
expect(onTurnEnd).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stamps latency on the last assistant bubble from turn_end", () => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(() => useNanobotStream("chat-lat", EMPTY_MESSAGES), {
|
||||
wrapper: wrap(fake.client),
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-lat", {
|
||||
event: "delta",
|
||||
chat_id: "chat-lat",
|
||||
text: "Hi",
|
||||
});
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-lat", {
|
||||
event: "turn_end",
|
||||
chat_id: "chat-lat",
|
||||
latency_ms: 2400,
|
||||
});
|
||||
});
|
||||
|
||||
const lastAssistant = [...result.current.messages].reverse().find((m) => m.role === "assistant");
|
||||
expect(lastAssistant?.latencyMs).toBe(2400);
|
||||
});
|
||||
|
||||
it("tracks goal_status running and clears on idle", () => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(() => useNanobotStream("chat-g", EMPTY_MESSAGES), {
|
||||
wrapper: wrap(fake.client),
|
||||
});
|
||||
|
||||
expect(result.current.runStartedAt).toBeNull();
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-g", {
|
||||
event: "goal_status",
|
||||
chat_id: "chat-g",
|
||||
status: "running",
|
||||
started_at: 1700,
|
||||
});
|
||||
});
|
||||
expect(result.current.runStartedAt).toBe(1700);
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-g", {
|
||||
event: "goal_status",
|
||||
chat_id: "chat-g",
|
||||
status: "idle",
|
||||
});
|
||||
});
|
||||
expect(result.current.runStartedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("restores runStartedAt after switching away and back when goal_status was recorded without a subscriber", () => {
|
||||
const fake = fakeClient();
|
||||
const { result, rerender } = renderHook(
|
||||
({ chatId }: { chatId: string }) => useNanobotStream(chatId, EMPTY_MESSAGES),
|
||||
{
|
||||
wrapper: wrap(fake.client),
|
||||
initialProps: { chatId: "chat-a" },
|
||||
},
|
||||
);
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-a", {
|
||||
event: "goal_status",
|
||||
chat_id: "chat-a",
|
||||
status: "running",
|
||||
started_at: 4242,
|
||||
});
|
||||
});
|
||||
expect(result.current.runStartedAt).toBe(4242);
|
||||
|
||||
rerender({ chatId: "chat-b" });
|
||||
expect(result.current.runStartedAt).toBeNull();
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-a", {
|
||||
event: "goal_status",
|
||||
chat_id: "chat-a",
|
||||
status: "running",
|
||||
started_at: 9001,
|
||||
});
|
||||
});
|
||||
|
||||
rerender({ chatId: "chat-a" });
|
||||
expect(result.current.runStartedAt).toBe(9001);
|
||||
});
|
||||
|
||||
it("tracks goal_state per chat and restores after switching sessions", () => {
|
||||
const fake = fakeClient();
|
||||
const { result, rerender } = renderHook(
|
||||
({ chatId }: { chatId: string }) => useNanobotStream(chatId, EMPTY_MESSAGES),
|
||||
{
|
||||
wrapper: wrap(fake.client),
|
||||
initialProps: { chatId: "chat-a" },
|
||||
},
|
||||
);
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-a", {
|
||||
event: "goal_state",
|
||||
chat_id: "chat-a",
|
||||
goal_state: { active: true, ui_summary: "Alpha" },
|
||||
});
|
||||
});
|
||||
expect(result.current.goalState).toEqual({ active: true, ui_summary: "Alpha" });
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-b", {
|
||||
event: "goal_state",
|
||||
chat_id: "chat-b",
|
||||
goal_state: { active: true, objective: "Beta task" },
|
||||
});
|
||||
});
|
||||
|
||||
rerender({ chatId: "chat-b" });
|
||||
expect(result.current.goalState).toEqual({ active: true, objective: "Beta task" });
|
||||
|
||||
rerender({ chatId: "chat-a" });
|
||||
expect(result.current.goalState).toEqual({ active: true, ui_summary: "Alpha" });
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-a", {
|
||||
event: "goal_state",
|
||||
chat_id: "chat-a",
|
||||
goal_state: { active: false },
|
||||
});
|
||||
});
|
||||
expect(result.current.goalState).toEqual({ active: false });
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ vi.mock("@/lib/api", async (importOriginal) => {
|
||||
...actual,
|
||||
listSessions: vi.fn(),
|
||||
deleteSession: vi.fn(),
|
||||
fetchSessionMessages: vi.fn(),
|
||||
fetchWebuiThread: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -24,6 +24,7 @@ function fakeClient() {
|
||||
onStatus: () => () => {},
|
||||
onError: () => () => {},
|
||||
onChat: () => () => {},
|
||||
getRunStartedAt: () => null,
|
||||
onSessionUpdate: (handler: (chatId: string) => void) => {
|
||||
sessionUpdateHandlers.add(handler);
|
||||
return () => sessionUpdateHandlers.delete(handler);
|
||||
@@ -57,7 +58,7 @@ describe("useSessions", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(api.listSessions).mockReset();
|
||||
vi.mocked(api.deleteSession).mockReset();
|
||||
vi.mocked(api.fetchSessionMessages).mockReset();
|
||||
vi.mocked(api.fetchWebuiThread).mockReset();
|
||||
});
|
||||
|
||||
it("removes a session from the local list after delete succeeds", async () => {
|
||||
@@ -98,14 +99,14 @@ describe("useSessions", () => {
|
||||
it("refreshes sessions when the websocket reports a session update", async () => {
|
||||
vi.mocked(api.listSessions)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
key: "websocket:chat-a",
|
||||
channel: "websocket",
|
||||
chatId: "chat-a",
|
||||
createdAt: "2026-04-16T10:00:00Z",
|
||||
updatedAt: "2026-04-16T10:00:00Z",
|
||||
preview: "",
|
||||
},
|
||||
{
|
||||
key: "websocket:chat-a",
|
||||
channel: "websocket",
|
||||
chatId: "chat-a",
|
||||
createdAt: "2026-04-16T10:00:00Z",
|
||||
updatedAt: "2026-04-16T10:00:00Z",
|
||||
preview: "",
|
||||
},
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
@@ -134,35 +135,26 @@ describe("useSessions", () => {
|
||||
expect(api.listSessions).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("hydrates media_urls from historical user turns into UIMessage.images", async () => {
|
||||
// Round-trip check for the signed-media replay: the backend emits
|
||||
// ``media_urls`` on a historical user row and the hook must surface them
|
||||
// as ``images`` so the bubble can render the preview. Assistant turns
|
||||
// carry no media_urls and should not sprout an ``images`` field.
|
||||
vi.mocked(api.fetchSessionMessages).mockResolvedValue({
|
||||
key: "websocket:chat-media",
|
||||
created_at: "2026-04-20T10:00:00Z",
|
||||
updated_at: "2026-04-20T10:05:00Z",
|
||||
it("passes through WebUI transcript user media as images and media", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
messages: [
|
||||
{
|
||||
id: "u1",
|
||||
role: "user",
|
||||
content: "what's this?",
|
||||
timestamp: "2026-04-20T10:00:00Z",
|
||||
media_urls: [
|
||||
createdAt: 1,
|
||||
images: [
|
||||
{ url: "/api/media/sig-1/payload-1", name: "snap.png" },
|
||||
{ url: "/api/media/sig-2/payload-2", name: "diag.jpg" },
|
||||
],
|
||||
media: [
|
||||
{ kind: "image", url: "/api/media/sig-1/payload-1", name: "snap.png" },
|
||||
{ kind: "image", url: "/api/media/sig-2/payload-2", name: "diag.jpg" },
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: "it's a cat",
|
||||
timestamp: "2026-04-20T10:00:01Z",
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: "follow-up without images",
|
||||
timestamp: "2026-04-20T10:01:00Z",
|
||||
},
|
||||
{ id: "a1", role: "assistant", content: "it's a cat", createdAt: 2 },
|
||||
{ id: "u2", role: "user", content: "follow-up without images", createdAt: 3 },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -187,19 +179,16 @@ describe("useSessions", () => {
|
||||
expect(third.images).toBeUndefined();
|
||||
});
|
||||
|
||||
it("hydrates historical assistant video media_urls into media attachments", async () => {
|
||||
vi.mocked(api.fetchSessionMessages).mockResolvedValue({
|
||||
key: "websocket:chat-video",
|
||||
created_at: "2026-04-20T10:00:00Z",
|
||||
updated_at: "2026-04-20T10:05:00Z",
|
||||
it("passes through assistant video media from transcript replay", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
messages: [
|
||||
{
|
||||
id: "a1",
|
||||
role: "assistant",
|
||||
content: "clip ready",
|
||||
timestamp: "2026-04-20T10:00:01Z",
|
||||
media_urls: [
|
||||
{ url: "/api/media/sig-v/payload-v", name: "clip.mp4" },
|
||||
],
|
||||
createdAt: 1,
|
||||
media: [{ kind: "video", url: "/api/media/sig-v/payload-v", name: "clip.mp4" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -210,24 +199,23 @@ describe("useSessions", () => {
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.messages[0].role).toBe("assistant");
|
||||
expect(result.current.messages[0].images).toBeUndefined();
|
||||
expect(result.current.messages[0].media).toEqual([
|
||||
expect(result.current.messages[0]!.role).toBe("assistant");
|
||||
expect(result.current.messages[0]!.images).toBeUndefined();
|
||||
expect(result.current.messages[0]!.media).toEqual([
|
||||
{ kind: "video", url: "/api/media/sig-v/payload-v", name: "clip.mp4" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("hydrates persisted assistant reasoning into the replayed message", async () => {
|
||||
vi.mocked(api.fetchSessionMessages).mockResolvedValue({
|
||||
key: "websocket:chat-reasoning",
|
||||
created_at: "2026-04-20T10:00:00Z",
|
||||
updated_at: "2026-04-20T10:05:00Z",
|
||||
it("passes through assistant reasoning from transcript replay", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
messages: [
|
||||
{
|
||||
id: "a1",
|
||||
role: "assistant",
|
||||
content: "final answer",
|
||||
timestamp: "2026-04-20T10:00:01Z",
|
||||
reasoning_content: "hidden but persisted reasoning",
|
||||
createdAt: 1,
|
||||
reasoning: "hidden but persisted reasoning",
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -239,75 +227,25 @@ describe("useSessions", () => {
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.messages).toHaveLength(1);
|
||||
expect(result.current.messages[0].role).toBe("assistant");
|
||||
expect(result.current.messages[0].content).toBe("final answer");
|
||||
expect(result.current.messages[0].reasoning).toBe("hidden but persisted reasoning");
|
||||
expect(result.current.messages[0].reasoningStreaming).toBe(false);
|
||||
expect(result.current.messages[0]!.role).toBe("assistant");
|
||||
expect(result.current.messages[0]!.content).toBe("final answer");
|
||||
expect(result.current.messages[0]!.reasoning).toBe("hidden but persisted reasoning");
|
||||
});
|
||||
|
||||
it("drops replayed assistant turns that only contain reasoning", async () => {
|
||||
vi.mocked(api.fetchSessionMessages).mockResolvedValue({
|
||||
key: "websocket:chat-empty-reasoning",
|
||||
created_at: "2026-04-20T10:00:00Z",
|
||||
updated_at: "2026-04-20T10:05:00Z",
|
||||
it("accepts transcript rows produced by the server replay reducer", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
messages: [
|
||||
{ id: "u1", role: "user", content: "research this", createdAt: 1 },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
timestamp: "2026-04-20T10:00:01Z",
|
||||
reasoning_content: "orphan reasoning",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSessionHistory("websocket:chat-empty-reasoning"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.messages).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("hydrates historical assistant tool calls into a replay trace row", async () => {
|
||||
vi.mocked(api.fetchSessionMessages).mockResolvedValue({
|
||||
key: "websocket:chat-tools",
|
||||
created_at: "2026-04-20T10:00:00Z",
|
||||
updated_at: "2026-04-20T10:05:00Z",
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: "research this",
|
||||
timestamp: "2026-04-20T10:00:00Z",
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
timestamp: "2026-04-20T10:00:01Z",
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call-1",
|
||||
type: "function",
|
||||
function: { name: "web_search", arguments: "{\"query\":\"agents\"}" },
|
||||
},
|
||||
{
|
||||
id: "call-2",
|
||||
type: "function",
|
||||
function: { name: "web_fetch", arguments: "{\"url\":\"https://example.com\"}" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "t1",
|
||||
role: "tool",
|
||||
content: "tool output that should not render directly",
|
||||
timestamp: "2026-04-20T10:00:02Z",
|
||||
tool_call_id: "call-1",
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: "summary",
|
||||
timestamp: "2026-04-20T10:00:03Z",
|
||||
kind: "trace",
|
||||
content: "web_fetch({})",
|
||||
traces: ["web_search({\"query\":\"agents\"})", "web_fetch({\"url\":\"https://example.com\"})"],
|
||||
createdAt: 2,
|
||||
},
|
||||
{ id: "a1", role: "assistant", content: "summary", createdAt: 3 },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -318,26 +256,26 @@ describe("useSessions", () => {
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.messages.map((m) => m.role)).toEqual(["user", "tool", "assistant"]);
|
||||
const trace = result.current.messages[1];
|
||||
const trace = result.current.messages[1]!;
|
||||
expect(trace.kind).toBe("trace");
|
||||
expect(trace.traces).toEqual([
|
||||
"web_search({\"query\":\"agents\"})",
|
||||
"web_fetch({\"url\":\"https://example.com\"})",
|
||||
]);
|
||||
expect(result.current.messages[2].content).toBe("summary");
|
||||
expect(result.current.messages[2]!.content).toBe("summary");
|
||||
});
|
||||
|
||||
it("flags history with trailing assistant tool calls as still pending", async () => {
|
||||
vi.mocked(api.fetchSessionMessages).mockResolvedValue({
|
||||
key: "websocket:chat-pending",
|
||||
created_at: "2026-04-20T10:00:00Z",
|
||||
updated_at: "2026-04-20T10:05:00Z",
|
||||
it("flags transcript ending with a trace row as pending", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
messages: [
|
||||
{
|
||||
role: "assistant",
|
||||
id: "t1",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "Using 2 tools",
|
||||
timestamp: "2026-04-20T10:00:01Z",
|
||||
tool_calls: [{ id: "call-1" }],
|
||||
traces: ["Using 2 tools"],
|
||||
createdAt: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -351,47 +289,11 @@ describe("useSessions", () => {
|
||||
expect(result.current.hasPendingToolCalls).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps pending when tool result rows trail assistant tool calls", async () => {
|
||||
vi.mocked(api.fetchSessionMessages).mockResolvedValue({
|
||||
key: "websocket:chat-pending-tool-result",
|
||||
created_at: "2026-04-20T10:00:00Z",
|
||||
updated_at: "2026-04-20T10:05:00Z",
|
||||
it("does not flag transcript as pending when last row is not a trace", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
messages: [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "Using 1 tool",
|
||||
timestamp: "2026-04-20T10:00:01Z",
|
||||
tool_calls: [{ id: "call-1" }],
|
||||
},
|
||||
{
|
||||
role: "tool",
|
||||
content: "tool output",
|
||||
timestamp: "2026-04-20T10:00:02Z",
|
||||
tool_call_id: "call-1",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSessionHistory("websocket:chat-pending-tool-result"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.hasPendingToolCalls).toBe(true);
|
||||
});
|
||||
|
||||
it("does not flag history as pending once the assistant turn has no tool calls", async () => {
|
||||
vi.mocked(api.fetchSessionMessages).mockResolvedValue({
|
||||
key: "websocket:chat-done",
|
||||
created_at: "2026-04-20T10:00:00Z",
|
||||
updated_at: "2026-04-20T10:05:00Z",
|
||||
messages: [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "All done",
|
||||
timestamp: "2026-04-20T10:00:01Z",
|
||||
},
|
||||
{ id: "a1", role: "assistant", content: "All done", createdAt: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -404,6 +306,19 @@ describe("useSessions", () => {
|
||||
expect(result.current.hasPendingToolCalls).toBe(false);
|
||||
});
|
||||
|
||||
it("treats missing transcript (404) as empty history", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue(null);
|
||||
|
||||
const { result } = renderHook(() => useSessionHistory("websocket:new-chat"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.messages).toEqual([]);
|
||||
expect(result.current.hasPendingToolCalls).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the session in the list when delete fails", async () => {
|
||||
vi.mocked(api.listSessions).mockResolvedValue([
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user