Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(chat): refine contextual chat UX and conversation lifecycle (#1960)

Raghav Chamadiya1c0de9c35960
diff --git a/packages/api-client/src/chat.ts b/packages/api-client/src/chat.ts
index a59078d27..93b216475 100644
--- a/packages/api-client/src/chat.ts
+++ b/packages/api-client/src/chat.ts
@@ -2,7 +2,7 @@
* Chat API module — conversation management and SSE message streaming.
*/
-import { apiGet, apiDelete, BASE_URL, buildHeaders } from "./client";
+import { apiGet, apiDelete, apiPatch, apiPost, BASE_URL, buildHeaders } from "./client";
import type { ConversationResponse, ChatMessageResponse } from "./types";
import type { ChatContext } from "@repowise-dev/types/chat";
@@ -31,6 +31,29 @@ export async function deleteConversation(
await apiDelete(`/api/repos/${repoId}/chat/conversations/${conversationId}`);
}
+export async function restoreConversation(repoId: string, conversationId: string) {
+ return apiPost<ConversationResponse>(`/api/repos/${repoId}/chat/conversations/${conversationId}/restore`);
+}
+
+export async function updateConversation(
+ repoId: string,
+ conversationId: string,
+ patch: { title?: string; pinned?: boolean },
+) {
+ return apiPatch<ConversationResponse>(`/api/repos/${repoId}/chat/conversations/${conversationId}`, patch);
+}
+
+export async function forkConversation(
+ repoId: string,
+ conversationId: string,
+ point?: { throughMessageId?: string; beforeMessageId?: string },
+) {
+ return apiPost<ConversationResponse>(`/api/repos/${repoId}/chat/conversations/${conversationId}/fork`, {
+ through_message_id: point?.throughMessageId ?? null,
+ before_message_id: point?.beforeMessageId ?? null,
+ });
+}
+
/**
* POST a chat message and return the raw Response for SSE streaming.
* The caller reads response.body as a ReadableStream.
diff --git a/packages/api-client/src/types/chat.ts b/packages/api-client/src/types/chat.ts
index be2e6463e..ee7ca9420 100644
--- a/packages/api-client/src/types/chat.ts
+++ b/packages/api-client/src/types/chat.ts
@@ -7,6 +7,7 @@ export interface ConversationResponse {
repository_id: string;
title: string;
message_count: number;
+ pinned?: boolean;
created_at: string;
updated_at: string;
}
@@ -25,6 +26,8 @@ export interface ChatMessageResponse {
summary?: string;
artifact_type?: string;
}>;
+ provider?: string;
+ model?: string;
};
created_at: string;
}
@@ -44,5 +47,5 @@ export type ChatSSEEvent =
summary: string;
artifact: { type: string; data: Record<string, unknown> };
}
- | { type: "done"; conversation_id: string; message_id: string }
+ | { type: "done"; conversation_id: string; message_id: string; user_message_id?: string; provider?: string; model?: string }
| { type: "error"; message: string };
diff --git a/packages/core/alembic/versions/0056_chat_conversation_refinement.py b/packages/core/alembic/versions/0056_chat_conversation_refinement.py
new file mode 100644
index 000000000..92f8672a3
--- /dev/null
+++ b/packages/core/alembic/versions/0056_chat_conversation_refinement.py
@@ -0,0 +1,30 @@
+"""Add pinning and recoverable deletion to chat conversations.
+
+Revision ID: 0056
+Revises: 0055
+Create Date: 2026-08-28
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "0056"
+down_revision: str | None = "0055"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column("conversations", sa.Column("pinned", sa.Boolean(), nullable=False, server_default=sa.false()))
+ op.add_column("conversations", sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True))
+ op.create_index("ix_conversations_repo_pinned_updated", "conversations", ["repository_id", "pinned", "updated_at"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_conversations_repo_pinned_updated", table_name="conversations")
+ op.drop_column("conversations", "deleted_at")
+ op.drop_column("conversations", "pinned")
diff --git a/packages/core/src/repowise/core/persistence/crud/chat.py b/packages/core/src/repowise/core/persistence/crud/chat.py
index d7fc30e5b..991936dbb 100644
--- a/packages/core/src/repowise/core/persistence/crud/chat.py
+++ b/packages/core/src/repowise/core/persistence/crud/chat.py
@@ -43,8 +43,8 @@ async def list_conversations(
) -> list[Conversation]:
result = await session.execute(
select(Conversation)
- .where(Conversation.repository_id == repository_id)
- .order_by(Conversation.updated_at.desc())
+ .where(Conversation.repository_id == repository_id, Conversation.deleted_at.is_(None))
+ .order_by(Conversation.pinned.desc(), Conversation.updated_at.desc())
.limit(limit)
)
return list(result.scalars().all())
@@ -65,11 +65,62 @@ async def delete_conversation(session: AsyncSession, conversation_id: str) -> bo
conv = await session.get(Conversation, conversation_id)
if conv is None:
return False
- await session.delete(conv)
+ conv.deleted_at = _now_utc()
await session.flush()
return True
+async def restore_conversation(session: AsyncSession, conversation_id: str) -> Conversation | None:
+ conv = await session.get(Conversation, conversation_id)
+ if conv:
+ conv.deleted_at = None
+ conv.updated_at = _now_utc()
+ await session.flush()
+ return conv
+
+
+async def set_conversation_pinned(
+ session: AsyncSession, conversation_id: str, pinned: bool
+) -> Conversation | None:
+ conv = await session.get(Conversation, conversation_id)
+ if conv:
+ conv.pinned = pinned
+ conv.updated_at = _now_utc()
+ await session.flush()
+ return conv
+
+
+async def fork_conversation(
+ session: AsyncSession,
+ conversation_id: str,
+ *,
+ through_message_id: str | None = None,
+ before_message_id: str | None = None,
+) -> Conversation | None:
+ source = await session.get(Conversation, conversation_id)
+ if source is None or source.deleted_at is not None:
+ return None
+ fork = await create_conversation(
+ session,
+ repository_id=source.repository_id,
+ title=f"Fork of {source.title}",
+ )
+ for message in await list_chat_messages(session, conversation_id):
+ if before_message_id and message.id == before_message_id:
+ break
+ clone = ChatMessage(
+ conversation_id=fork.id,
+ role=message.role,
+ content_json=message.content_json,
+ created_at=message.created_at,
+ )
+ session.add(clone)
+ if through_message_id and message.id == through_message_id:
+ break
+ await session.flush()
+ return fork
+
+
async def touch_conversation(session: AsyncSession, conversation_id: str) -> None:
"""Update the updated_at timestamp of a conversation."""
conv = await session.get(Conversation, conversation_id)
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index af0ef87e6..89e25e880 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -1040,6 +1040,8 @@ class Conversation(Base):
String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
)
title: Mapped[str] = mapped_column(Text, nullable=False, default="New conversation")
+ pinned: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
+ deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.py
index 96499dfc7..3015aa915 100644
--- a/packages/server/src/repowise/server/routers/chat.py
+++ b/packages/server/src/repowise/server/routers/chat.py
@@ -27,7 +27,9 @@ from repowise.server.provider_config import get_chat_provider_instance
from repowise.server.schemas import (
ChatMessageResponse,
ChatRequest,
+ ConversationForkRequest,
ConversationResponse,
+ ConversationUpdateRequest,
)
logger = logging.getLogger(__name__)
@@ -166,6 +168,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
async def event_stream():
conv_id = body.conversation_id
msg_id = ""
+ user_msg_id = ""
try:
# Emit retry interval
@@ -175,7 +178,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
async with get_session(factory) as session:
if conv_id:
conv = await crud.get_conversation(session, conv_id)
- if not conv or conv.repository_id != repo_id:
+ if not conv or conv.repository_id != repo_id or conv.deleted_at is not None:
# Every other failure here goes out on the ``data``
# channel carrying a ``type``, which is the only shape
# the client switches on. This one used to be an
@@ -195,12 +198,13 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
conv_id = conv.id
# Save user message
- await crud.create_chat_message(
+ user_msg = await crud.create_chat_message(
session,
conversation_id=conv_id,
role="user",
content={"text": body.message},
)
+ user_msg_id = user_msg.id
# Build message history from DB
async with get_session(factory) as session:
@@ -394,6 +398,8 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
content={
"text": final_text,
"tool_calls": tool_calls_made,
+ "provider": provider.provider_name,
+ "model": provider.model_name,
},
)
msg_id = msg.id
@@ -405,6 +411,9 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
"type": "done",
"conversation_id": conv_id,
"message_id": msg_id,
+ "user_message_id": user_msg_id,
+ "provider": provider.provider_name,
+ "model": provider.model_name,
},
)
@@ -456,7 +465,7 @@ async def get_conversation(
session=Depends(get_db_session),
):
conv = await crud.get_conversation(session, conversation_id)
- if not conv or conv.repository_id != repo_id:
+ if not conv or conv.repository_id != repo_id or conv.deleted_at is not None:
raise HTTPException(404, "Conversation not found")
messages = await crud.list_chat_messages(session, conversation_id)
@@ -479,6 +488,62 @@ async def delete_conversation(
return {"ok": True}
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/restore")
+async def restore_conversation(repo_id: str, conversation_id: str, session=Depends(get_db_session)):
+ conv = await crud.get_conversation(session, conversation_id)
+ if not conv or conv.repository_id != repo_id:
+ raise HTTPException(404, "Conversation not found")
+ restored = await crud.restore_conversation(session, conversation_id)
+ return ConversationResponse.from_orm(restored)
+
+
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}")
+async def update_conversation(
+ repo_id: str,
+ conversation_id: str,
+ body: ConversationUpdateRequest,
+ session=Depends(get_db_session),
+):
+ conv = await crud.get_conversation(session, conversation_id)
+ if not conv or conv.repository_id != repo_id or conv.deleted_at is not None:
+ raise HTTPException(404, "Conversation not found")
+ if body.title is not None:
+ title = body.title.strip()
+ if not title:
+ raise HTTPException(422, "Conversation title cannot be blank")
+ conv = await crud.update_conversation_title(session, conversation_id, title)
+ if body.pinned is not None:
+ conv = await crud.set_conversation_pinned(session, conversation_id, body.pinned)
+ return ConversationResponse.from_orm(conv)
+
+
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/fork")
+async def fork_conversation(
+ repo_id: str,
+ conversation_id: str,
+ body: ConversationForkRequest,
+ session=Depends(get_db_session),
+):
+ conv = await crud.get_conversation(session, conversation_id)
+ if not conv or conv.repository_id != repo_id or conv.deleted_at is not None:
+ raise HTTPException(404, "Conversation not found")
+ if body.through_message_id is not None and body.before_message_id is not None:
+ raise HTTPException(422, "Choose either a through or before fork point")
+ fork_point = body.through_message_id or body.before_message_id
+ if fork_point is not None:
+ messages = await crud.list_chat_messages(session, conversation_id)
+ if all(message.id != fork_point for message in messages):
+ raise HTTPException(404, "Fork point not found")
+ fork = await crud.fork_conversation(
+ session,
+ conversation_id,
+ through_message_id=body.through_message_id,
+ before_message_id=body.before_message_id,
+ )
+ count = await crud.count_chat_messages(session, fork.id)
+ return ConversationResponse.from_orm(fork, message_count=count)
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 44acc144a..e6e80b981 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -37,7 +37,9 @@ from .c4 import (
from .chat import (
ChatMessageResponse,
ChatRequest,
+ ConversationForkRequest,
ConversationResponse,
+ ConversationUpdateRequest,
)
from .code_quality import (
DeadCodeFindingResponse,
@@ -265,7 +267,9 @@ __all__ = [
"CommunitySliceNodeResponse",
"CommunitySliceResponse",
"CommunitySummaryItem",
+ "ConversationForkRequest",
"ConversationResponse",
+ "ConversationUpdateRequest",
"CoordinatorHealthResponse",
"CostGroupResponse",
"CostSummaryResponse",
diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.py
index 25dc3397d..8d2ff0960 100644
--- a/packages/server/src/repowise/server/schemas/chat.py
+++ b/packages/server/src/repowise/server/schemas/chat.py
@@ -62,6 +62,7 @@ class ConversationResponse(BaseModel):
repository_id: str
title: str
message_count: int = 0
+ pinned: bool = False
created_at: datetime
updated_at: datetime
@@ -72,11 +73,22 @@ class ConversationResponse(BaseModel):
repository_id=obj.repository_id, # type: ignore[attr-defined]
title=obj.title, # type: ignore[attr-defined]
message_count=message_count,
+ pinned=bool(getattr(obj, "pinned", False)),
created_at=obj.created_at, # type: ignore[attr-defined]
updated_at=obj.updated_at, # type: ignore[attr-defined]
)
+class ConversationUpdateRequest(BaseModel):
+ title: str | None = Field(default=None, min_length=1, max_length=200)
+ pinned: bool | None = None
+
+
+class ConversationForkRequest(BaseModel):
+ through_message_id: str | None = None
+ before_message_id: str | None = None
+
+
class ChatMessageResponse(BaseModel):
id: str
conversation_id: str
diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.ts
index 33e981104..eb4fe0d3b 100644
--- a/packages/types/src/chat.ts
+++ b/packages/types/src/chat.ts
@@ -74,6 +74,7 @@ export interface Conversation {
repository_id: string;
title: string;
message_count: number;
+ pinned?: boolean;
created_at: string;
updated_at: string;
}
@@ -94,6 +95,8 @@ export interface ChatMessage {
content: {
text?: string;
tool_calls?: ChatToolCall[];
+ provider?: string;
+ model?: string;
};
created_at: string;
}
@@ -119,6 +122,9 @@ export interface ChatUIMessage {
text: string;
toolCalls: ChatUIToolCall[];
isStreaming: boolean;
+ /** Provenance recorded on assistant responses. */
+ provider?: string;
+ model?: string;
}
// ---------------------------------------------------------------------------
@@ -444,5 +450,5 @@ export type ChatSSEEvent =
artifact: ChatArtifact;
citations?: ChatCitation[];
}
- | { type: "done"; conversation_id: string; message_id: string }
+ | { type: "done"; conversation_id: string; message_id: string; user_message_id?: string; provider?: string; model?: string }
| { type: "error"; message: string };
diff --git a/packages/ui/__tests__/chat/chat-interface.test.tsx b/packages/ui/__tests__/chat/chat-interface.test.tsx
index 2de3b5f60..4b4803e90 100644
--- a/packages/ui/__tests__/chat/chat-interface.test.tsx
+++ b/packages/ui/__tests__/chat/chat-interface.test.tsx
@@ -52,6 +52,68 @@ describe("ChatInterface shell", () => {
expect(screen.queryByText(/Ask anything about/i)).not.toBeInTheDocument();
});
+ it("does not scroll the transcript on streaming message updates", () => {
+ const scrollIntoView = vi.fn();
+ Object.defineProperty(Element.prototype, "scrollIntoView", {
+ configurable: true,
+ value: scrollIntoView,
+ });
+ const streaming = { ...ASSISTANT_MSG, isStreaming: true, text: "First" };
+ const view = render(
+ <ChatInterface
+ repoId="r1"
+ messages={[USER_MSG, streaming]}
+ isStreaming
+ onSend={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+ scrollIntoView.mockClear();
+
+ view.rerender(
+ <ChatInterface
+ repoId="r1"
+ messages={[USER_MSG, { ...streaming, text: "First second" }]}
+ isStreaming
+ onSend={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it("passes explicit page and dock density profiles to transcript turns", () => {
+ const view = render(
+ <ChatInterface
+ repoId="r1"
+ messages={[USER_MSG, ASSISTANT_MSG]}
+ isStreaming={false}
+ onSend={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("article", { name: "Repowise" })).toHaveAttribute(
+ "data-chat-density",
+ "page",
+ );
+
+ view.rerender(
+ <ChatInterface
+ variant="dock"
+ repoId="r1"
+ messages={[USER_MSG, ASSISTANT_MSG]}
+ isStreaming={false}
+ onSend={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("article", { name: "Repowise" })).toHaveAttribute(
+ "data-chat-density",
+ "dock",
+ );
+ });
+
it("invokes onSend with trimmed text when the user submits", () => {
const onSend = vi.fn();
render(
@@ -110,7 +172,7 @@ describe("ChatInterface shell", () => {
expect(onCancel).toHaveBeenCalled();
});
- it("renders modelSelectorSlot + historySlot in the active-conversation header", () => {
+ it("renders history in the header and model choice in the composer footer", () => {
render(
<ChatInterface
repoId="r1"
@@ -124,5 +186,25 @@ describe("ChatInterface shell", () => {
);
expect(screen.getByTestId("model-slot")).toBeInTheDocument();
expect(screen.getByTestId("history-slot")).toBeInTheDocument();
+ const model = screen.getByTestId("model-slot");
+ const shortcut = screen.getByText("Shift+Enter for newline");
+ expect(model.compareDocumentPosition(shortcut) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Send message" }).className).not.toContain("accent-fill");
+ });
+
+ it("announces meaningful stream transitions without announcing token deltas", () => {
+ const streaming = { ...ASSISTANT_MSG, isStreaming: true, text: "First" };
+ const view = render(
+ <ChatInterface repoId="r1" messages={[USER_MSG, ASSISTANT_MSG]} isStreaming={false} onSend={vi.fn()} onCancel={vi.fn()} />,
+ );
+ view.rerender(
+ <ChatInterface repoId="r1" messages={[USER_MSG, streaming]} isStreaming onSend={vi.fn()} onCancel={vi.fn()} />,
+ );
+ expect(screen.getByRole("status")).toHaveTextContent("Working on your answer.");
+ view.rerender(
+ <ChatInterface repoId="r1" messages={[USER_MSG, { ...ASSISTANT_MSG, text: "First second" }]} isStreaming={false} onSend={vi.fn()} onCancel={vi.fn()} />,
+ );
+ expect(screen.getByRole("status")).toHaveTextContent("Answer complete.");
+ expect(screen.getByRole("status")).not.toHaveTextContent("First second");
});
});
diff --git a/packages/ui/__tests__/chat/chat-message.test.tsx b/packages/ui/__tests__/chat/chat-message.test.tsx
index 502c02770..6d03a2b02 100644
--- a/packages/ui/__tests__/chat/chat-message.test.tsx
+++ b/packages/ui/__tests__/chat/chat-message.test.tsx
@@ -30,10 +30,14 @@ describe("ChatMessage", () => {
).toBeNull();
});
- it("renders the question above the reply's body size", () => {
+ it("renders the user on the opposite side with a neutral identity surface", () => {
render(<ChatMessage message={USER} repoId="r1" />);
+ const turn = screen.getByRole("article", { name: "You" });
+ expect(turn.className).toContain("justify-end");
+ expect(turn).toHaveAttribute("data-chat-role", "user");
+ expect(screen.getByText("You")).toBeInTheDocument();
expect(screen.getByText("Where is auth handled?").className).toContain(
- "text-lg",
+ "bg-[var(--color-bg-surface)]",
);
});
diff --git a/packages/ui/__tests__/chat/conversation-history.test.tsx b/packages/ui/__tests__/chat/conversation-history.test.tsx
index 3646d2837..378ea6427 100644
--- a/packages/ui/__tests__/chat/conversation-history.test.tsx
+++ b/packages/ui/__tests__/chat/conversation-history.test.tsx
@@ -97,4 +97,63 @@ describe("ConversationHistory shell", () => {
fireEvent.click(screen.getByRole("button", { name: /history/i }));
expect(screen.getByText(/No conversations yet/i)).toBeInTheDocument();
});
+
+ it("closes on Escape and restores focus to the history trigger", () => {
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => { callback(0); return 1; });
+ render(<ConversationHistory conversations={CONVERSATIONS} onSelect={vi.fn()} onDelete={vi.fn()} onNew={vi.fn()} />);
+ const trigger = screen.getByRole("button", { name: /history/i });
+ fireEvent.click(trigger);
+ expect(screen.getByRole("dialog", { name: "Conversation history" })).toBeInTheDocument();
+ fireEvent.keyDown(document, { key: "Escape" });
+ expect(screen.queryByRole("dialog", { name: "Conversation history" })).toBeNull();
+ expect(trigger).toHaveFocus();
+ });
+
+ it("renders grouped history as a persistent rail with management actions", () => {
+ const onPin = vi.fn();
+ const onFork = vi.fn();
+ render(
+ <ConversationHistory
+ variant="rail"
+ conversations={[{ ...CONVERSATIONS[0]!, pinned: true }, CONVERSATIONS[1]!]}
+ onSelect={vi.fn()}
+ onDelete={vi.fn()}
+ onNew={vi.fn()}
+ onRename={vi.fn()}
+ onPin={onPin}
+ onFork={onFork}
+ undoDelete={{ title: "Old chat", onUndo: vi.fn() }}
+ />,
+ );
+ expect(screen.getByRole("complementary", { name: "Conversation history" })).toBeInTheDocument();
+ expect(screen.getByText("Pinned")).toBeInTheDocument();
+ expect(screen.getByText("Auth flow review").className).toContain("overflow-wrap:anywhere");
+ fireEvent.click(screen.getByRole("button", { name: "Unpin conversation" }));
+ expect(onPin).toHaveBeenCalledWith("c1", false);
+ fireEvent.click(screen.getAllByRole("button", { name: "Fork conversation" })[0]!);
+ expect(onFork).toHaveBeenCalledWith("c1");
+ expect(screen.getByRole("button", { name: /Undo/ })).toBeInTheDocument();
+ });
+
+ it("collapses to a compact rail and remembers the preference", () => {
+ const preferenceKey = "test:history-rail";
+ window.localStorage.removeItem(preferenceKey);
+ render(
+ <ConversationHistory
+ variant="rail"
+ collapsible
+ railPreferenceKey={preferenceKey}
+ conversations={CONVERSATIONS}
+ onSelect={vi.fn()}
+ onDelete={vi.fn()}
+ onNew={vi.fn()}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Collapse conversation history" }));
+ expect(screen.getByRole("complementary", { name: "Conversation history" })).toHaveAttribute("data-collapsed", "true");
+ expect(window.localStorage.getItem(preferenceKey)).toBe("collapsed");
+ fireEvent.click(screen.getByRole("button", { name: "Expand conversation history" }));
+ expect(screen.getByRole("complementary", { name: "Conversation history" })).toHaveAttribute("data-collapsed", "false");
+ expect(window.localStorage.getItem(preferenceKey)).toBe("expanded");
+ });
});
diff --git a/packages/ui/__tests__/chat/model-selector.test.tsx b/packages/ui/__tests__/chat/model-selector.test.tsx
index b3335a741..b164328f5 100644
--- a/packages/ui/__tests__/chat/model-selector.test.tsx
+++ b/packages/ui/__tests__/chat/model-selector.test.tsx
@@ -51,7 +51,7 @@ describe("ModelSelector shell", () => {
expect(onActivate).toHaveBeenCalledWith("anthropic", "claude-sonnet-4-6");
});
- it("shows Add-key affordance for unconfigured providers", () => {
+ it("routes API-key configuration to Settings", () => {
render(
<ModelSelector
providers={PROVIDERS}
@@ -62,6 +62,29 @@ describe("ModelSelector shell", () => {
/>,
);
fireEvent.click(screen.getByText("Anthropic · claude-opus-4-7"));
- expect(screen.getByText("Add key")).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Configure in Settings" })).toHaveAttribute("href", "/settings");
+ expect(screen.queryByText("Add key")).toBeNull();
+ });
+
+ it("opens above the composer with neutral model chrome", () => {
+ render(<ModelSelector providers={PROVIDERS} activeProvider="anthropic" activeModel="claude-opus-4-7" onActivate={vi.fn()} />);
+ fireEvent.click(screen.getByText("Anthropic · claude-opus-4-7"));
+ const panel = screen.getByRole("dialog", { name: "Choose conversation model" });
+ expect(panel.className).toContain("bottom-full");
+ expect(panel.className).toContain("left-0");
+ const trigger = screen.getByRole("button", { name: "Anthropic · claude-opus-4-7" });
+ expect(trigger.className).not.toContain("accent-fill");
+ expect(screen.getByText("claude-opus-4-7").closest("button")?.className).toContain("accent-secondary");
+ });
+
+ it("closes on Escape and restores focus to the model trigger", () => {
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => { callback(0); return 1; });
+ render(<ModelSelector providers={PROVIDERS} activeProvider="anthropic" activeModel="claude-opus-4-7" onActivate={vi.fn()} />);
+ const trigger = screen.getByRole("button", { name: "Anthropic · claude-opus-4-7" });
+ fireEvent.click(trigger);
+ expect(screen.getByRole("dialog", { name: "Choose conversation model" })).toBeInTheDocument();
+ fireEvent.keyDown(document, { key: "Escape" });
+ expect(screen.queryByRole("dialog", { name: "Choose conversation model" })).toBeNull();
+ expect(trigger).toHaveFocus();
});
});
diff --git a/packages/ui/__tests__/chat/source-citations.test.tsx b/packages/ui/__tests__/chat/source-citations.test.tsx
index 1c3fb4f2b..742155d9c 100644
--- a/packages/ui/__tests__/chat/source-citations.test.tsx
+++ b/packages/ui/__tests__/chat/source-citations.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import {
SourceCitations,
extractSources,
@@ -140,4 +140,14 @@ describe("SourceCitations render", () => {
expect(pct.className).toContain("tabular-nums");
expect(pct.className).toContain("font-mono");
});
+
+ it("collapses end-of-answer sources by default and lets the reader expand them", () => {
+ const { container } = renderList();
+ const disclosure = container.querySelector("details");
+ expect(disclosure).not.toHaveAttribute("open");
+ expect(screen.getByText("Sources · 2")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByText("Sources · 2"));
+ expect(disclosure).toHaveAttribute("open");
+ });
});
diff --git a/packages/ui/__tests__/chat/tool-call-group.test.tsx b/packages/ui/__tests__/chat/tool-call-group.test.tsx
index bf5002015..b4107a273 100644
--- a/packages/ui/__tests__/chat/tool-call-group.test.tsx
+++ b/packages/ui/__tests__/chat/tool-call-group.test.tsx
@@ -15,9 +15,7 @@ function call(id: string, status: ChatUIToolCall["status"]): ChatUIToolCall {
/** Every element carrying the group shell's ground. */
function shells(container: HTMLElement) {
- return container.querySelectorAll(
- '[class*="rounded-lg"][class*="border"][class*="bg-[var(--color-bg-surface)]"]',
- );
+ return container.querySelectorAll('[data-activity-trail="true"]');
}
describe("ToolCallGroup", () => {
@@ -34,11 +32,11 @@ describe("ToolCallGroup", () => {
toolCalls={[call("a", "done"), call("b", "done"), call("c", "done")]}
/>,
);
- fireEvent.click(screen.getByRole("button", { name: /Thinking/ }));
+ fireEvent.click(screen.getByRole("button", { name: /Activity/ }));
expect(shells(container)).toHaveLength(1);
});
- it("marks a running step but not a finished one", () => {
+ it("uses one calm working orb rather than orange spinners", () => {
// Rule 10: a badge every row carries says nothing. Success is the default,
// so only work in flight gets a marker.
const { container: done } = render(
@@ -50,7 +48,9 @@ describe("ToolCallGroup", () => {
const { container: running } = render(
<ToolCallGroup toolCalls={[call("b", "running")]} />,
);
- expect(running.querySelector(".animate-spin")).not.toBeNull();
+ expect(running.querySelector(".animate-spin")).toBeNull();
+ expect(running.querySelector('[data-working-orb="true"]')).not.toBeNull();
+ expect(running.innerHTML).not.toContain("color-accent-primary");
});
it("auto-expands while a step is running and reports the step count", () => {
diff --git a/packages/ui/__tests__/chat/use-chat-draft.test.tsx b/packages/ui/__tests__/chat/use-chat-draft.test.tsx
new file mode 100644
index 000000000..4cdbb3f29
--- /dev/null
+++ b/packages/ui/__tests__/chat/use-chat-draft.test.tsx
@@ -0,0 +1,19 @@
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { useChatDraft } from "../../src/chat/use-chat-draft.js";
+
+describe("useChatDraft", () => {
+ it("restores a distinct draft for each conversation", () => {
+ localStorage.setItem("draft:c1", "first draft");
+ localStorage.setItem("draft:c2", "second draft");
+ const view = renderHook(({ keyName }) => useChatDraft(keyName), {
+ initialProps: { keyName: "draft:c1" },
+ });
+ expect(view.result.current[0]).toBe("first draft");
+ view.rerender({ keyName: "draft:c2" });
+ expect(view.result.current[0]).toBe("second draft");
+ act(() => view.result.current[1]("updated"));
+ expect(localStorage.getItem("draft:c2")).toBe("updated");
+ expect(localStorage.getItem("draft:c1")).toBe("first draft");
+ });
+});
diff --git a/packages/ui/__tests__/chat/use-chat-scroll.test.tsx b/packages/ui/__tests__/chat/use-chat-scroll.test.tsx
new file mode 100644
index 000000000..91f6bdd7d
--- /dev/null
+++ b/packages/ui/__tests__/chat/use-chat-scroll.test.tsx
@@ -0,0 +1,111 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { act, useState } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useChatScroll } from "../../src/chat/use-chat-scroll.js";
+
+function ScrollHarness() {
+ const [turns, setTurns] = useState(1);
+ const scroll = useChatScroll();
+ return (
+ <>
+ <div ref={scroll.viewportRef} data-testid="viewport">
+ <div ref={scroll.contentRef}>
+ {Array.from({ length: turns }, (_, index) => (
+ <article key={index} data-chat-role="user">Turn {index + 1}</article>
+ ))}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => {
+ scroll.revealNewTurn();
+ setTurns(2);
+ }}
+ >
+ Send
+ </button>
+ <button type="button" onClick={scroll.jumpToLatest}>Jump</button>
+ <output>{scroll.hasContentBelow ? "below" : "latest"}</output>
+ <output>{scroll.isFollowingLive ? "following" : "stable"}</output>
+ </>
+ );
+}
+
+function LateViewportHarness() {
+ const [visible, setVisible] = useState(false);
+ const scroll = useChatScroll();
+ return (
+ <>
+ {visible && <div ref={scroll.viewportRef} data-testid="late-viewport"><div ref={scroll.contentRef}>Answer</div></div>}
+ <button type="button" onClick={() => setVisible(true)}>Show transcript</button>
+ <output>{scroll.hasContentBelow ? "late-below" : "late-latest"}</output>
+ </>
+ );
+}
+
+describe("useChatScroll", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("follows only after Jump to latest and stops when the reader scrolls away", () => {
+ render(<ScrollHarness />);
+ const viewport = screen.getByTestId("viewport");
+ Object.defineProperties(viewport, {
+ clientHeight: { configurable: true, value: 300 },
+ scrollHeight: { configurable: true, value: 1000 },
+ scrollTop: { configurable: true, writable: true, value: 100 },
+ });
+
+ fireEvent.scroll(viewport);
+ expect(screen.getByText("below")).toBeInTheDocument();
+ expect(screen.getByText("stable")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Jump" }));
+ expect(viewport.scrollTop).toBe(1000);
+ expect(screen.getByText("following")).toBeInTheDocument();
+
+ viewport.scrollTop = 200;
+ fireEvent.scroll(viewport);
+ expect(screen.getByText("stable")).toBeInTheDocument();
+ expect(screen.getByText("below")).toBeInTheDocument();
+ });
+
+ it("reveals a newly sent user turn once without enabling follow mode", () => {
+ let frame: FrameRequestCallback | undefined;
+ vi.stubGlobal(
+ "requestAnimationFrame",
+ vi.fn((callback: FrameRequestCallback) => {
+ frame = callback;
+ return 1;
+ }),
+ );
+ vi.stubGlobal("cancelAnimationFrame", vi.fn());
+ render(<ScrollHarness />);
+ const viewport = screen.getByTestId("viewport");
+ Object.defineProperties(viewport, {
+ clientHeight: { configurable: true, value: 300 },
+ scrollHeight: { configurable: true, value: 1000 },
+ scrollTop: { configurable: true, writable: true, value: 0 },
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+ const secondTurn = screen.getByText("Turn 2");
+ Object.defineProperty(secondTurn, "offsetTop", { configurable: true, value: 520 });
+ act(() => frame?.(16));
+
+ expect(viewport.scrollTop).toBe(504);
+ expect(screen.getByText("stable")).toBeInTheDocument();
+ });
+
+ it("attaches scroll intent after an empty view mounts its transcript", () => {
+ render(<LateViewportHarness />);
+ fireEvent.click(screen.getByRole("button", { name: "Show transcript" }));
+ const viewport = screen.getByTestId("late-viewport");
+ Object.defineProperties(viewport, {
+ clientHeight: { configurable: true, value: 200 },
+ scrollHeight: { configurable: true, value: 800 },
+ scrollTop: { configurable: true, writable: true, value: 100 },
+ });
+ fireEvent.scroll(viewport);
+ expect(screen.getByText("late-below")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/shared/markdown.test.tsx b/packages/ui/__tests__/shared/markdown.test.tsx
index f15bc4bfb..bef057d2c 100644
--- a/packages/ui/__tests__/shared/markdown.test.tsx
+++ b/packages/ui/__tests__/shared/markdown.test.tsx
@@ -1,7 +1,10 @@
-import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
import { Markdown } from "../../src/shared/markdown.js";
+const codeToHtml = vi.hoisted(() => vi.fn(async () => '<pre class="shiki"><code><span>highlighted</span></code></pre>'));
+vi.mock("shiki", () => ({ codeToHtml }));
+
describe("Markdown", () => {
it("renders reply body at the reading scale, not chrome sizes", () => {
// Chat is a reading surface: a reply is read for minutes, so body is 16px.
@@ -58,4 +61,58 @@ describe("Markdown", () => {
expect(th!.className).toContain("font-mono");
expect(th!.className).toContain("uppercase");
});
+
+ it("contains wide tables in their own responsive content lane", () => {
+ const { container } = render(
+ <Markdown content={"| File | Hash |\n|---|---|\n| src/a.ts | abcdef |"} />,
+ );
+ const table = container.querySelector("table");
+ expect(table?.className).toContain("min-w-");
+ expect(table?.parentElement?.className).toContain("overflow-x-auto");
+ });
+
+ it("labels fenced code and exposes a copy action", () => {
+ render(<Markdown content={"```ts\nconst answer = 42\n```"} streaming />);
+ expect(screen.getByText("ts")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Copy code" })).toBeInTheDocument();
+ });
+
+ it("keeps language-less fences as copyable block code", () => {
+ const { container } = render(<Markdown content={"```\nplain output\n```"} streaming />);
+ expect(screen.getByText("text")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Copy code" })).toBeInTheDocument();
+ expect(container.querySelector("pre code")?.textContent).toBe("plain output");
+ });
+
+ it("keeps incomplete streaming fences as a safe plain-code fallback", () => {
+ const { container } = render(
+ <Markdown content={"```ts\nconst unfinished ="} streaming />,
+ );
+ expect(container.querySelector("pre code")?.textContent).toContain(
+ "const unfinished =",
+ );
+ expect(container.querySelector(".shiki")).toBeNull();
+ });
+
+ it("lazy-highlights completed code and reuses the cached result", async () => {
+ const content = "```ts\nconst cached = true\n```";
+ const first = render(<Markdown content={content} />);
+ await waitFor(() => expect(first.container.querySelector(".shiki")).not.toBeNull());
+ first.unmount();
+ const second = render(<Markdown content={content} />);
+ await waitFor(() => expect(second.container.querySelector(".shiki")).not.toBeNull());
+ expect(codeToHtml).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps streaming Mermaid as stable source until the fence is complete", () => {
+ const { container } = render(<Markdown content={"```mermaid\ngraph TD; A-->"} streaming />);
+ expect(container.querySelector("pre code")?.textContent).toContain("graph TD; A-->");
+ });
+
+ it("preserves semantic nested lists, task lists, and blockquotes", () => {
+ const { container } = render(<Markdown content={"> Note\n\n- parent\n - child\n\n- [x] done"} />);
+ expect(container.querySelector("blockquote")).not.toBeNull();
+ expect(container.querySelectorAll("ul").length).toBeGreaterThan(1);
+ expect(container.querySelector('input[type="checkbox"]')).toBeChecked();
+ });
});
diff --git a/packages/ui/src/chat/artifact-panel.tsx b/packages/ui/src/chat/artifact-panel.tsx
index 6b4ec020c..af4679237 100644
--- a/packages/ui/src/chat/artifact-panel.tsx
+++ b/packages/ui/src/chat/artifact-panel.tsx
@@ -64,7 +64,7 @@ export function ArtifactPanel({ artifacts, open, onClose }: ArtifactPanelProps)
className={cn(
"px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors",
idx === activeIdx
- ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
+ ? "border-[var(--color-border-hover)] bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
: "border-transparent text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",
)}
>
diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsx
index 96964cbc7..4f48c3e02 100644
--- a/packages/ui/src/chat/artifacts.tsx
+++ b/packages/ui/src/chat/artifacts.tsx
@@ -155,7 +155,7 @@ export function ContextRenderer({ data }: { data: ContextArtifactData }) {
const md = info.docs?.content_md ?? "";
return (
<div key={target}>
- <h3 className="text-xs font-mono text-[var(--color-accent-primary)] mb-2 break-all">
+ <h3 className="text-xs font-mono text-[var(--color-text-secondary)] mb-2 break-all">
{target}
</h3>
{md ? (
diff --git a/packages/ui/src/chat/chat-composer.tsx b/packages/ui/src/chat/chat-composer.tsx
index b316d31e9..26365013f 100644
--- a/packages/ui/src/chat/chat-composer.tsx
+++ b/packages/ui/src/chat/chat-composer.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useEffect, useRef, type RefObject } from "react";
-import { Send, StopCircle } from "lucide-react";
+import { useEffect, useRef, type ReactNode, type RefObject } from "react";
+import { ArrowUp, Square } from "lucide-react";
import { Button } from "../ui/button";
import { cn } from "../lib/cn";
@@ -18,6 +18,8 @@ export interface ChatComposerProps {
appearance?: "contained" | "bare";
textareaRef?: RefObject<HTMLTextAreaElement | null>;
className?: string;
+ /** Quiet conversation controls rendered below the input (for example model choice). */
+ footer?: ReactNode;
}
/** Shared, controlled composer used by both the page chat and floating dock. */
@@ -34,6 +36,7 @@ export function ChatComposer({
appearance = "contained",
textareaRef: forwardedRef,
className,
+ footer,
}: ChatComposerProps) {
const localRef = useRef<HTMLTextAreaElement>(null);
const textareaRef = forwardedRef ?? localRef;
@@ -55,50 +58,59 @@ export function ChatComposer({
return (
<div
className={cn(
- "flex items-end gap-2",
+ "min-w-0",
appearance === "contained"
- ? "rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-4 py-3 focus-within:border-[var(--color-accent-primary)]"
- : "border-t border-[var(--color-border-subtle)] px-0 pb-0 pt-3",
+ ? "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2.5 py-1.5 focus-within:border-[var(--color-accent-primary)]"
+ : "border-t border-[var(--color-border-subtle)] px-0 pb-0 pt-2",
disabled && "opacity-60",
- compact && appearance === "contained" && "rounded-xl px-3 py-2.5",
+ compact && appearance === "contained" && "px-2 py-1.5",
className,
)}
>
- <textarea
- ref={textareaRef}
- value={value}
- onChange={(event) => onValueChange(event.target.value)}
- onKeyDown={(event) => {
- if (event.key === "Enter" && !event.shiftKey) {
- event.preventDefault();
- void submit();
- }
- }}
- placeholder={placeholder}
- aria-label="Chat message"
- disabled={disabled}
- autoFocus={autoFocus}
- rows={1}
- className={cn(
- "min-w-0 flex-1 resize-none bg-transparent text-[15px] leading-6 text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] overflow-y-auto",
- compact ? "max-h-24" : "max-h-36",
- )}
- style={{ scrollbarWidth: "none" }}
- />
- <Button
- size="icon"
- className="h-8 w-8 shrink-0 rounded-xl"
- onClick={isStreaming ? onCancel : () => void submit()}
- disabled={(!value.trim() && !isStreaming) || disabled}
- aria-label={isStreaming ? "Stop generation" : "Send message"}
- title={isStreaming ? "Stop generation" : "Send message"}
- >
- {isStreaming ? (
- <StopCircle className="h-4 w-4" />
- ) : (
- <Send className="h-4 w-4" />
- )}
- </Button>
+ <div className="flex items-end gap-2">
+ <textarea
+ ref={textareaRef}
+ value={value}
+ onChange={(event) => onValueChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ void submit();
+ }
+ }}
+ placeholder={placeholder}
+ aria-label="Chat message"
+ disabled={disabled}
+ autoFocus={autoFocus}
+ rows={1}
+ className={cn(
+ "min-w-0 flex-1 resize-none bg-transparent px-1 py-0.5 text-[15px] leading-6 text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] overflow-y-auto",
+ compact ? "max-h-24" : "max-h-36",
+ )}
+ style={{ scrollbarWidth: "none" }}
+ />
+ <Button
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "h-9 w-9 shrink-0 rounded-md border border-[var(--color-border-default)]",
+ "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]",
+ "hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-overlay)]",
+ )}
+ onClick={isStreaming ? onCancel : () => void submit()}
+ disabled={(!value.trim() && !isStreaming) || disabled}
+ aria-label={isStreaming ? "Stop generation" : "Send message"}
+ title={isStreaming ? "Stop generation" : "Send message"}
+ >
+ {isStreaming ? <Square className="h-3.5 w-3.5 fill-current" /> : <ArrowUp className="h-4 w-4" />}
+ </Button>
+ </div>
+ {footer && (
+ <div className="mt-0.5 flex min-h-6 items-center justify-between gap-2 px-0.5 text-xs text-[var(--color-text-tertiary)]">
+ <div className="min-w-0">{footer}</div>
+ <span className="ml-auto hidden sm:inline">Shift+Enter for newline</span>
+ </div>
+ )}
</div>
);
}
diff --git a/packages/ui/src/chat/chat-dock.tsx b/packages/ui/src/chat/chat-dock.tsx
index 2027bb66a..d62237105 100644
--- a/packages/ui/src/chat/chat-dock.tsx
+++ b/packages/ui/src/chat/chat-dock.tsx
@@ -256,7 +256,7 @@ export function ChatDock({
}
className="group flex min-h-11 items-center gap-2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1.5 pl-1.5 pr-3 shadow-[var(--shadow-md)] outline-none transition-[border-color,box-shadow,transform] hover:border-[var(--color-border-hover)] hover:shadow-[var(--shadow-lg)] focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] motion-safe:hover:-translate-y-px motion-reduce:transition-none"
>
- <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--color-accent-muted)]">
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--color-bg-elevated)]">
<BrandMark
darkSrc={owlDarkSrc}
lightSrc={owlLightSrc}
@@ -274,7 +274,7 @@ export function ChatDock({
"block h-1.5 w-1.5 rounded-full",
isStreaming
? "bg-[var(--color-text-tertiary)] motion-safe:animate-pulse"
- : "bg-[var(--color-accent-primary)]",
+ : "bg-[var(--color-accent-secondary)]",
)}
/>
</span>
@@ -351,7 +351,7 @@ export function ChatDock({
setDraft(suggestion);
compactTextareaRef.current?.focus();
}}
- className="mt-2 block max-w-full truncate rounded-md px-1 py-1 text-left text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ className="mt-2 block max-w-full truncate rounded-md px-1 py-1 text-left text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
>
<span className="mr-1.5 text-[var(--color-text-tertiary)]">Try</span>
{suggestion}
@@ -376,7 +376,7 @@ export function ChatDock({
>
<DialogPrimitive.Portal>
{isMobile && (
- <DialogPrimitive.Overlay className="fixed inset-0 z-[var(--z-modal)] bg-black/40" />
+ <DialogPrimitive.Overlay className="fixed inset-0 z-[var(--z-modal)] bg-[color-mix(in_srgb,var(--color-bg-root)_72%,transparent)]" />
)}
<DialogPrimitive.Content
style={expandedDockStyle}
@@ -384,7 +384,7 @@ export function ChatDock({
onInteractOutside={(event) => {
if (!isMobile) event.preventDefault();
}}
- className="fixed inset-x-0 bottom-0 z-[var(--z-modal)] flex h-[min(88dvh,760px)] flex-col overflow-hidden rounded-t-2xl border-t border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] pb-[env(safe-area-inset-bottom)] shadow-[var(--shadow-xl)] outline-none md:inset-x-auto md:bottom-[max(var(--chat-dock-bottom-offset),env(safe-area-inset-bottom))] md:right-[max(1rem,env(safe-area-inset-right))] md:w-[min(480px,calc(100vw-2rem))] md:rounded-2xl md:border"
+ className="fixed inset-x-0 bottom-0 z-[var(--z-modal)] flex h-[min(88dvh,760px)] flex-col overflow-hidden rounded-t-2xl border-t border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] pb-[env(safe-area-inset-bottom)] shadow-[var(--shadow-xl)] outline-none md:inset-x-auto md:bottom-[max(var(--chat-dock-bottom-offset),env(safe-area-inset-bottom))] md:right-[max(1rem,env(safe-area-inset-right))] md:w-[min(520px,calc(100vw-2rem))] md:rounded-2xl md:border xl:w-[min(580px,calc(100vw-2rem))]"
>
<DialogPrimitive.Title className="sr-only">
Repository chat
@@ -393,7 +393,7 @@ export function ChatDock({
<div className="h-1 w-10 rounded-full bg-[var(--color-border-hover)]" />
</div>
<header className="flex min-w-0 items-center gap-2 border-b border-[var(--color-border-default)] px-3 py-2">
- <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--color-accent-muted)]">
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--color-bg-elevated)]">
<BrandMark darkSrc={owlDarkSrc} lightSrc={owlLightSrc} size={25} alt="" />
</span>
<div className="min-w-0 flex-1">
@@ -408,7 +408,7 @@ export function ChatDock({
<button
type="button"
onClick={onOpenFullChat}
- className="inline-flex h-8 items-center gap-1.5 rounded-md px-2 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ className="inline-flex h-8 items-center gap-1.5 rounded-md px-2 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
>
<MessageCircle className="h-3.5 w-3.5" />
Full chat
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index c98fe5cc1..1e544f641 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -26,7 +26,7 @@ import {
type RefObject,
type ReactNode,
} from "react";
-import { Send, PanelRight } from "lucide-react";
+import { ArrowDown, Send, PanelRight } from "lucide-react";
import { Button } from "../ui/button";
import { ScrollArea } from "../ui/scroll-area";
import { cn } from "../lib/cn";
@@ -41,6 +41,7 @@ import {
import type { ChatUIMessage } from "@repowise-dev/types/chat";
import type { SourceReference } from "./source-citations";
import { ChatComposer } from "./chat-composer";
+import { useChatScroll } from "./use-chat-scroll";
const DEFAULT_SUGGESTIONS = [
"Give me an overview of this codebase",
@@ -75,8 +76,7 @@ export interface ChatInterfaceProps {
onCancel: () => void;
/**
- * Slot rendered in the right side of the active-conversation header bar AND
- * in the empty-state composer footer. Typically a `<ModelSelector />`
+ * Slot rendered at the left side of the composer footer. Typically a `<ModelSelector />`
* wrapper that owns its providers SWR.
*/
modelSelectorSlot?: ReactNode;
@@ -89,6 +89,8 @@ export interface ChatInterfaceProps {
/** Avatar src forwarded to `ChatMessage`. */
assistantAvatarSrc?: string;
+ /** Optional host-supplied avatar for user turns. */
+ userAvatarSrc?: string;
/** Forwarded to `SourceCitations` for href customisation. */
buildCitationHref?: (source: SourceReference) => string;
/** Forwarded to `SourceCitations` for route-agnostic link generation. */
@@ -114,6 +116,8 @@ export interface ChatInterfaceProps {
onDraftChange?: (draft: string) => void;
onContextRemove?: () => void;
composerRef?: RefObject<HTMLTextAreaElement | null>;
+ onRetry?: (message: ChatUIMessage) => void | Promise<void>;
+ onEditAndResend?: (message: ChatUIMessage, text: string) => void | Promise<void>;
}
export function ChatInterface({
@@ -128,6 +132,7 @@ export function ChatInterface({
modelSelectorSlot,
historySlot,
assistantAvatarSrc,
+ userAvatarSrc,
buildCitationHref,
linkPrefix,
emptyStateLogoSrc = "/repowise-logo.png",
@@ -141,13 +146,14 @@ export function ChatInterface({
onDraftChange,
onContextRemove,
composerRef,
+ onRetry,
+ onEditAndResend,
}: ChatInterfaceProps) {
const [internalInput, setInternalInput] = useState("");
const input = draft ?? internalInput;
const setInput = onDraftChange ?? setInternalInput;
const [artifactPanelOpen, setArtifactPanelOpen] = useState(false);
const [artifacts, setArtifacts] = useState<Artifact[]>([]);
- const bottomRef = useRef<HTMLDivElement>(null);
const internalTextareaRef = useRef<HTMLTextAreaElement>(null);
const textareaRef = composerRef ?? internalTextareaRef;
@@ -161,9 +167,50 @@ export function ChatInterface({
context.kind !== "repository" &&
context.kind !== "chat";
+ const {
+ viewportRef,
+ contentRef,
+ hasContentBelow,
+ isFollowingLive,
+ revealNewTurn,
+ jumpToLatest,
+ } = useChatScroll();
+ const [announcement, setAnnouncement] = useState("");
+ const previousStreaming = useRef(isStreaming);
+ const cancelledRef = useRef(false);
+
useEffect(() => {
- bottomRef.current?.scrollIntoView?.({ behavior: "smooth" });
- }, [messages]);
+ if (error) setAnnouncement(`Answer failed. ${error}`);
+ else if (!previousStreaming.current && isStreaming) {
+ cancelledRef.current = false;
+ setAnnouncement("Working on your answer.");
+ } else if (previousStreaming.current && !isStreaming) {
+ if (!cancelledRef.current) setAnnouncement("Answer complete.");
+ }
+ previousStreaming.current = isStreaming;
+ }, [error, isStreaming]);
+
+ const handleSend = useCallback(
+ (text: string) => {
+ revealNewTurn();
+ return onSend(text);
+ },
+ [onSend, revealNewTurn],
+ );
+
+ const handleCancel = useCallback(() => {
+ cancelledRef.current = true;
+ setAnnouncement("Answer stopped.");
+ onCancel();
+ }, [onCancel]);
+
+ const handleFollowUp = useCallback(
+ (text: string) => {
+ setInput(text);
+ textareaRef.current?.focus();
+ },
+ [setInput, textareaRef],
+ );
const handleViewArtifact = useCallback(
(artifact: { type: string; data: Record<string, unknown> }) => {
@@ -208,7 +255,7 @@ export function ChatInterface({
return (
<div className="flex h-full min-h-0 flex-col" data-chat-variant={variant}>
{/* The one chrome row. */}
- {(historySlot || modelSelectorSlot) && (
+ {(historySlot || totalArtifactCount > 0) && (
<div className="flex items-center justify-between gap-2 px-[var(--page-pad)] py-2.5 border-b border-[var(--color-border-default)] shrink-0 bg-[var(--color-bg-surface)]">
<div className="flex min-w-0 items-center gap-2">{historySlot}</div>
<div className="flex items-center gap-2 shrink-0">
@@ -219,7 +266,7 @@ export function ChatInterface({
className={cn(
"h-8 text-xs gap-1.5 tabular-nums",
artifactPulse &&
- "animate-pulse text-[var(--color-accent-primary)]",
+ "animate-pulse text-[var(--color-accent-secondary)]",
)}
onClick={() => setArtifactPanelOpen(true)}
>
@@ -228,7 +275,6 @@ export function ChatInterface({
{totalArtifactCount}
</Button>
)}
- {modelSelectorSlot}
</div>
</div>
)}
@@ -241,8 +287,8 @@ export function ChatInterface({
// Top-anchored rather than centred — vertical centring would need a
// height Radix's `display:table` viewport wrapper does not pass down,
// and the section style reads left-aligned everywhere else anyway.
- <ScrollArea className="h-full">
- <div className={cn("mx-auto flex max-w-2xl flex-col", variant === "dock" ? "gap-5 px-4 py-7" : "gap-10 px-[var(--page-pad)] py-14")}>
+ <ScrollArea className="h-full" viewportRef={viewportRef}>
+ <div ref={contentRef} className={cn("mx-auto flex max-w-2xl flex-col", variant === "dock" ? "gap-5 px-4 py-7" : "gap-10 px-[var(--page-pad)] py-14")}>
<div className="space-y-4">
{variant !== "dock" && <BrandMark darkSrc={emptyStateLogoSrc} size={40} />}
<h2 className={cn("font-semibold text-[var(--color-text-primary)]", variant === "dock" ? "text-lg" : "text-[22px]")}>
@@ -268,7 +314,7 @@ export function ChatInterface({
{visibleSuggestions.slice(0, variant === "dock" ? 3 : undefined).map((s) => (
<li key={s}>
<button
- className="group flex w-full items-center gap-3 border-b border-[var(--color-border-default)] py-3 text-left text-[15px] text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-accent-primary)]"
+ className="group flex w-full items-center gap-3 border-b border-[var(--color-border-default)] py-3 text-left text-[15px] text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)]"
onClick={() => handleSuggestion(s)}
>
<span className="flex-1 min-w-0">{s}</span>
@@ -281,30 +327,74 @@ export function ChatInterface({
</div>
</ScrollArea>
) : (
- <ScrollArea className="h-full">
- <div className={cn("mx-auto max-w-3xl", variant === "dock" ? "space-y-7 px-4 py-6" : "space-y-10 px-[var(--page-pad)] py-10")}>
- {messages.map((m) => (
+ <ScrollArea
+ className="h-full"
+ viewportRef={viewportRef}
+ viewportClassName="[overflow-anchor:auto]"
+ >
+ <div
+ ref={contentRef}
+ className={cn(
+ "mx-auto w-full",
+ variant === "dock"
+ ? "max-w-full space-y-6 px-4 py-5"
+ : "max-w-[960px] space-y-10 px-[var(--page-pad)] py-10",
+ )}
+ >
+ {messages.map((m, index) => {
+ const previousAssistant = messages
+ .slice(0, index)
+ .reverse()
+ .find((candidate) => candidate.role === "assistant");
+ const modelChanged = Boolean(
+ m.role === "assistant" &&
+ previousAssistant &&
+ `${previousAssistant.provider ?? ""}:${previousAssistant.model ?? ""}` !==
+ `${m.provider ?? ""}:${m.model ?? ""}`,
+ );
+ return (
<ChatMessage
key={m.id}
message={m}
repoId={repoId}
onViewArtifact={handleViewArtifact}
{...(assistantAvatarSrc ? { assistantAvatarSrc } : {})}
+ {...(userAvatarSrc ? { userAvatarSrc } : {})}
+ density={variant}
+ modelChanged={modelChanged}
+ {...(onRetry ? { onRetry } : {})}
+ {...(onEditAndResend ? { onEditAndResend } : {})}
+ onFollowUp={handleFollowUp}
{...(buildCitationHref ? { buildCitationHref } : {})}
{...(linkPrefix ? { linkPrefix } : {})}
/>
- ))}
+ );
+ })}
{error && (
<div className="rounded-lg border border-[var(--color-error)]/30 bg-[var(--color-error)]/10 px-4 py-2.5 text-sm text-[var(--color-error)]">
{error}
</div>
)}
- <div ref={bottomRef} />
</div>
</ScrollArea>
)}
+ {!isEmpty && hasContentBelow && (
+ <button
+ type="button"
+ onClick={jumpToLatest}
+ aria-pressed={isFollowingLive}
+ className="absolute bottom-3 left-1/2 z-10 inline-flex min-h-9 -translate-x-1/2 items-center gap-1.5 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-3 text-xs font-medium text-[var(--color-text-secondary)] shadow-[var(--shadow-sm)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <ArrowDown className="h-3.5 w-3.5" />
+ Jump to latest
+ </button>
+ )}
</div>
+ <span className="sr-only" role="status" aria-live="polite" aria-atomic="true">
+ {announcement}
+ </span>
+
{/* Input area. The composer keeps its elevation: it is a genuinely
interactive surface, which is what rule 1 reserves elevation for. */}
<div
@@ -314,7 +404,7 @@ export function ChatInterface({
!isEmpty && "border-t border-[var(--color-border-default)]",
)}
>
- <div className="max-w-3xl mx-auto">
+ <div className={cn("mx-auto w-full", variant === "dock" ? "max-w-full" : "max-w-[960px]")}>
{sendDisabled && sendDisabledReason && (
<div className="mb-2 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-3 py-2 text-xs text-[var(--color-text-secondary)]">
{sendDisabledReason}
@@ -329,15 +419,16 @@ export function ChatInterface({
<ChatComposer
value={input}
onValueChange={setInput}
- onSend={onSend}
- onCancel={onCancel}
+ onSend={handleSend}
+ onCancel={handleCancel}
isStreaming={isStreaming}
placeholder={composerPlaceholder}
disabled={sendDisabled}
compact={variant === "dock"}
textareaRef={textareaRef}
+ {...(modelSelectorSlot ? { footer: modelSelectorSlot } : {})}
/>
- {isEmpty && (
+ {isEmpty && !modelSelectorSlot && (
<p className={cn(MICRO_LABEL, "mt-2.5 text-center")}>
Shift+Enter for newline · Enter to send
</p>
diff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsx
index cbb23378f..2a319e1e1 100644
--- a/packages/ui/src/chat/chat-message.tsx
+++ b/packages/ui/src/chat/chat-message.tsx
@@ -1,9 +1,12 @@
"use client";
import { memo } from "react";
+import { UserRound } from "lucide-react";
import { cn } from "../lib/cn";
import { BrandMark } from "../shared/brand-mark";
import { ToolCallGroup } from "./tool-call-group";
+import { WorkingOrb } from "./working-orb";
+import { MessageActions } from "./message-actions";
import { Markdown } from "../shared/markdown";
import { SourceCitations, type SourceReference } from "./source-citations";
import type { ChatUIMessage } from "@repowise-dev/types/chat";
@@ -18,6 +21,14 @@ interface ChatMessageProps {
buildCitationHref?: (source: SourceReference) => string;
/** Forwarded to `SourceCitations` for route-agnostic link generation. */
linkPrefix?: string;
+ density?: "page" | "dock";
+ /** Optional host identity image for user turns. */
+ userAvatarSrc?: string;
+ /** True when this response uses a different model from the prior answer. */
+ modelChanged?: boolean;
+ onRetry?: (message: ChatUIMessage) => void | Promise<void>;
+ onEditAndResend?: (message: ChatUIMessage, text: string) => void | Promise<void>;
+ onFollowUp?: (text: string) => void;
}
/**
@@ -40,36 +51,74 @@ function ChatMessageImpl({
assistantAvatarSrc = "/repowise-logo.png",
buildCitationHref,
linkPrefix,
+ density = "page",
+ userAvatarSrc,
+ modelChanged = false,
+ onRetry,
+ onEditAndResend,
+ onFollowUp,
}: ChatMessageProps) {
const isUser = message.role === "user";
if (isUser) {
return (
- <div className="flex gap-3">
- <span
- aria-hidden
- className="mt-[0.7rem] h-px w-6 shrink-0 bg-[var(--color-border-default)]"
- />
- <p className="flex-1 min-w-0 text-lg font-medium leading-snug text-[var(--color-text-primary)]">
- {message.text}
- </p>
- </div>
+ <article
+ aria-label="You"
+ data-chat-message-id={message.id}
+ data-chat-role="user"
+ data-chat-density={density}
+ className="flex min-w-0 justify-end gap-2.5"
+ >
+ <div className={cn("min-w-0", density === "dock" ? "max-w-[88%]" : "max-w-[78%]") }>
+ <p className="mb-1 text-right font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ You
+ </p>
+ <p
+ className={cn(
+ "[overflow-wrap:anywhere] rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]",
+ density === "dock"
+ ? "px-3 py-2 text-[15px] leading-relaxed"
+ : "px-3.5 py-2.5 text-base leading-relaxed",
+ )}
+ >
+ {message.text}
+ </p>
+ <MessageActions message={message} {...(onEditAndResend ? { onEditAndResend: (text) => onEditAndResend(message, text) } : {})} />
+ </div>
+ <div className="mt-5 flex h-7 w-7 shrink-0 items-center justify-center overflow-hidden rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-secondary)]">
+ {userAvatarSrc ? (
+ <img src={userAvatarSrc} alt="" className="h-full w-full object-cover" />
+ ) : (
+ <UserRound aria-hidden className="h-3.5 w-3.5" />
+ )}
+ </div>
+ </article>
);
}
return (
- <div className="flex gap-3.5">
- <div
- className={cn(
- "flex h-8 w-8 shrink-0 items-center justify-center rounded-full mt-0.5",
- "bg-[var(--color-bg-surface)] border border-[var(--color-border-default)]",
- )}
- >
+ <article
+ aria-label="Repowise"
+ data-chat-message-id={message.id}
+ data-chat-role="assistant"
+ data-chat-density={density}
+ className={cn("flex min-w-0", density === "dock" ? "gap-2.5" : "gap-3.5")}
+ >
+ <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center">
<BrandMark darkSrc={assistantAvatarSrc} size={22} />
</div>
<div className="flex-1 min-w-0">
- <div className="max-w-full space-y-3">
+ <p className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Repowise
+ </p>
+ {(message.provider || message.model) && (
+ <p className="mb-2 text-[11px] text-[var(--color-text-tertiary)]">
+ {modelChanged ? "Model changed to " : ""}
+ {[message.provider, message.model].filter(Boolean).join(" · ")}
+ </p>
+ )}
+ <div className={cn("max-w-full", density === "dock" ? "space-y-2.5" : "space-y-3")}>
{message.toolCalls.length > 0 && (
<ToolCallGroup
toolCalls={message.toolCalls}
@@ -77,7 +126,9 @@ function ChatMessageImpl({
/>
)}
- {message.text && <Markdown content={message.text} />}
+ {message.text && (
+ <Markdown content={message.text} density={density === "dock" ? "compact" : "reading"} streaming={message.isStreaming} />
+ )}
{!message.isStreaming && message.toolCalls.length > 0 && (
<SourceCitations
@@ -91,21 +142,19 @@ function ChatMessageImpl({
{message.isStreaming &&
!message.text &&
message.toolCalls.length === 0 && (
- <div className="flex items-center gap-1.5 py-2">
- <div className="h-1.5 w-1.5 rounded-full bg-[var(--color-text-tertiary)] animate-pulse" />
- <div
- className="h-1.5 w-1.5 rounded-full bg-[var(--color-text-tertiary)] animate-pulse"
- style={{ animationDelay: "0.15s" }}
- />
- <div
- className="h-1.5 w-1.5 rounded-full bg-[var(--color-text-tertiary)] animate-pulse"
- style={{ animationDelay: "0.3s" }}
- />
+ <div className="flex items-center gap-2 py-2 text-xs text-[var(--color-text-tertiary)]">
+ <WorkingOrb />
+ <span>Reading context</span>
</div>
)}
+ <MessageActions
+ message={message}
+ {...(onRetry ? { onRetry: () => onRetry(message) } : {})}
+ {...(onFollowUp ? { onFollowUp } : {})}
+ />
</div>
</div>
- </div>
+ </article>
);
}
diff --git a/packages/ui/src/chat/conversation-history.tsx b/packages/ui/src/chat/conversation-history.tsx
index 82b9877cf..c3729ecd3 100644
--- a/packages/ui/src/chat/conversation-history.tsx
+++ b/packages/ui/src/chat/conversation-history.tsx
@@ -1,14 +1,7 @@
"use client";
-/**
- * Presentational shell for the chat conversation-history dropdown. The data
- * fetch (SWR list) and delete mutation live in the consumer wrapper; this
- * shell only renders the trigger, popover surface, list rows, and emits
- * select / delete / new intents via callbacks.
- */
-
-import { useMemo, useState } from "react";
-import { History, Plus, Search, Trash2 } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { GitFork, History, PanelLeftClose, PanelLeftOpen, Pencil, Pin, Plus, Search, Trash2, Undo2 } from "lucide-react";
import { cn } from "../lib/cn";
import { formatRelativeTime } from "../lib/format";
import type { Conversation } from "@repowise-dev/types/chat";
@@ -16,134 +9,126 @@ import type { Conversation } from "@repowise-dev/types/chat";
export interface ConversationHistoryProps {
conversations: Conversation[] | undefined;
isLoading?: boolean;
- /** id of the currently active conversation. */
selectedId?: string | null;
onSelect: (id: string) => void;
onDelete: (id: string) => void | Promise<void>;
onNew: () => void;
+ onRename?: (id: string, title: string) => void | Promise<void>;
+ onPin?: (id: string, pinned: boolean) => void | Promise<void>;
+ onFork?: (id: string) => void | Promise<void>;
+ undoDelete?: { title: string; onUndo: () => void | Promise<void> };
+ variant?: "popover" | "rail";
+ /** Enables a compact icon rail for the persistent full-page history. */
+ collapsible?: boolean;
+ /** Optional host-owned key used to remember the rail preference. */
+ railPreferenceKey?: string;
className?: string;
}
+function historyGroup(conversation: Conversation): string {
+ if (conversation.pinned) return "Pinned";
+ const age = Date.now() - new Date(conversation.updated_at).getTime();
+ if (age < 86400000) return "Today";
+ if (age < 604800000) return "Previous 7 days";
+ return "Earlier";
+}
+
export function ConversationHistory({
- conversations,
- isLoading = false,
- selectedId = null,
- onSelect,
- onDelete,
- onNew,
- className,
+ conversations, isLoading = false, selectedId = null, onSelect, onDelete,
+ onNew, onRename, onPin, onFork, undoDelete, variant = "popover",
+ collapsible = false, railPreferenceKey, className,
}: ConversationHistoryProps) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
-
+ const [editing, setEditing] = useState<{ id: string; title: string } | null>(null);
+ const [railCollapsed, setRailCollapsed] = useState(false);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const panelRef = useRef<HTMLDivElement>(null);
+ const closePopover = useCallback(() => {
+ setOpen(false);
+ window.requestAnimationFrame(() => triggerRef.current?.focus());
+ }, []);
+ useEffect(() => {
+ if (!open || variant === "rail") return;
+ panelRef.current?.querySelector<HTMLElement>("input, button")?.focus();
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ closePopover();
+ }
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, [closePopover, open, variant]);
+ useEffect(() => {
+ if (!railPreferenceKey) return;
+ setRailCollapsed(window.localStorage.getItem(railPreferenceKey) === "collapsed");
+ }, [railPreferenceKey]);
+ const updateRailCollapsed = useCallback((collapsed: boolean) => {
+ setRailCollapsed(collapsed);
+ if (railPreferenceKey) {
+ window.localStorage.setItem(railPreferenceKey, collapsed ? "collapsed" : "expanded");
+ }
+ }, [railPreferenceKey]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
- if (!q) return conversations;
- return conversations?.filter((c) => c.title.toLowerCase().includes(q));
+ return q ? conversations?.filter((c) => c.title.toLowerCase().includes(q)) : conversations;
}, [conversations, query]);
+ const groups = useMemo(() => {
+ const result = new Map<string, Conversation[]>();
+ for (const conversation of filtered ?? []) {
+ const key = historyGroup(conversation);
+ result.set(key, [...(result.get(key) ?? []), conversation]);
+ }
+ return result;
+ }, [filtered]);
- return (
- <div className={cn("relative", className)}>
- <button
- onClick={() => setOpen(!open)}
- className={cn(
- "flex items-center gap-1 rounded-md px-2 py-1 text-xs",
- "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",
- "hover:bg-[var(--color-bg-elevated)] transition-colors",
- )}
- >
- <History className="h-3.5 w-3.5 shrink-0" />
- <span className="sr-only sm:not-sr-only">History</span>
- </button>
-
- {open && (
- <>
- <div
- className="fixed inset-0 z-[var(--z-dropdown)]"
- onClick={() => setOpen(false)}
- />
- <div className="absolute left-0 top-full mt-1 z-[calc(var(--z-dropdown)+1)] w-72 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-lg overflow-hidden">
- <button
- onClick={() => {
- onNew();
- setOpen(false);
- }}
- className="flex w-full items-center gap-2 px-3 py-2 text-xs text-[var(--color-accent-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors border-b border-[var(--color-border-default)]"
- >
- <Plus className="h-3.5 w-3.5" />
- New conversation
- </button>
-
- {(conversations?.length ?? 0) > 5 && (
- <div className="flex items-center gap-1.5 border-b border-[var(--color-border-default)] px-3 py-1.5">
- <Search className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
- <input
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder="Search conversations…"
- aria-label="Search conversations"
- className="w-full bg-transparent text-xs text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]"
- />
- </div>
- )}
-
- <div className="max-h-64 overflow-y-auto">
- {isLoading && !conversations && (
- <div className="px-3 py-4 text-xs text-[var(--color-text-tertiary)] text-center">
- Loading...
- </div>
- )}
- {conversations?.length === 0 && (
- <div className="px-3 py-4 text-xs text-[var(--color-text-tertiary)] text-center">
- No conversations yet
- </div>
- )}
- {(conversations?.length ?? 0) > 0 && filtered?.length === 0 && (
- <div className="px-3 py-4 text-xs text-[var(--color-text-tertiary)] text-center">
- No conversations match
- </div>
- )}
- {filtered?.map((conv) => (
- <div
- key={conv.id}
- className={cn(
- "flex items-center gap-2 px-3 py-2 hover:bg-[var(--color-bg-elevated)] transition-colors group cursor-pointer",
- conv.id === selectedId &&
- "bg-[var(--color-accent-muted)]",
+ const panel = (
+ <div ref={panelRef} {...(variant === "popover" ? { role: "dialog", "aria-label": "Conversation history" } : {})} className={cn("flex min-h-0 flex-col bg-[var(--color-bg-surface)]", variant === "rail" ? "h-full border-r border-[var(--color-border-default)]" : "max-h-[min(70dvh,560px)] w-80 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-[var(--shadow-lg)]")}>
+ <div className="flex items-center gap-1 border-b border-[var(--color-border-default)] p-2">
+ <button type="button" onClick={() => { onNew(); closePopover(); }} className="flex min-h-9 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-xs text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"><Plus className="h-3.5 w-3.5 shrink-0" /> <span className="truncate">New conversation</span></button>
+ {variant === "rail" && collapsible && <button type="button" onClick={() => updateRailCollapsed(true)} aria-label="Collapse conversation history" title="Collapse history" className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"><PanelLeftClose className="h-4 w-4" /></button>}
+ </div>
+ <label className="m-2 flex min-h-9 items-center gap-2 border-b border-[var(--color-border-default)] px-1"><Search className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" /><span className="sr-only">Search conversations</span><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search history" className="min-w-0 flex-1 bg-transparent text-xs text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]" /></label>
+ <div className="min-h-0 flex-1 overflow-y-auto px-2 pb-2">
+ {isLoading && !conversations && <p className="py-6 text-center text-xs text-[var(--color-text-tertiary)]">Loading…</p>}
+ {conversations?.length === 0 && <p className="py-6 text-center text-xs text-[var(--color-text-tertiary)]">No conversations yet</p>}
+ {(conversations?.length ?? 0) > 0 && filtered?.length === 0 && <p className="py-6 text-center text-xs text-[var(--color-text-tertiary)]">No conversations match</p>}
+ {[...groups].map(([label, rows]) => (
+ <section key={label} aria-label={label}>
+ <h3 className="px-2 pb-1 pt-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">{label}</h3>
+ <div className="border-t border-[var(--color-border-default)]">
+ {rows.map((conversation) => (
+ <div key={conversation.id} className={cn("group relative border-b border-[var(--color-border-default)]", conversation.id === selectedId && "bg-[var(--color-bg-elevated)]")}>
+ {editing?.id === conversation.id ? (
+ <form className="flex gap-1 p-2" onSubmit={(event) => { event.preventDefault(); const title = editing.title.trim(); if (title) void onRename?.(conversation.id, title); setEditing(null); }}><input autoFocus value={editing.title} onChange={(event) => setEditing({ id: conversation.id, title: event.target.value })} aria-label="Conversation title" className="min-w-0 flex-1 border-b border-[var(--color-accent-primary)] bg-transparent text-xs text-[var(--color-text-primary)] outline-none" /><button className="min-h-8 px-2 text-xs text-[var(--color-text-secondary)]">Save</button></form>
+ ) : (
+ <button type="button" onClick={() => { onSelect(conversation.id); closePopover(); }} className="w-full py-2 pl-2 pr-[7.5rem] text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] sm:pr-2"><span className="block text-xs leading-4 text-[var(--color-text-primary)] [overflow-wrap:anywhere]">{conversation.title}</span><span className="mt-0.5 block truncate font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">{formatRelativeTime(conversation.updated_at)} · {conversation.message_count} msgs</span></button>
)}
- onClick={() => {
- onSelect(conv.id);
- setOpen(false);
- }}
- >
- <div className="flex-1 min-w-0">
- {/* Two lines rather than an ellipsis: a conversation is
- identified by its title, so cutting it mid-word reports
- a width decision as missing content. */}
- <div className="text-xs text-[var(--color-text-primary)] line-clamp-2">
- {conv.title}
- </div>
- <div className="font-mono text-[10px] text-[var(--color-text-tertiary)] tabular-nums mt-0.5">
- {formatRelativeTime(conv.updated_at)} ·{" "}
- {conv.message_count} msgs
- </div>
+ <div className="absolute right-1 top-1 flex items-center justify-end gap-0.5 opacity-70 sm:rounded sm:opacity-0 sm:group-hover:bg-[var(--color-bg-overlay)] sm:group-hover:opacity-100 sm:group-focus-within:bg-[var(--color-bg-overlay)] sm:group-focus-within:opacity-100">
+ {onRename && <button type="button" onClick={() => setEditing({ id: conversation.id, title: conversation.title })} aria-label="Rename conversation" className="flex h-7 w-7 items-center justify-center rounded text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"><Pencil className="h-3.5 w-3.5" /></button>}
+ {onPin && <button type="button" onClick={() => void onPin(conversation.id, !conversation.pinned)} aria-label={conversation.pinned ? "Unpin conversation" : "Pin conversation"} className="flex h-7 w-7 items-center justify-center rounded text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"><Pin className="h-3.5 w-3.5" /></button>}
+ {onFork && <button type="button" onClick={() => void onFork(conversation.id)} aria-label="Fork conversation" className="flex h-7 w-7 items-center justify-center rounded text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"><GitFork className="h-3.5 w-3.5" /></button>}
+ <button type="button" onClick={() => void onDelete(conversation.id)} aria-label="Delete conversation" className="flex h-7 w-7 items-center justify-center rounded text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-error)]"><Trash2 className="h-3.5 w-3.5" /></button>
</div>
- <button
- onClick={(e) => {
- e.stopPropagation();
- void onDelete(conv.id);
- }}
- className="opacity-0 group-hover:opacity-100 focus-visible:opacity-100 p-1 shrink-0 self-start text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] transition-all"
- aria-label="Delete conversation"
- >
- <Trash2 className="h-3 w-3" />
- </button>
</div>
))}
</div>
- </div>
- </>
- )}
+ </section>
+ ))}
+ </div>
+ {undoDelete && <div className="flex items-center gap-2 border-t border-[var(--color-border-default)] px-3 py-2 text-xs text-[var(--color-text-secondary)]"><span className="min-w-0 flex-1 truncate">Deleted {undoDelete.title}</span><button type="button" onClick={() => void undoDelete.onUndo()} className="inline-flex min-h-8 items-center gap-1 font-medium text-[var(--color-text-primary)]"><Undo2 className="h-3.5 w-3.5" /> Undo</button></div>}
</div>
);
+
+ if (variant === "rail" && collapsible && railCollapsed) return (
+ <aside aria-label="Conversation history" data-collapsed="true" className={cn("min-h-0 overflow-hidden", className)}>
+ <div className="flex h-full flex-col items-center gap-1 border-r border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-1.5 py-2">
+ <button type="button" onClick={() => updateRailCollapsed(false)} aria-label="Expand conversation history" title="Expand history" className="flex h-9 w-9 items-center justify-center rounded-md text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"><PanelLeftOpen className="h-4 w-4" /></button>
+ <button type="button" onClick={onNew} aria-label="New conversation" title="New conversation" className="flex h-9 w-9 items-center justify-center rounded-md text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"><Plus className="h-4 w-4" /></button>
+ </div>
+ </aside>
+ );
+ if (variant === "rail") return <aside aria-label="Conversation history" data-collapsed="false" className={cn("min-h-0 overflow-hidden", className)}>{panel}</aside>;
+ return <div className={cn("relative", className)}><button ref={triggerRef} type="button" onClick={() => setOpen(!open)} aria-expanded={open} aria-haspopup="dialog" className="flex min-h-9 items-center gap-1 rounded-md px-2 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"><History className="h-3.5 w-3.5" /><span className="sr-only sm:not-sr-only">History</span></button>{open && <><button type="button" aria-label="Close history" className="fixed inset-0 z-[var(--z-dropdown)]" onClick={closePopover} /><div className="absolute left-0 top-full z-[calc(var(--z-dropdown)+1)] mt-1">{panel}</div></>}</div>;
}
diff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.ts
index 362755407..711c21315 100644
--- a/packages/ui/src/chat/index.ts
+++ b/packages/ui/src/chat/index.ts
@@ -1,6 +1,8 @@
export * from "./artifact-panel";
export * from "./artifacts";
export * from "./chat-interface";
+export * from "./use-chat-scroll";
+export * from "./use-chat-draft";
export * from "./chat-composer";
export * from "./chat-dock";
export * from "./chat-context";
@@ -9,6 +11,7 @@ export * from "../shared/markdown";
export * from "./chat-message";
export * from "./conversation-history";
export * from "./model-selector";
+export * from "./message-actions";
export * from "./source-citation";
export * from "./source-citations";
export * from "./tool-call-block";
diff --git a/packages/ui/src/chat/message-actions.tsx b/packages/ui/src/chat/message-actions.tsx
new file mode 100644
index 000000000..a91f5c627
--- /dev/null
+++ b/packages/ui/src/chat/message-actions.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import { useState } from "react";
+import { Check, Copy, Pencil, RotateCcw, Send } from "lucide-react";
+import type { ChatUIMessage } from "@repowise-dev/types/chat";
+
+interface MessageActionsProps {
+ message: ChatUIMessage;
+ onRetry?: () => void | Promise<void>;
+ onEditAndResend?: (text: string) => void | Promise<void>;
+ onFollowUp?: (text: string) => void;
+}
+
+export function MessageActions({ message, onRetry, onEditAndResend, onFollowUp }: MessageActionsProps) {
+ const [copied, setCopied] = useState(false);
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(message.text);
+ if (message.isStreaming || !message.text) return null;
+
+ if (editing) {
+ return <form className="mt-2 flex gap-2" onSubmit={(event) => { event.preventDefault(); const text = draft.trim(); if (text) void onEditAndResend?.(text); setEditing(false); }}><textarea autoFocus value={draft} onChange={(event) => setDraft(event.target.value)} aria-label="Edit message" className="min-h-20 flex-1 resize-y rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-2 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent-primary)]" /><button type="submit" className="flex h-10 w-10 items-center justify-center rounded-md bg-[var(--color-accent-fill)] text-[var(--color-text-on-accent)]" aria-label="Fork and resend"><Send className="h-4 w-4" /></button></form>;
+ }
+
+ const actionClass = "inline-flex min-h-8 items-center gap-1 rounded-md px-1.5 text-[11px] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";
+ return <div className="mt-1.5 flex flex-wrap items-center gap-1" aria-label={`${message.role} message actions`}><button type="button" className={actionClass} onClick={() => { void navigator.clipboard.writeText(message.text); setCopied(true); window.setTimeout(() => setCopied(false), 1600); }}>{copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}{copied ? "Copied" : "Copy"}</button>{message.role === "assistant" && onRetry && <button type="button" className={actionClass} onClick={() => void onRetry()}><RotateCcw className="h-3 w-3" />Retry</button>}{message.role === "user" && message.serverId && onEditAndResend && <button type="button" className={actionClass} onClick={() => setEditing(true)}><Pencil className="h-3 w-3" />Edit and resend</button>}{message.role === "assistant" && onFollowUp && <button type="button" className={actionClass} onClick={() => onFollowUp("Can you go deeper on the most important part?")}>Follow up</button>}</div>;
+}
diff --git a/packages/ui/src/chat/model-selector.tsx b/packages/ui/src/chat/model-selector.tsx
index e704e5ea6..5b994d569 100644
--- a/packages/ui/src/chat/model-selector.tsx
+++ b/packages/ui/src/chat/model-selector.tsx
@@ -7,8 +7,8 @@
* via a thin wrapper that maps its hook output onto these props.
*/
-import { useState } from "react";
-import { ChevronDown, Check, Key, X } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { ChevronUp, Check } from "lucide-react";
import { cn } from "../lib/cn";
export interface ModelSelectorProvider {
@@ -25,7 +25,10 @@ export interface ModelSelectorProps {
activeModel: string | null;
isLoading?: boolean;
onActivate: (providerId: string, model: string) => void | Promise<void>;
- onSaveKey: (providerId: string, key: string) => void | Promise<void>;
+ /** API-key management belongs in Settings, outside routine model choice. */
+ settingsHref?: string;
+ /** @deprecated Key management is ignored here and belongs in Settings. */
+ onSaveKey?: (providerId: string, key: string) => void | Promise<void>;
/** Optional label override when no provider is active. */
emptyLabel?: string;
className?: string;
@@ -37,14 +40,29 @@ export function ModelSelector({
activeModel,
isLoading = false,
onActivate,
- onSaveKey,
+ settingsHref = "/settings",
emptyLabel = "Select model",
className,
}: ModelSelectorProps) {
const [open, setOpen] = useState(false);
- const [addingKeyFor, setAddingKeyFor] = useState<string | null>(null);
- const [keyInput, setKeyInput] = useState("");
- const [saving, setSaving] = useState(false);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const panelRef = useRef<HTMLDivElement>(null);
+ const close = useCallback(() => {
+ setOpen(false);
+ window.requestAnimationFrame(() => triggerRef.current?.focus());
+ }, []);
+ useEffect(() => {
+ if (!open) return;
+ panelRef.current?.querySelector<HTMLElement>("button, a")?.focus();
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ close();
+ }
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, [close, open]);
const activeP = providers.find((p) => p.id === activeProvider);
const label = activeP
@@ -53,32 +71,21 @@ export function ModelSelector({
async function handleSelect(providerId: string, model: string) {
await onActivate(providerId, model);
- setOpen(false);
- }
-
- async function handleSaveKey(providerId: string) {
- if (!keyInput.trim()) return;
- setSaving(true);
- try {
- await onSaveKey(providerId, keyInput.trim());
- setAddingKeyFor(null);
- setKeyInput("");
- } catch {
- // Errors surface via the consumer's hook.
- } finally {
- setSaving(false);
- }
+ close();
}
return (
<div className={cn("relative", className)}>
<button
+ ref={triggerRef}
+ type="button"
onClick={() => setOpen(!open)}
+ aria-expanded={open}
+ aria-haspopup="dialog"
className={cn(
- "flex items-center gap-1.5 rounded-md px-2 py-1 text-xs",
+ "flex min-h-7 items-center gap-1.5 rounded px-1.5 py-0.5 text-xs",
"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",
"hover:bg-[var(--color-bg-elevated)] transition-colors",
- "border border-[var(--color-border-default)]",
)}
>
{/* The model name is the longest string in a crowded row. Below `sm`
@@ -87,7 +94,7 @@ export function ModelSelector({
<span className="truncate max-w-[120px] sm:max-w-[200px]">
{isLoading ? "…" : label}
</span>
- <ChevronDown className="h-3 w-3 shrink-0" />
+ <ChevronUp className="h-3 w-3 shrink-0" />
</button>
{open && (
@@ -95,12 +102,11 @@ export function ModelSelector({
<div
className="fixed inset-0 z-[var(--z-dropdown)]"
onClick={() => {
- setOpen(false);
- setAddingKeyFor(null);
+ close();
}}
/>
- <div className="absolute right-0 top-full mt-1 z-[calc(var(--z-dropdown)+1)] w-72 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-lg overflow-hidden">
+ <div ref={panelRef} role="dialog" aria-label="Choose conversation model" className="absolute bottom-full left-0 z-[calc(var(--z-dropdown)+1)] mb-1 w-72 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-[var(--shadow-lg)]">
<div className="p-2 space-y-1 max-h-80 overflow-y-auto">
{providers.map((provider) => {
const isConfigured = provider.configured;
@@ -118,57 +124,12 @@ export function ModelSelector({
{provider.name}
</span>
{!isConfigured && (
- <button
- onClick={(e) => {
- e.stopPropagation();
- setAddingKeyFor(
- addingKeyFor === provider.id
- ? null
- : provider.id,
- );
- setKeyInput("");
- }}
- className="text-[10px] text-[var(--color-accent-primary)] hover:underline flex items-center gap-0.5"
- >
- <Key className="h-3 w-3" />
- Add key
- </button>
+ <a href={settingsHref} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">
+ Configure in Settings
+ </a>
)}
</div>
- {addingKeyFor === provider.id && (
- <div className="px-2 pb-1.5 flex gap-1">
- <input
- type="password"
- value={keyInput}
- onChange={(e) => setKeyInput(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter")
- handleSaveKey(provider.id);
- }}
- placeholder="API key..."
- className="flex-1 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1 text-xs text-[var(--color-text-primary)] outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)]"
- autoFocus
- />
- <button
- onClick={() => handleSaveKey(provider.id)}
- disabled={saving || !keyInput.trim()}
- className="rounded bg-[var(--color-accent-primary)] px-2 py-1 text-xs text-white disabled:opacity-50"
- >
- {saving ? "..." : "Save"}
- </button>
- <button
- onClick={() => {
- setAddingKeyFor(null);
- setKeyInput("");
- }}
- className="p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- <X className="h-3 w-3" />
- </button>
- </div>
- )}
-
{isConfigured &&
provider.models.map((model) => {
const isActive =
@@ -181,7 +142,7 @@ export function ModelSelector({
className={cn(
"flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-xs transition-colors",
isActive
- ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
+ ? "bg-[var(--color-accent-secondary)]/10 text-[var(--color-accent-secondary)]"
: "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",
)}
>
@@ -189,7 +150,7 @@ export function ModelSelector({
{model}
</span>
{isActive && (
- <Check className="h-3 w-3 shrink-0" />
+ <Check className="h-3 w-3 shrink-0 text-[var(--color-accent-secondary)]" />
)}
</button>
);
diff --git a/packages/ui/src/chat/source-citations.tsx b/packages/ui/src/chat/source-citations.tsx
index 2b99735f6..6cdaf05a5 100644
--- a/packages/ui/src/chat/source-citations.tsx
+++ b/packages/ui/src/chat/source-citations.tsx
@@ -161,21 +161,22 @@ export function SourceCitations({
if (sources.length === 0) return null;
return (
- <div className="mt-5 pt-4 border-t border-[var(--color-border-default)]">
- <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] mb-2.5">
- Sources
- </p>
+ <details className="group mt-5 border-t border-[var(--color-border-default)] pt-3">
+ <summary className="flex min-h-8 cursor-pointer list-none items-center gap-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] marker:hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] [&::-webkit-details-marker]:hidden">
+ <span>Sources · {sources.length}</span>
+ <span aria-hidden className="transition-transform group-open:rotate-90">›</span>
+ </summary>
{/* Links, not chips. Each one goes somewhere, so the accent is earned on
hover; a border and a ground on every entry turned a list of eight
into a wall of boxes that outweighed the answer above it. The counter
badge went with them — numbering is only worth its weight when the
prose cites [1], and a reply does not. */}
- <ul className="flex flex-col gap-1.5">
+ <ul className="flex flex-col gap-1.5 pb-1 pt-2">
{sources.map((source) => (
<li key={source.id}>
<a
href={buildHref ? buildHref(source) : defaultBuildHref(source, prefix)}
- className="group inline-flex items-baseline gap-2 text-[13px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors"
+ className="group flex w-full min-w-0 items-baseline gap-2 text-[13px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors"
>
<SourceIcon
pageType={source.pageType}
@@ -183,7 +184,7 @@ export function SourceCitations({
/>
{/* No truncation: a cut title reports a layout decision to the
reader as missing content. Long ones wrap. */}
- <span className="font-medium">{source.title}</span>
+ <span className="min-w-0 font-medium [overflow-wrap:anywhere]">{source.title}</span>
{source.confidence != null && (
<span className="font-mono text-[11px] text-[var(--color-text-tertiary)] tabular-nums">
{(source.confidence * 100).toFixed(0)}%
@@ -194,6 +195,6 @@ export function SourceCitations({
</li>
))}
</ul>
- </div>
+ </details>
);
}
diff --git a/packages/ui/src/chat/tool-call-block.tsx b/packages/ui/src/chat/tool-call-block.tsx
index ecb7c2b1b..e0ebe84e0 100644
--- a/packages/ui/src/chat/tool-call-block.tsx
+++ b/packages/ui/src/chat/tool-call-block.tsx
@@ -13,8 +13,9 @@
*/
import { useState } from "react";
-import { ChevronDown, ChevronRight, Loader2, ArrowUpRight } from "lucide-react";
+import { ChevronDown, ChevronRight, ArrowUpRight } from "lucide-react";
import { cn } from "../lib/cn";
+import { WorkingOrb } from "./working-orb";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
const TOOL_LABELS: Record<string, string> = {
@@ -45,6 +46,7 @@ export function ToolCallBlock({
const [expanded, setExpanded] = useState(false);
const label = TOOL_LABELS[toolCall.name] ?? toolCall.name;
const isRunning = toolCall.status === "running";
+ const isError = toolCall.status === "error";
return (
<div
@@ -61,9 +63,7 @@ export function ToolCallBlock({
disabled={isRunning}
aria-expanded={expanded}
>
- {isRunning && (
- <Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--color-accent-primary)] shrink-0" />
- )}
+ {isRunning && <WorkingOrb />}
<span className="font-medium text-[var(--color-text-secondary)]">
{label}
</span>
@@ -72,6 +72,9 @@ export function ToolCallBlock({
— {toolCall.summary}
</span>
)}
+ {isError && (
+ <span className="text-[var(--color-error)]">— Failed</span>
+ )}
</button>
<span className="ml-auto flex items-center gap-2 shrink-0">
{toolCall.artifact && onViewArtifact && !isRunning && (
diff --git a/packages/ui/src/chat/tool-call-group.tsx b/packages/ui/src/chat/tool-call-group.tsx
index 2446ed364..e044a353a 100644
--- a/packages/ui/src/chat/tool-call-group.tsx
+++ b/packages/ui/src/chat/tool-call-group.tsx
@@ -1,8 +1,9 @@
"use client";
import { useState } from "react";
-import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
+import { ChevronDown, ChevronRight } from "lucide-react";
import { ToolCallBlock } from "./tool-call-block";
+import { WorkingOrb } from "./working-orb";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
interface ToolCallGroupProps {
@@ -27,7 +28,7 @@ export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps)
if (toolCalls.length === 0) return null;
const shell =
- "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-xs overflow-hidden";
+ "border-y border-[var(--color-border-default)] text-xs overflow-hidden";
// A lone tool call doesn't need a group wrapper, but it still needs the
// container the row no longer carries itself.
@@ -36,7 +37,7 @@ export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps)
const artifact = tc.artifact;
const handler = artifact && onViewArtifact ? () => onViewArtifact(artifact) : undefined;
return (
- <div className={shell}>
+ <div data-activity-trail="true" className={shell}>
<ToolCallBlock toolCall={tc} {...(handler ? { onViewArtifact: handler } : {})} />
</div>
);
@@ -45,18 +46,16 @@ export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps)
const open = expanded || running;
return (
- <div className={shell}>
+ <div data-activity-trail="true" className={shell}>
<button
type="button"
className="flex w-full items-center gap-2 px-3 py-2 text-left"
onClick={() => setExpanded((e) => !e)}
aria-expanded={open}
>
- {running && (
- <Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--color-accent-primary)] shrink-0" />
- )}
+ {running && <WorkingOrb />}
<span className="font-medium text-[var(--color-text-secondary)]">
- {running ? "Working" : "Thinking"}
+ {running ? "Working" : "Activity"}
</span>
<span className="text-[var(--color-text-tertiary)] tabular-nums">
· {toolCalls.length} steps
diff --git a/packages/ui/src/chat/use-chat-draft.ts b/packages/ui/src/chat/use-chat-draft.ts
new file mode 100644
index 000000000..7be7f2b52
--- /dev/null
+++ b/packages/ui/src/chat/use-chat-draft.ts
@@ -0,0 +1,26 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+/** Portable per-conversation draft persistence for page and hosted surfaces. */
+export function useChatDraft(storageKey: string) {
+ const [state, setState] = useState({ storageKey, value: "" });
+
+ useEffect(() => {
+ let value = "";
+ try {
+ value = window.localStorage.getItem(storageKey) ?? "";
+ } catch {}
+ setState({ storageKey, value });
+ }, [storageKey]);
+
+ const visible = state.storageKey === storageKey ? state.value : "";
+ const setValue = (value: string) => {
+ setState({ storageKey, value });
+ try {
+ if (value) window.localStorage.setItem(storageKey, value);
+ else window.localStorage.removeItem(storageKey);
+ } catch {}
+ };
+ return [visible, setValue] as const;
+}
diff --git a/packages/ui/src/chat/use-chat-scroll.ts b/packages/ui/src/chat/use-chat-scroll.ts
new file mode 100644
index 000000000..c4360693b
--- /dev/null
+++ b/packages/ui/src/chat/use-chat-scroll.ts
@@ -0,0 +1,127 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+const BOTTOM_THRESHOLD = 48;
+
+function isAtBottom(viewport: HTMLElement) {
+ return viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight <= BOTTOM_THRESHOLD;
+}
+
+/**
+ * Scroll intent for a growing transcript.
+ *
+ * Live output never opts itself into follow mode. Sending reveals the new turn
+ * once, while Jump to latest is the explicit action that follows subsequent
+ * output. Native scroll anchoring remains enabled so markdown reflow above the
+ * viewport does not displace the sentence a reader is on.
+ */
+export function useChatScroll() {
+ const viewportNodeRef = useRef<HTMLDivElement | null>(null);
+ const contentNodeRef = useRef<HTMLDivElement | null>(null);
+ const [viewportNode, setViewportNode] = useState<HTMLDivElement | null>(null);
+ const [contentNode, setContentNode] = useState<HTMLDivElement | null>(null);
+ const viewportRef = useCallback((node: HTMLDivElement | null) => {
+ viewportNodeRef.current = node;
+ setViewportNode(node);
+ }, []);
+ const contentRef = useCallback((node: HTMLDivElement | null) => {
+ contentNodeRef.current = node;
+ setContentNode(node);
+ }, []);
+ const followLiveRef = useRef(false);
+ const revealFrameRef = useRef<number | null>(null);
+ const [hasContentBelow, setHasContentBelow] = useState(false);
+ const [isFollowingLive, setIsFollowingLive] = useState(false);
+
+ const updateContentBelow = useCallback(() => {
+ const viewport = viewportNodeRef.current;
+ if (!viewport) return;
+ setHasContentBelow(!isAtBottom(viewport));
+ }, []);
+
+ const stopFollowing = useCallback(() => {
+ followLiveRef.current = false;
+ setIsFollowingLive(false);
+ }, []);
+
+ useEffect(() => {
+ const viewport = viewportNode;
+ if (!viewport) return;
+
+ const onScroll = () => {
+ if (!isAtBottom(viewport)) stopFollowing();
+ updateContentBelow();
+ };
+ viewport.addEventListener("scroll", onScroll, { passive: true });
+ return () => viewport.removeEventListener("scroll", onScroll);
+ }, [stopFollowing, updateContentBelow, viewportNode]);
+
+ useEffect(() => {
+ const content = contentNode;
+ if (!content || typeof ResizeObserver === "undefined") return;
+
+ const observer = new ResizeObserver(() => {
+ const viewport = viewportNodeRef.current;
+ if (!viewport) return;
+ if (followLiveRef.current) {
+ viewport.scrollTop = viewport.scrollHeight;
+ }
+ updateContentBelow();
+ });
+ observer.observe(content);
+ return () => observer.disconnect();
+ }, [contentNode, updateContentBelow]);
+
+ useEffect(
+ () => () => {
+ if (revealFrameRef.current !== null) {
+ window.cancelAnimationFrame(revealFrameRef.current);
+ }
+ },
+ [],
+ );
+
+ const revealNewTurn = useCallback(() => {
+ const content = contentNodeRef.current;
+ const existingUserTurns = content?.querySelectorAll('[data-chat-role="user"]').length ?? 0;
+ stopFollowing();
+
+ let attempts = 0;
+ const reveal = () => {
+ const viewport = viewportNodeRef.current;
+ const currentContent = contentNodeRef.current;
+ if (!viewport || !currentContent) return;
+ const userTurns = currentContent.querySelectorAll<HTMLElement>(
+ '[data-chat-role="user"]',
+ );
+ if (userTurns.length > existingUserTurns) {
+ const turn = userTurns[userTurns.length - 1];
+ if (turn) viewport.scrollTop = Math.max(0, turn.offsetTop - 16);
+ updateContentBelow();
+ return;
+ }
+ attempts += 1;
+ if (attempts < 5) revealFrameRef.current = window.requestAnimationFrame(reveal);
+ };
+ revealFrameRef.current = window.requestAnimationFrame(reveal);
+ }, [stopFollowing, updateContentBelow]);
+
+ const jumpToLatest = useCallback(() => {
+ const viewport = viewportNodeRef.current;
+ if (!viewport) return;
+ followLiveRef.current = true;
+ setIsFollowingLive(true);
+ viewport.scrollTop = viewport.scrollHeight;
+ setHasContentBelow(false);
+ }, []);
+
+ return {
+ viewportRef,
+ contentRef,
+ hasContentBelow,
+ isFollowingLive,
+ revealNewTurn,
+ jumpToLatest,
+ };
+}
diff --git a/packages/ui/src/chat/working-orb.tsx b/packages/ui/src/chat/working-orb.tsx
new file mode 100644
index 000000000..0d9b1cc12
--- /dev/null
+++ b/packages/ui/src/chat/working-orb.tsx
@@ -0,0 +1,17 @@
+import { cn } from "../lib/cn";
+
+export function WorkingOrb({ className }: { className?: string }) {
+ return (
+ <span
+ data-working-orb="true"
+ aria-hidden="true"
+ className={cn(
+ "relative inline-block h-4 w-4 shrink-0 rounded-full border border-[var(--color-border-hover)] motion-safe:animate-[pulse_2.4s_ease-in-out_infinite] motion-reduce:animate-none",
+ className,
+ )}
+ >
+ <span className="absolute left-[3px] top-[4px] h-1.5 w-1.5 rounded-full bg-[var(--color-accent-secondary)] opacity-70" />
+ <span className="absolute bottom-[3px] right-[3px] h-1 w-1 rounded-full bg-[var(--color-text-tertiary)] opacity-70" />
+ </span>
+ );
+}
diff --git a/packages/ui/src/shared/code-block.tsx b/packages/ui/src/shared/code-block.tsx
new file mode 100644
index 000000000..39679de00
--- /dev/null
+++ b/packages/ui/src/shared/code-block.tsx
@@ -0,0 +1,105 @@
+"use client";
+
+import { useEffect, useState, type ReactNode } from "react";
+import { Check, Copy } from "lucide-react";
+import { cn } from "../lib/cn";
+
+const highlightedHtml = new Map<string, Promise<string>>();
+
+function highlight(code: string, language: string) {
+ const key = `${language}\u0000${code}`;
+ const cached = highlightedHtml.get(key);
+ if (cached) return cached;
+
+ const pending = import("shiki").then(({ codeToHtml }) =>
+ codeToHtml(code, {
+ lang: language as never,
+ themes: { light: "github-light", dark: "vesper" },
+ defaultColor: false,
+ }),
+ );
+ highlightedHtml.set(key, pending);
+ pending.catch(() => highlightedHtml.delete(key));
+ return pending;
+}
+
+interface CodeFrameProps {
+ code: string;
+ language: string;
+ children: ReactNode;
+ compact?: boolean;
+}
+
+export function CodeFrame({ code, language, children, compact = false }: CodeFrameProps) {
+ const [copied, setCopied] = useState(false);
+
+ async function copy() {
+ await navigator.clipboard.writeText(code);
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 2000);
+ }
+
+ return (
+ <div className="group my-4 min-w-0 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-inset)]">
+ <div className="flex min-h-9 items-center justify-between border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3">
+ <span className="font-mono text-[10px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]">
+ {language || "text"}
+ </span>
+ <button
+ type="button"
+ onClick={() => void copy()}
+ className="inline-flex min-h-8 items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ aria-label="Copy code"
+ >
+ {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
+ {copied ? "Copied" : "Copy"}
+ </button>
+ </div>
+ <div className={cn("min-w-0 overflow-x-auto", compact ? "text-[11px]" : "text-sm")}>{children}</div>
+ </div>
+ );
+}
+
+interface HighlightedCodeBlockProps {
+ code: string;
+ language: string;
+ compact?: boolean;
+ streaming?: boolean;
+}
+
+export function HighlightedCodeBlock({
+ code,
+ language,
+ compact = false,
+ streaming = false,
+}: HighlightedCodeBlockProps) {
+ const [html, setHtml] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (streaming || !language) return;
+ let active = true;
+ void highlight(code, language)
+ .then((value) => {
+ if (active) setHtml(value);
+ })
+ .catch(() => {});
+ return () => {
+ active = false;
+ };
+ }, [code, language, streaming]);
+
+ return (
+ <CodeFrame code={code} language={language} compact={compact}>
+ {!streaming && html ? (
+ <div
+ className="[&>pre]:m-0 [&>pre]:bg-transparent! [&>pre]:p-4"
+ dangerouslySetInnerHTML={{ __html: html }}
+ />
+ ) : (
+ <pre className="m-0 min-w-max p-4">
+ <code className="font-mono text-[var(--color-text-primary)]">{code}</code>
+ </pre>
+ )}
+ </CodeFrame>
+ );
+}
diff --git a/packages/ui/src/shared/markdown.tsx b/packages/ui/src/shared/markdown.tsx
index aa1e23847..6daa6854a 100644
--- a/packages/ui/src/shared/markdown.tsx
+++ b/packages/ui/src/shared/markdown.tsx
@@ -34,6 +34,7 @@ import { lazy, Suspense, useMemo } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { Components } from "react-markdown";
+import { CodeFrame, HighlightedCodeBlock } from "./code-block";
// Mermaid pulls a heavy renderer that is strictly client-side. Lazy-load it so
// it never enters the chat bundle (or SSR pass) unless a reply actually contains
@@ -87,90 +88,82 @@ const SCALES: Record<MarkdownDensity, Scale> = {
},
};
-function buildComponents(s: Scale): Components {
+function buildComponents(s: Scale, streaming: boolean): Components {
+ const measure = s.body === "text-base" ? "max-w-[72ch]" : "max-w-full";
return {
h1: ({ children }) => (
<h1
- className={`${s.h1} font-semibold text-[var(--color-text-primary)]`}
+ className={`${s.h1} ${measure} font-semibold text-[var(--color-text-primary)] [overflow-wrap:anywhere]`}
>
{children}
</h1>
),
h2: ({ children }) => (
<h2
- className={`${s.h2} font-semibold text-[var(--color-text-primary)]`}
+ className={`${s.h2} ${measure} font-semibold text-[var(--color-text-primary)] [overflow-wrap:anywhere]`}
>
{children}
</h2>
),
h3: ({ children }) => (
<h3
- className={`${s.h3} font-semibold text-[var(--color-text-primary)]`}
+ className={`${s.h3} ${measure} font-semibold text-[var(--color-text-primary)] [overflow-wrap:anywhere]`}
>
{children}
</h3>
),
p: ({ children }) => (
<p
- className={`${s.body} ${s.gap} text-[var(--color-text-primary)] leading-relaxed`}
+ className={`${s.body} ${s.gap} ${measure} text-[var(--color-text-primary)] leading-relaxed [overflow-wrap:anywhere]`}
>
{children}
</p>
),
ul: ({ children }) => (
<ul
- className={`list-disc ${s.listIndent} ${s.list} ${s.gap} text-[var(--color-text-primary)]`}
+ className={`list-disc ${s.listIndent} ${s.list} ${s.gap} ${measure} text-[var(--color-text-primary)] [&.contains-task-list]:ml-0 [&.contains-task-list]:list-none`}
>
{children}
</ul>
),
ol: ({ children }) => (
<ol
- className={`list-decimal ${s.listIndent} ${s.list} ${s.gap} text-[var(--color-text-primary)]`}
+ className={`list-decimal ${s.listIndent} ${s.list} ${s.gap} ${measure} text-[var(--color-text-primary)]`}
>
{children}
</ol>
),
- li: ({ children }) => <li className="leading-relaxed">{children}</li>,
- code: ({ className, children, ...props }) => {
- const isBlock = className?.includes("language-");
+ li: ({ children, className }) => <li className={`${className ?? ""} leading-relaxed [overflow-wrap:anywhere] [&>p]:mb-1`}>{children}</li>,
+ input: ({ type, node: _node, ...props }) => type === "checkbox" ? (
+ <input type="checkbox" disabled className="mr-2 align-middle accent-[var(--color-accent-secondary)]" {...props} />
+ ) : <input type={type} {...props} />,
+ code: ({ className, children, node: _node, ...props }) => {
+ const declaredLanguage = className?.match(/language-([^\s]+)/)?.[1];
+ const rawCode = String(children ?? "");
+ const isBlock = Boolean(declaredLanguage) || rawCode.includes("\n");
if (isBlock) {
- const isMermaid = className?.includes("language-mermaid");
- const fence = `${s.block} rounded-lg bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-4 overflow-x-auto`;
- if (isMermaid) {
- const chart = String(children ?? "").replace(/\n$/, "");
+ const language = declaredLanguage ?? "text";
+ const code = rawCode.replace(/\n$/, "");
+ if (language === "mermaid") {
return (
- <Suspense
- fallback={
- <pre className={fence}>
- <code
- className={`${s.code} font-mono text-[var(--color-text-primary)]`}
- >
- {chart}
- </code>
- </pre>
- }
- >
- <MermaidDiagram chart={chart} />
- </Suspense>
+ <CodeFrame code={code} language={language} compact={s.body !== "text-base"}>
+ {streaming ? (
+ <pre className="m-0 min-w-max p-4"><code className="font-mono text-[var(--color-text-primary)]">{code}</code></pre>
+ ) : (
+ <Suspense fallback={<pre className="m-0 min-w-max p-4"><code className="font-mono text-[var(--color-text-primary)]">{code}</code></pre>}>
+ <MermaidDiagram chart={code} />
+ </Suspense>
+ )}
+ </CodeFrame>
);
}
- return (
- <pre className={fence}>
- <code
- className={`${s.code} font-mono text-[var(--color-text-primary)]`}
- {...props}
- >
- {children}
- </code>
- </pre>
- );
+ return <HighlightedCodeBlock code={code} language={language} compact={s.body !== "text-base"} streaming={streaming} />;
}
// 0.85em, relative: Geist Mono runs wider and taller than Geist at the
// same nominal size, so 1em mono inside 16px sans reads oversized.
return (
<code
- className="rounded px-1 py-0.5 bg-[var(--color-bg-inset)] text-[var(--color-text-primary)] text-[0.85em] font-mono"
+ className="break-all whitespace-normal rounded px-1 py-0.5 bg-[var(--color-bg-inset)] text-[var(--color-text-primary)] text-[0.85em] font-mono [overflow-wrap:anywhere]"
{...props}
>
{children}
@@ -180,7 +173,7 @@ function buildComponents(s: Scale): Components {
pre: ({ children }) => <>{children}</>,
blockquote: ({ children }) => (
<blockquote
- className={`${s.block} ${s.body} border-l-2 border-[var(--color-border-default)] pl-4 text-[var(--color-text-secondary)]`}
+ className={`${s.block} ${s.body} ${measure} border-l-2 border-[var(--color-border-default)] pl-4 text-[var(--color-text-secondary)] [overflow-wrap:anywhere]`}
>
{children}
</blockquote>
@@ -188,7 +181,7 @@ function buildComponents(s: Scale): Components {
a: ({ href, children }) => (
<a
href={href}
- className="text-[var(--color-accent-primary)] hover:underline"
+ className="text-[var(--color-accent-primary)] underline underline-offset-2 [overflow-wrap:anywhere]"
target="_blank"
rel="noopener noreferrer"
>
@@ -196,8 +189,8 @@ function buildComponents(s: Scale): Components {
</a>
),
table: ({ children }) => (
- <div className={`${s.block} overflow-x-auto`}>
- <table className={`${s.code} w-full border-collapse`}>{children}</table>
+ <div className={`${s.block} max-w-full overflow-x-auto overscroll-x-contain border-y border-[var(--color-border-default)]`}>
+ <table className={`${s.code} w-full min-w-[640px] border-collapse`}>{children}</table>
</div>
),
thead: ({ children }) => (
@@ -206,7 +199,7 @@ function buildComponents(s: Scale): Components {
</thead>
),
th: ({ children }) => (
- <th className={`text-left px-3 py-2 font-normal ${MICRO_LABEL}`}>
+ <th scope="col" className={`text-left px-3 py-2.5 font-normal ${MICRO_LABEL}`}>
{children}
</th>
),
@@ -216,7 +209,7 @@ function buildComponents(s: Scale): Components {
</tr>
),
td: ({ children }) => (
- <td className="px-3 py-2 text-[var(--color-text-primary)] tabular-nums">
+ <td className="px-3 py-2.5 align-top text-[var(--color-text-primary)] tabular-nums [overflow-wrap:anywhere]">
{children}
</td>
),
@@ -235,12 +228,14 @@ export interface MarkdownProps {
content: string;
/** `compact` keeps chrome sizes for narrow panels. */
density?: MarkdownDensity;
+ /** Defers expensive code/diagram rendering until the answer is complete. */
+ streaming?: boolean;
}
-export function Markdown({ content, density = "reading" }: MarkdownProps) {
+export function Markdown({ content, density = "reading", streaming = false }: MarkdownProps) {
const components = useMemo(
- () => buildComponents(SCALES[density]),
- [density],
+ () => buildComponents(SCALES[density], streaming),
+ [density, streaming],
);
return (
<ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
diff --git a/packages/ui/src/ui/scroll-area.tsx b/packages/ui/src/ui/scroll-area.tsx
index ffb6026e9..cafe216bc 100644
--- a/packages/ui/src/ui/scroll-area.tsx
+++ b/packages/ui/src/ui/scroll-area.tsx
@@ -4,16 +4,25 @@ import * as React from "react";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import { cn } from "../lib/cn";
+interface ScrollAreaProps
+ extends React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> {
+ viewportRef?: React.Ref<HTMLDivElement>;
+ viewportClassName?: string;
+}
+
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
- React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
->(({ className, children, ...props }, ref) => (
+ ScrollAreaProps
+>(({ className, children, viewportRef, viewportClassName, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
- <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
+ <ScrollAreaPrimitive.Viewport
+ ref={viewportRef}
+ className={cn("h-full w-full rounded-[inherit]", viewportClassName)}
+ >
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
diff --git a/packages/web/src/components/chat/chat-interface.test.tsx b/packages/web/src/components/chat/chat-interface.test.tsx
new file mode 100644
index 000000000..c714685c2
--- /dev/null
+++ b/packages/web/src/components/chat/chat-interface.test.tsx
@@ -0,0 +1,70 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { render, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ChatInterface } from "./chat-interface";
+
+const mocks = vi.hoisted(() => ({
+ reset: vi.fn(),
+ loadConversation: vi.fn(),
+ sendMessage: vi.fn(),
+ replace: vi.fn(),
+ push: vi.fn(),
+ conversation: null as string | null,
+ activeConversation: null as string | null,
+}));
+
+vi.mock("next/navigation", () => ({
+ usePathname: () => "/repos/r1/chat",
+ useRouter: () => ({ replace: mocks.replace, push: mocks.push }),
+ useSearchParams: () => new URLSearchParams(
+ mocks.conversation ? `conversation=${mocks.conversation}` : "",
+ ),
+}));
+vi.mock("swr", () => ({ default: () => ({ data: undefined }) }));
+vi.mock("next/link", () => ({ default: ({ children }: { children: React.ReactNode }) => <>{children}</> }));
+vi.mock("@repowise-dev/ui/chat/chat-interface", () => ({ ChatInterface: () => <div /> }));
+vi.mock("./model-selector", () => ({ ModelSelector: () => <div /> }));
+vi.mock("./conversation-history", () => ({ ConversationHistory: () => <div /> }));
+vi.mock("./repository-chat-provider", () => ({
+ useRepositoryChat: () => ({
+ messages: [], conversationId: mocks.activeConversation, isStreaming: false, error: null,
+ sendMessage: mocks.sendMessage, loadConversation: mocks.loadConversation,
+ cancel: vi.fn(), reset: mocks.reset,
+ pageContext: { kind: "chat", label: "Chat" },
+ selectedProvider: null, selectedModel: null, selectModel: vi.fn(),
+ }),
+}));
+
+describe("chat route conversation lifecycle", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.conversation = null;
+ mocks.activeConversation = null;
+ });
+
+ it("starts a fresh conversation on the plain chat URL", async () => {
+ render(<ChatInterface repoId="r1" />);
+ await waitFor(() => expect(mocks.reset).toHaveBeenCalledOnce());
+ expect(mocks.loadConversation).not.toHaveBeenCalled();
+ });
+
+ it("restores only the conversation named by the URL", async () => {
+ mocks.conversation = "c42";
+ render(<ChatInterface repoId="r1" />);
+ await waitFor(() => expect(mocks.loadConversation).toHaveBeenCalledWith("c42"));
+ expect(mocks.reset).not.toHaveBeenCalled();
+ });
+
+ it("does not reload a newly completed conversation when its id is written to the URL", async () => {
+ const view = render(<ChatInterface repoId="r1" />);
+ await waitFor(() => expect(mocks.reset).toHaveBeenCalledOnce());
+ mocks.activeConversation = "c-new";
+ view.rerender(<ChatInterface repoId="r1" />);
+ await waitFor(() => expect(mocks.replace).toHaveBeenCalledWith("/repos/r1/chat?conversation=c-new"));
+ mocks.conversation = "c-new";
+ view.rerender(<ChatInterface repoId="r1" />);
+ expect(mocks.loadConversation).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index dc7135fb5..1e7b52d36 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -1,13 +1,16 @@
"use client";
-import { useEffect, useRef } from "react";
+import React, { useCallback, useEffect, useRef } from "react";
import useSWR from "swr";
import Link from "next/link";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { ChatInterface as ChatInterfaceShell } from "@repowise-dev/ui/chat/chat-interface";
+import { useChatDraft } from "@repowise-dev/ui/chat";
import { pageHref } from "@/lib/utils/page-href";
-import { listConversations } from "@/lib/api/chat";
import { getProviders } from "@/lib/api/providers";
import { getRepoStats } from "@/lib/api/repos";
+import { forkConversation } from "@/lib/api/chat";
+import type { ChatUIMessage } from "@repowise-dev/types/chat";
import { ModelSelector } from "./model-selector";
import { ConversationHistory } from "./conversation-history";
import { useRepositoryChat } from "./repository-chat-provider";
@@ -40,7 +43,17 @@ export function ChatInterface({
cancel,
reset,
pageContext,
+ selectedProvider,
+ selectedModel,
+ selectModel,
} = useRepositoryChat();
+ const pathname = usePathname();
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const urlConversationId = searchParams.get("conversation");
+ const [draft, setDraft] = useChatDraft(
+ `repowise:chat-draft:${repoId}:${urlConversationId ?? conversationId ?? "new"}`,
+ );
// Provider guard: surface "no chat provider configured" BEFORE the first
// send instead of erroring after.
@@ -59,48 +72,95 @@ export function ChatInterface({
{ revalidateOnFocus: false },
);
- // Fire the seeded question exactly once (guards StrictMode double-effects).
- const seededRef = useRef(false);
+ // A plain /chat URL is an explicit fresh workspace. Only an addressable
+ // conversation URL restores history, which keeps returning users from being
+ // dropped at the bottom of an old answer they did not choose to reopen.
+ const lifecycleRef = useRef("");
+ const awaitingFreshIdRef = useRef(false);
useEffect(() => {
- if (!initialQuestion || seededRef.current) return;
- seededRef.current = true;
- void sendMessage(initialQuestion);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [initialQuestion]);
+ const identity = `${repoId}:${urlConversationId ?? "new"}:${initialQuestion ?? ""}`;
+ if (lifecycleRef.current === identity) return;
+ lifecycleRef.current = identity;
+ if (urlConversationId) {
+ awaitingFreshIdRef.current = false;
+ if (urlConversationId !== conversationId) {
+ void loadConversation(urlConversationId);
+ }
+ return;
+ }
+ awaitingFreshIdRef.current = true;
+ reset();
+ if (initialQuestion) void sendMessage(initialQuestion, {
+ context: pageContext,
+ ...(selectedProvider ? { provider: selectedProvider } : {}),
+ ...(selectedModel ? { model: selectedModel } : {}),
+ });
+ }, [conversationId, initialQuestion, loadConversation, pageContext, repoId, reset, selectedModel, selectedProvider, sendMessage, urlConversationId]);
- // Resume the most recent conversation when landing on a blank chat (no
- // seeded question). Once only; "New conversation" still resets cleanly.
- const resumedRef = useRef(false);
useEffect(() => {
- if (resumedRef.current || seededRef.current || initialQuestion) return;
- if (messages.length > 0 || conversationId) return;
- resumedRef.current = true;
- void (async () => {
- try {
- const conversations = await listConversations(repoId);
- const latest = conversations[0];
- if (latest && latest.message_count > 0) {
- await loadConversation(latest.id);
- }
- } catch {
- // Resume is best-effort; a blank chat is a fine fallback.
- }
- })();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [repoId]);
+ if (!awaitingFreshIdRef.current || !conversationId) return;
+ awaitingFreshIdRef.current = false;
+ const next = new URLSearchParams(searchParams.toString());
+ next.delete("q");
+ next.set("conversation", conversationId);
+ router.replace(`${pathname}?${next.toString()}`);
+ }, [conversationId, pathname, router, searchParams]);
+
+ const selectConversation = useCallback(
+ (id: string) => router.push(`${pathname}?conversation=${encodeURIComponent(id)}`),
+ [pathname, router],
+ );
+ const newConversation = useCallback(() => router.push(pathname), [pathname, router]);
+ const buildCitationHref = useCallback(
+ (source: { pageId: string }) => pageHref(repoId, source.pageId),
+ [repoId],
+ );
+ const sendWithConversationModel = useCallback((text: string) => sendMessage(text, {
+ context: pageContext,
+ ...(selectedProvider ? { provider: selectedProvider } : {}),
+ ...(selectedModel ? { model: selectedModel } : {}),
+ }), [pageContext, selectedModel, selectedProvider, sendMessage]);
+ const retryMessage = useCallback((message: ChatUIMessage) => {
+ const index = messages.findIndex((candidate) => candidate.id === message.id);
+ const previousUser = messages.slice(0, index).reverse().find((candidate) => candidate.role === "user");
+ if (previousUser) return sendWithConversationModel(previousUser.text);
+ }, [messages, sendWithConversationModel]);
+ const editAndResend = useCallback(async (message: ChatUIMessage, text: string) => {
+ if (!conversationId || !message.serverId) return;
+ const fork = await forkConversation(repoId, conversationId, { beforeMessageId: message.serverId });
+ await loadConversation(fork.id);
+ router.push(`${pathname}?conversation=${encodeURIComponent(fork.id)}`);
+ await sendWithConversationModel(text);
+ }, [conversationId, loadConversation, pathname, repoId, router, sendWithConversationModel]);
return (
- <ChatInterfaceShell
+ <div className="flex h-full min-h-0 overflow-hidden">
+ <ConversationHistory
+ repoId={repoId}
+ activeConversationId={conversationId}
+ onSelect={selectConversation}
+ onNew={newConversation}
+ variant="rail"
+ collapsible
+ railPreferenceKey={`repowise:chat-history-rail:${repoId}`}
+ className="hidden h-full shrink-0 overflow-hidden transition-[width] duration-150 lg:block lg:data-[collapsed=true]:w-12 lg:data-[collapsed=false]:w-64 2xl:data-[collapsed=false]:w-72 motion-reduce:transition-none"
+ />
+ <div className="h-full min-h-0 min-w-0 flex-1">
+ <ChatInterfaceShell
repoId={repoId}
{...(repoName !== undefined ? { repoName } : {})}
context={pageContext}
messages={messages}
isStreaming={isStreaming}
error={error}
- onSend={(text) => sendMessage(text, { context: pageContext })}
+ onSend={sendWithConversationModel}
onCancel={cancel}
- buildCitationHref={(s) => pageHref(repoId, s.pageId)}
- modelSelectorSlot={<ModelSelector repoId={repoId} />}
+ draft={draft}
+ onDraftChange={setDraft}
+ buildCitationHref={buildCitationHref}
+ modelSelectorSlot={<ModelSelector repoId={repoId} activeProvider={selectedProvider} activeModel={selectedModel} onSelect={selectModel} />}
+ onRetry={retryMessage}
+ onEditAndResend={editAndResend}
statusSlot={
// Orientation, in one line: what was indexed, and which commit it was
// indexed from. The branch and SHA used to sit in a second page header
@@ -133,13 +193,17 @@ export function ChatInterface({
</span>
}
historySlot={
- <ConversationHistory
- repoId={repoId}
- activeConversationId={conversationId}
- onSelect={loadConversation}
- onNew={reset}
- />
+ <div className="lg:hidden">
+ <ConversationHistory
+ repoId={repoId}
+ activeConversationId={conversationId}
+ onSelect={selectConversation}
+ onNew={newConversation}
+ />
+ </div>
}
/>
+ </div>
+ </div>
);
}
diff --git a/packages/web/src/components/chat/conversation-history.tsx b/packages/web/src/components/chat/conversation-history.tsx
index 397c64d7d..d8b17bfb4 100644
--- a/packages/web/src/components/chat/conversation-history.tsx
+++ b/packages/web/src/components/chat/conversation-history.tsx
@@ -1,8 +1,15 @@
"use client";
+import { useState } from "react";
import useSWR from "swr";
import { ConversationHistory as ConversationHistoryShell } from "@repowise-dev/ui/chat/conversation-history";
-import { listConversations, deleteConversation } from "@/lib/api/chat";
+import {
+ deleteConversation,
+ forkConversation,
+ listConversations,
+ restoreConversation,
+ updateConversation,
+} from "@/lib/api/chat";
import type { ConversationResponse } from "@/lib/api/types";
interface Props {
@@ -10,6 +17,10 @@ interface Props {
activeConversationId: string | null;
onSelect: (id: string) => void;
onNew: () => void;
+ variant?: "popover" | "rail";
+ collapsible?: boolean;
+ railPreferenceKey?: string;
+ className?: string;
}
export function ConversationHistoryWrapper({
@@ -17,7 +28,12 @@ export function ConversationHistoryWrapper({
activeConversationId,
onSelect,
onNew,
+ variant = "popover",
+ collapsible = false,
+ railPreferenceKey,
+ className,
}: Props) {
+ const [deleted, setDeleted] = useState<{ id: string; title: string } | null>(null);
const { data: conversations, isLoading, mutate } = useSWR<
ConversationResponse[]
>(`chat-convs:${repoId}`, () => listConversations(repoId), {
@@ -25,7 +41,10 @@ export function ConversationHistoryWrapper({
});
async function handleDelete(convId: string) {
+ const conversation = conversations?.find((item) => item.id === convId);
await deleteConversation(repoId, convId);
+ if (conversation) setDeleted({ id: convId, title: conversation.title });
+ if (convId === activeConversationId) onNew();
await mutate();
}
@@ -37,6 +56,17 @@ export function ConversationHistoryWrapper({
onSelect={onSelect}
onDelete={handleDelete}
onNew={onNew}
+ variant={variant}
+ collapsible={collapsible}
+ {...(railPreferenceKey ? { railPreferenceKey } : {})}
+ className={className}
+ onRename={async (id, title) => { await updateConversation(repoId, id, { title }); await mutate(); }}
+ onPin={async (id, pinned) => { await updateConversation(repoId, id, { pinned }); await mutate(); }}
+ onFork={async (id) => { const fork = await forkConversation(repoId, id); await mutate(); onSelect(fork.id); }}
+ {...(deleted ? { undoDelete: {
+ title: deleted.title,
+ onUndo: async () => { await restoreConversation(repoId, deleted.id); setDeleted(null); await mutate(); },
+ } } : {})}
/>
);
}
diff --git a/packages/web/src/components/chat/model-selector.tsx b/packages/web/src/components/chat/model-selector.tsx
index 47e66e66f..af5dcb2bd 100644
--- a/packages/web/src/components/chat/model-selector.tsx
+++ b/packages/web/src/components/chat/model-selector.tsx
@@ -3,24 +3,32 @@
import { ModelSelector as ModelSelectorShell } from "@repowise-dev/ui/chat/model-selector";
import { useProviders } from "@/lib/hooks/use-providers";
-export function ModelSelector({ repoId }: { repoId?: string }) {
+export function ModelSelector({
+ repoId,
+ activeProvider: controlledProvider,
+ activeModel: controlledModel,
+ onSelect,
+}: {
+ repoId?: string;
+ activeProvider?: string | null;
+ activeModel?: string | null;
+ onSelect?: (provider: string, model: string) => void;
+}) {
const {
providers,
activeProvider,
activeModel,
isLoading,
- activate,
- saveKey,
} = useProviders(repoId);
return (
<ModelSelectorShell
providers={providers}
- activeProvider={activeProvider}
- activeModel={activeModel}
+ activeProvider={controlledProvider ?? activeProvider}
+ activeModel={controlledModel ?? activeModel}
isLoading={isLoading}
- onActivate={(id, model) => activate(id, model)}
- onSaveKey={saveKey}
+ onActivate={(id, model) => onSelect?.(id, model)}
+ settingsHref="/settings"
/>
);
}
diff --git a/packages/web/src/components/chat/repository-chat-dock.test.tsx b/packages/web/src/components/chat/repository-chat-dock.test.tsx
index 43e90e5fa..a2bc60aa6 100644
--- a/packages/web/src/components/chat/repository-chat-dock.test.tsx
+++ b/packages/web/src/components/chat/repository-chat-dock.test.tsx
@@ -21,6 +21,9 @@ vi.mock("./repository-chat-provider", () => ({
sendMessage: vi.fn(),
loadConversation: vi.fn(),
reset: vi.fn(),
+ selectedProvider: null,
+ selectedModel: null,
+ selectModel: vi.fn(),
}),
}));
diff --git a/packages/web/src/components/chat/repository-chat-dock.tsx b/packages/web/src/components/chat/repository-chat-dock.tsx
index 382e6b38d..733cba25c 100644
--- a/packages/web/src/components/chat/repository-chat-dock.tsx
+++ b/packages/web/src/components/chat/repository-chat-dock.tsx
@@ -45,17 +45,25 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
return (
<ChatDock
- storageKey={`repowise:chat-dock:${chat.repoId}`}
+ storageKey={`repowise:chat-dock:${chat.repoId}:${chat.conversationId ?? "new"}`}
repoId={chat.repoId}
repoName={chat.repoName}
context={chat.pageContext}
messages={chat.messages}
isStreaming={chat.isStreaming}
error={chat.error}
- onSend={(text, context) => chat.sendMessage(text, { context })}
+ onSend={(text, context) => chat.sendMessage(text, {
+ context,
+ ...(chat.selectedProvider ? { provider: chat.selectedProvider } : {}),
+ ...(chat.selectedModel ? { model: chat.selectedModel } : {}),
+ })}
onCancel={chat.cancel}
buildCitationHref={(source) => pageHref(chat.repoId, source.pageId)}
- onOpenFullChat={() => router.push(`/repos/${chat.repoId}/chat`)}
+ onOpenFullChat={() => router.push(
+ chat.conversationId
+ ? `/repos/${chat.repoId}/chat?conversation=${encodeURIComponent(chat.conversationId)}`
+ : `/repos/${chat.repoId}/chat`,
+ )}
{...(collisionInset ? { collisionInset } : {})}
sendDisabled={!anyConfigured}
sendDisabledReason={
@@ -70,7 +78,7 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
.
</span>
}
- modelSelectorSlot={<ModelSelector repoId={chat.repoId} />}
+ modelSelectorSlot={<ModelSelector repoId={chat.repoId} activeProvider={chat.selectedProvider} activeModel={chat.selectedModel} onSelect={chat.selectModel} />}
historySlot={
<ConversationHistory
repoId={chat.repoId}
diff --git a/packages/web/src/components/chat/repository-chat-provider.tsx b/packages/web/src/components/chat/repository-chat-provider.tsx
index aac994ad6..4a2cbcbf2 100644
--- a/packages/web/src/components/chat/repository-chat-provider.tsx
+++ b/packages/web/src/components/chat/repository-chat-provider.tsx
@@ -2,8 +2,11 @@
import {
createContext,
+ useCallback,
+ useEffect,
useContext,
useMemo,
+ useState,
type ReactNode,
} from "react";
import { usePathname, useSearchParams } from "next/navigation";
@@ -17,6 +20,9 @@ export interface RepositoryChatValue extends ChatController {
repoId: string;
repoName: string;
pageContext: PageChatContext;
+ selectedProvider: string | null;
+ selectedModel: string | null;
+ selectModel: (provider: string, model: string) => void;
}
const RepositoryChatContext = createContext<RepositoryChatValue | null>(null);
@@ -31,6 +37,31 @@ export function RepositoryChatProvider({
children: ReactNode;
}) {
const chat = useChat(repoId);
+ const [modelSelection, setModelSelection] = useState<{ provider: string; model: string } | null>(null);
+ const modelIdentity = chat.conversationId ?? "new";
+ useEffect(() => {
+ const storageKey = `repowise:chat-model:${repoId}:${modelIdentity}`;
+ try {
+ const stored = JSON.parse(window.localStorage.getItem(storageKey) ?? "null") as typeof modelSelection;
+ if (stored?.provider && stored.model) setModelSelection(stored);
+ else {
+ const lastAssistant = [...chat.messages].reverse().find((message) => message.role === "assistant" && message.provider && message.model);
+ setModelSelection(lastAssistant?.provider && lastAssistant.model ? { provider: lastAssistant.provider, model: lastAssistant.model } : null);
+ }
+ } catch {
+ setModelSelection(null);
+ }
+ // Deliberately keyed to conversation identity, not streaming message updates.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [modelIdentity, repoId]);
+
+ const selectModel = useCallback((provider: string, model: string) => {
+ const selection = { provider, model };
+ setModelSelection(selection);
+ try {
+ window.localStorage.setItem(`repowise:chat-model:${repoId}:${modelIdentity}`, JSON.stringify(selection));
+ } catch {}
+ }, [modelIdentity, repoId]);
const pathname = usePathname();
const searchParams = useSearchParams();
const pageContext = useMemo(
@@ -52,6 +83,9 @@ export function RepositoryChatProvider({
repoId,
repoName,
pageContext,
+ selectedProvider: modelSelection?.provider ?? null,
+ selectedModel: modelSelection?.model ?? null,
+ selectModel,
messages,
conversationId,
isStreaming,
@@ -73,6 +107,8 @@ export function RepositoryChatProvider({
loadConversation,
cancel,
reset,
+ modelSelection,
+ selectModel,
],
);
diff --git a/packages/web/src/components/layout/page-transition.test.tsx b/packages/web/src/components/layout/page-transition.test.tsx
new file mode 100644
index 000000000..8a4cd4c09
--- /dev/null
+++ b/packages/web/src/components/layout/page-transition.test.tsx
@@ -0,0 +1,41 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { PageTransition } from "./page-transition";
+
+const navigation = vi.hoisted(() => ({ pathname: "/repos/r1/chat" }));
+
+vi.mock("next/navigation", () => ({ usePathname: () => navigation.pathname }));
+vi.mock("framer-motion", () => ({
+ AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ motion: {
+ div: ({ children, initial: _initial, animate: _animate, exit: _exit, transition: _transition, ...props }: React.HTMLAttributes<HTMLDivElement> & { initial?: unknown; animate?: unknown; exit?: unknown; transition?: unknown }) => (
+ <div data-testid="transition" {...props}>{children}</div>
+ ),
+ },
+}));
+
+afterEach(cleanup);
+
+describe("PageTransition", () => {
+ it("locks the chat workspace to the available viewport", () => {
+ render(<PageTransition>Chat</PageTransition>);
+ expect(screen.getByTestId("transition").className).toContain("min-h-0");
+ expect(screen.getByTestId("transition").className).toContain("overflow-hidden");
+ });
+
+ it("locks the Docs reader so its tree and article scroll independently", () => {
+ navigation.pathname = "/repos/r1/docs";
+ render(<PageTransition>Docs</PageTransition>);
+ expect(screen.getByTestId("transition").className).toContain("min-h-0");
+ expect(screen.getByTestId("transition").className).toContain("overflow-hidden");
+ });
+
+ it("keeps ordinary document routes eligible for main-page scrolling", () => {
+ navigation.pathname = "/repos/r1/files";
+ render(<PageTransition>Files</PageTransition>);
+ expect(screen.getByTestId("transition").className).not.toContain("overflow-hidden");
+ });
+});
diff --git a/packages/web/src/components/layout/page-transition.tsx b/packages/web/src/components/layout/page-transition.tsx
index 6db2e5a93..517eaba9f 100644
--- a/packages/web/src/components/layout/page-transition.tsx
+++ b/packages/web/src/components/layout/page-transition.tsx
@@ -1,8 +1,10 @@
"use client";
+import React from "react";
import { usePathname } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import type { ReactNode } from "react";
+import { cn } from "@repowise-dev/ui/lib/cn";
interface PageTransitionProps {
children: ReactNode;
@@ -10,6 +12,7 @@ interface PageTransitionProps {
export function PageTransition({ children }: PageTransitionProps) {
const pathname = usePathname();
+ const isInternallyScrolledWorkspace = /\/repos\/[^/]+\/(?:chat|docs)\/?$/.test(pathname);
return (
<AnimatePresence mode="wait" initial={false}>
@@ -21,10 +24,11 @@ export function PageTransition({ children }: PageTransitionProps) {
transition={{ duration: 0.15, ease: "easeOut" }}
// `flex-1`, not `h-full`. `main` is a flex column, so this claims the
// space left over after the route layout's banners instead of 100% of
- // `main` regardless of them. Deliberately no `min-h-0`: the default
- // `min-height: auto` keeps a page taller than the viewport able to
- // grow and scroll `main`, which is what every document page relies on.
- className="flex-1"
+ // `main` regardless of them. Most pages deliberately keep the default
+ // `min-height: auto`, which lets a page taller than the viewport
+ // grow and scroll `main`. Chat and the Docs reader are bounded
+ // workspaces with their own scroll regions, so they opt out.
+ className={cn("flex-1", isInternallyScrolledWorkspace && "min-h-0 overflow-hidden")}
>
{children}
</motion.div>
diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.ts b/packages/web/src/lib/chat/to-chat-ui-messages.ts
index ee1aaa076..3f43d2968 100644
--- a/packages/web/src/lib/chat/to-chat-ui-messages.ts
+++ b/packages/web/src/lib/chat/to-chat-ui-messages.ts
@@ -30,5 +30,7 @@ export function toChatUiMessages(
status: "done" as const,
})),
isStreaming: false,
+ ...(message.content.provider ? { provider: message.content.provider } : {}),
+ ...(message.content.model ? { model: message.content.model } : {}),
}));
}
diff --git a/packages/web/src/lib/hooks/use-chat.test.tsx b/packages/web/src/lib/hooks/use-chat.test.tsx
index 23c1593ec..c4324ccd3 100644
--- a/packages/web/src/lib/hooks/use-chat.test.tsx
+++ b/packages/web/src/lib/hooks/use-chat.test.tsx
@@ -1,25 +1,33 @@
// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { useChat } from "./use-chat";
const mocks = vi.hoisted(() => ({
signal: undefined as AbortSignal | undefined,
getConversation: vi.fn(),
+ postChatMessage: vi.fn(),
}));
vi.mock("@/lib/api/chat", () => ({
getConversation: mocks.getConversation,
- postChatMessage: vi.fn(
- (_repoId: string, options: { signal?: AbortSignal }) => {
- mocks.signal = options.signal;
- return new Promise<Response>(() => undefined);
- },
- ),
+ postChatMessage: mocks.postChatMessage,
}));
describe("useChat lifecycle", () => {
+ beforeEach(() => {
+ mocks.signal = undefined;
+ mocks.getConversation.mockReset();
+ mocks.postChatMessage.mockReset();
+ mocks.postChatMessage.mockImplementation(
+ (_repoId: string, options: { signal?: AbortSignal }) => {
+ mocks.signal = options.signal;
+ return new Promise<Response>(() => undefined);
+ },
+ );
+ });
+
it("aborts an in-flight request when its repository owner unmounts", () => {
const { result, unmount } = renderHook(() => useChat("r1"));
@@ -68,6 +76,54 @@ describe("useChat lifecycle", () => {
expect(result.current.isStreaming).toBe(false);
});
+ it("buffers rapid text deltas until the next animation frame", async () => {
+ let frame: FrameRequestCallback | undefined;
+ vi.stubGlobal(
+ "requestAnimationFrame",
+ vi.fn((callback: FrameRequestCallback) => {
+ frame = callback;
+ return 1;
+ }),
+ );
+ vi.stubGlobal("cancelAnimationFrame", vi.fn());
+ let streamController!: ReadableStreamDefaultController<Uint8Array>;
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ streamController = controller;
+ },
+ });
+ mocks.postChatMessage.mockImplementationOnce(
+ (_repoId: string, options: { signal?: AbortSignal }) => {
+ mocks.signal = options.signal;
+ return Promise.resolve(new Response(stream));
+ },
+ );
+ const { result } = renderHook(() => useChat("r1"));
+
+ act(() => {
+ void result.current.sendMessage("Explain this page");
+ });
+ await act(async () => {
+ streamController.enqueue(
+ new TextEncoder().encode(
+ ["a", "b", "c"]
+ .map((text) => `data: ${JSON.stringify({ type: "text_delta", text })}\n`)
+ .join(""),
+ ),
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(result.current.messages.at(-1)?.text).toBe("");
+ expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
+ act(() => frame?.(16));
+ expect(result.current.messages.at(-1)?.text).toBe("abc");
+
+ act(() => result.current.cancel());
+ vi.unstubAllGlobals();
+ });
+
it.each(["resolve", "reject"] as const)(
"ignores a late conversation %s from the previous repository",
async (outcome) => {
@@ -112,4 +168,39 @@ describe("useChat lifecycle", () => {
expect(result.current.error).toBeNull();
},
);
+
+ it("lets only the newest conversation load update state", async () => {
+ let resolveFirst!: (value: unknown) => void;
+ let resolveSecond!: (value: unknown) => void;
+ mocks.getConversation
+ .mockReturnValueOnce(new Promise((resolve) => { resolveFirst = resolve; }))
+ .mockReturnValueOnce(new Promise((resolve) => { resolveSecond = resolve; }));
+ const { result } = renderHook(() => useChat("r1"));
+ let first!: Promise<void>;
+ let second!: Promise<void>;
+ act(() => {
+ first = result.current.loadConversation("c1");
+ second = result.current.loadConversation("c2");
+ });
+ const response = (id: string, text: string) => ({ messages: [{ id: `m-${id}`, conversation_id: id, role: "assistant", content: { text }, created_at: "2026-08-28T00:00:00Z" }] });
+ await act(async () => { resolveSecond(response("c2", "newest")); await second; });
+ await act(async () => { resolveFirst(response("c1", "stale")); await first; });
+ expect(result.current.conversationId).toBe("c2");
+ expect(result.current.messages[0]?.text).toBe("newest");
+ });
+
+ it("does not restore a load that resolves after reset", async () => {
+ let resolveLoad!: (value: unknown) => void;
+ mocks.getConversation.mockReturnValueOnce(new Promise((resolve) => { resolveLoad = resolve; }));
+ const { result } = renderHook(() => useChat("r1"));
+ let loading!: Promise<void>;
+ act(() => { loading = result.current.loadConversation("c1"); });
+ act(() => result.current.reset());
+ await act(async () => {
+ resolveLoad({ messages: [{ id: "m1", conversation_id: "c1", role: "assistant", content: { text: "stale" }, created_at: "2026-08-28T00:00:00Z" }] });
+ await loading;
+ });
+ expect(result.current.messages).toEqual([]);
+ expect(result.current.conversationId).toBeNull();
+ });
});
diff --git a/packages/web/src/lib/hooks/use-chat.ts b/packages/web/src/lib/hooks/use-chat.ts
index 978bbe860..3acaf910c 100644
--- a/packages/web/src/lib/hooks/use-chat.ts
+++ b/packages/web/src/lib/hooks/use-chat.ts
@@ -27,6 +27,16 @@ const EMPTY_CHAT_STATE: UseChatState = {
error: null,
};
+function stopRunningTools(message: ChatMessage, summary: string): ChatMessage {
+ return {
+ ...message,
+ isStreaming: false,
+ toolCalls: message.toolCalls.map((tool) =>
+ tool.status === "running" ? { ...tool, status: "error" as const, summary } : tool,
+ ),
+ };
+}
+
// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
@@ -36,12 +46,16 @@ export function useChat(repoId: string) {
const abortRef = useRef<AbortController | null>(null);
const activeRepoRef = useRef(repoId);
+ const conversationIdRef = useRef<string | null>(null);
+ const loadRequestRef = useRef(0);
useEffect(() => {
if (activeRepoRef.current !== repoId) {
abortRef.current?.abort();
abortRef.current = null;
+ loadRequestRef.current += 1;
activeRepoRef.current = repoId;
+ conversationIdRef.current = null;
setState(EMPTY_CHAT_STATE);
}
return () => abortRef.current?.abort();
@@ -53,11 +67,44 @@ export function useChat(repoId: string) {
opts?: { provider?: string; model?: string; context?: ChatContext },
) => {
abortRef.current?.abort();
+ loadRequestRef.current += 1;
const abort = new AbortController();
abortRef.current = abort;
const userMsgId = `user-${Date.now()}`;
const asstMsgId = `asst-${Date.now()}`;
+ let pendingText = "";
+ let textFrame: number | null = null;
+
+ const flushText = () => {
+ if (textFrame !== null) {
+ window.cancelAnimationFrame(textFrame);
+ textFrame = null;
+ }
+ if (!pendingText || abort.signal.aborted || activeRepoRef.current !== repoId) {
+ pendingText = "";
+ return;
+ }
+ const text = pendingText;
+ pendingText = "";
+ setState((prev) => ({
+ ...prev,
+ messages: prev.messages.map((message) =>
+ message.id === asstMsgId
+ ? { ...message, text: message.text + text }
+ : message,
+ ),
+ }));
+ };
+
+ const queueText = (text: string) => {
+ pendingText += text;
+ if (textFrame !== null) return;
+ textFrame = window.requestAnimationFrame(() => {
+ textFrame = null;
+ flushText();
+ });
+ };
setState((prev) => ({
...prev,
@@ -94,7 +141,7 @@ export function useChat(repoId: string) {
message: text,
conversationId:
activeRepoRef.current === repoId
- ? state.conversationId ?? undefined
+ ? conversationIdRef.current ?? undefined
: undefined,
provider: opts?.provider,
model: opts?.model,
@@ -131,6 +178,7 @@ export function useChat(repoId: string) {
}
}
} catch (err: unknown) {
+ if (textFrame !== null) window.cancelAnimationFrame(textFrame);
if (!abort.signal.aborted) {
settled = true;
setState((prev) => ({
@@ -138,13 +186,14 @@ export function useChat(repoId: string) {
isStreaming: false,
error: toFriendlyMessage(err),
messages: prev.messages.map((m) =>
- m.id === asstMsgId ? { ...m, isStreaming: false } : m,
+ m.id === asstMsgId ? stopRunningTools(m, "Stopped after an error") : m,
),
}));
}
}
if (!settled && !abort.signal.aborted) {
+ flushText();
setState((prev) => ({
...prev,
isStreaming: false,
@@ -152,7 +201,7 @@ export function useChat(repoId: string) {
prev.error ??
"The response ended before it finished. The server log should say why.",
messages: prev.messages.map((m) =>
- m.id === asstMsgId ? { ...m, isStreaming: false } : m,
+ m.id === asstMsgId ? stopRunningTools(m, "Response ended early") : m,
),
}));
}
@@ -160,14 +209,19 @@ export function useChat(repoId: string) {
function handleEvent(ev: ChatSSEEvent, asstId: string) {
if (activeRepoRef.current !== repoId) return;
if (ev.type === "done" || ev.type === "error") settled = true;
+ if (ev.type === "text_delta") {
+ queueText(ev.text);
+ return;
+ }
+ flushText();
setState((prev) => {
const messages = prev.messages.map((m) => {
+ if (ev.type === "done" && m.id === userMsgId) {
+ return ev.user_message_id ? { ...m, serverId: ev.user_message_id } : m;
+ }
if (m.id !== asstId) return m;
switch (ev.type) {
- case "text_delta":
- return { ...m, text: m.text + ev.text };
-
case "tool_start":
return {
...m,
@@ -199,10 +253,16 @@ export function useChat(repoId: string) {
};
case "done":
- return { ...m, isStreaming: false, serverId: ev.message_id };
+ return {
+ ...m,
+ isStreaming: false,
+ serverId: ev.message_id,
+ ...(ev.provider ? { provider: ev.provider } : {}),
+ ...(ev.model ? { model: ev.model } : {}),
+ };
case "error":
- return { ...m, isStreaming: false };
+ return stopRunningTools(m, ev.message);
default:
return m;
@@ -221,17 +281,20 @@ export function useChat(repoId: string) {
messages,
};
});
+ if (ev.type === "done") conversationIdRef.current = ev.conversation_id;
}
},
- [repoId, state.conversationId],
+ [repoId],
);
const loadConversation = useCallback(
async (conversationId: string) => {
+ const requestId = ++loadRequestRef.current;
try {
const data = await getConversation(repoId, conversationId);
- if (activeRepoRef.current !== repoId) return;
+ if (activeRepoRef.current !== repoId || loadRequestRef.current !== requestId) return;
const msgs = toChatUiMessages(data.messages);
+ conversationIdRef.current = conversationId;
setState({
messages: msgs,
conversationId,
@@ -239,7 +302,7 @@ export function useChat(repoId: string) {
error: null,
});
} catch (err) {
- if (activeRepoRef.current !== repoId) return;
+ if (activeRepoRef.current !== repoId || loadRequestRef.current !== requestId) return;
setState((prev) => ({
...prev,
error: toFriendlyMessage(err),
@@ -256,7 +319,7 @@ export function useChat(repoId: string) {
...prev,
isStreaming: false,
messages: prev.messages.map((message) =>
- message.isStreaming ? { ...message, isStreaming: false } : message,
+ message.isStreaming ? stopRunningTools(message, "Stopped") : message,
),
}));
}, []);
@@ -264,6 +327,8 @@ export function useChat(repoId: string) {
const reset = useCallback(() => {
abortRef.current?.abort();
abortRef.current = null;
+ loadRequestRef.current += 1;
+ conversationIdRef.current = null;
setState(EMPTY_CHAT_STATE);
}, []);
diff --git a/tests/unit/server/test_chat_stream_terminal_event.py b/tests/unit/server/test_chat_stream_terminal_event.py
index 389294992..f3e1fec20 100644
--- a/tests/unit/server/test_chat_stream_terminal_event.py
+++ b/tests/unit/server/test_chat_stream_terminal_event.py
@@ -14,14 +14,20 @@ handler already used ``data`` + ``type``; this one branch did not.
from __future__ import annotations
import json
+import os
+import tempfile
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from datetime import UTC, datetime
+from pathlib import Path
from unittest.mock import patch
import pytest
+from alembic import command
+from alembic.config import Config
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
+from sqlalchemy import inspect
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import StaticPool
@@ -138,3 +144,111 @@ async def test_a_completed_turn_ends_the_stream_with_done():
assert events, f"stream carried no readable data events: {body!r}"
assert events[-1]["type"] == "done"
assert events[-1]["conversation_id"]
+ assert events[-1]["user_message_id"]
+ assert events[-1]["provider"] == "test"
+ assert events[-1]["model"] == "test-model"
+
+
+async def test_conversation_history_supports_rename_pin_fork_and_delete_undo():
+ app = await _make_app()
+ with patch(
+ "repowise.server.routers.chat.get_chat_provider_instance",
+ return_value=_SilentProvider(),
+ ):
+ events = _data_events(await _post(app, {"message": "original question"}))
+ conversation_id = events[-1]["conversation_id"]
+
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://testserver") as client:
+ updated = await client.patch(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}",
+ json={"title": "Pinned investigation", "pinned": True},
+ )
+ assert updated.status_code == 200
+ assert updated.json()["title"] == "Pinned investigation"
+ assert updated.json()["pinned"] is True
+
+ messages = await client.get(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}"
+ )
+ user_message_id = messages.json()["messages"][0]["id"]
+ forked_before = await client.post(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}/fork",
+ json={"before_message_id": user_message_id},
+ )
+ assert forked_before.status_code == 200
+ assert forked_before.json()["message_count"] == 0
+
+ bad_point = await client.post(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}/fork",
+ json={"before_message_id": "missing"},
+ )
+ assert bad_point.status_code == 404
+
+ blank_title = await client.patch(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}",
+ json={"title": " "},
+ )
+ assert blank_title.status_code == 422
+
+ forked = await client.post(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}/fork",
+ json={},
+ )
+ assert forked.status_code == 200
+ assert forked.json()["message_count"] == 2
+
+ deleted = await client.delete(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}"
+ )
+ assert deleted.status_code == 200
+ listed = await client.get(f"/api/repos/{_REPO_ID}/chat/conversations")
+ assert all(row["id"] != conversation_id for row in listed.json())
+
+ restored = await client.post(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}/restore"
+ )
+ assert restored.status_code == 200
+ listed = await client.get(f"/api/repos/{_REPO_ID}/chat/conversations")
+ assert any(row["id"] == conversation_id for row in listed.json())
+
+
+def test_conversation_refinement_migration_upgrades_sqlite() -> None:
+ core_root = Path("packages/core").resolve()
+ with tempfile.TemporaryDirectory() as tmp:
+ database_path = Path(tmp) / "chat-migration.db"
+ url = f"sqlite+aiosqlite:///{database_path}"
+ previous_url = os.environ.get("DATABASE_URL")
+ previous_cwd = Path.cwd()
+ os.environ["DATABASE_URL"] = url
+ try:
+ os.chdir(core_root)
+ config = Config("alembic.ini")
+ config.set_main_option("sqlalchemy.url", url)
+ with patch("logging.config.fileConfig"):
+ command.upgrade(config, "0055")
+ command.upgrade(config, "0056")
+ finally:
+ os.chdir(previous_cwd)
+ if previous_url is None:
+ os.environ.pop("DATABASE_URL", None)
+ else:
+ os.environ["DATABASE_URL"] = previous_url
+
+ engine = create_async_engine(url, connect_args={"check_same_thread": False})
+
+ async def verify() -> None:
+ async with engine.connect() as connection:
+ columns = await connection.run_sync(
+ lambda sync_connection: {
+ column["name"]
+ for column in inspect(sync_connection).get_columns("conversations")
+ }
+ )
+ assert {"pinned", "deleted_at"} <= columns
+ await engine.dispose()
+
+ import asyncio
+
+ asyncio.run(verify())