);
}
// DraftChat is the default right-pane view: a fresh chat (agent picker in the
// header, centered empty state, composer) with NO conversation created yet. The
// conversation is created lazily on the first send (ChatGPT-style), then the
// parent switches to the real ChatView.
function DraftChat({
agents,
profiles,
onStarted,
}: {
agents: Agent[];
profiles: LLMProfile[];
onStarted: (c: Conversation, pending?: { input?: string; attachments?: ChatAttachment[] }) => void;
}) {
const [agentKey, setAgentKey] = React.useState("");
const [llmProfileId, setLlmProfileId] = React.useState(null);
const [input, setInput] = React.useState("");
const [sending, setSending] = React.useState(false);
const [uploading, setUploading] = React.useState(false);
// default the agent to Auto once agents load.
React.useEffect(() => {
if (!agentKey && agents.some((a) => a.key === "auto")) setAgentKey("auto");
}, [agentKey, agents]);
const agent = agents.find((a) => a.key === agentKey);
async function send() {
const msg = input.trim();
if (!msg || !agentKey || sending) return;
setSending(true);
try {
const c = await api.createConversation(agentKey, "", llmProfileId);
await api.sendConversationMessage(c.id, msg);
onStarted(c);
} catch (e) {
toast.error("发送失败:" + (e as Error).message);
setSending(false);
}
}
// Attachments need a conversation to own the uploads dir (sessions/conv-/),
// and a draft has none yet — so picking a file CREATES the conversation, uploads
// into it, then hands off to ChatView carrying the typed text + attachments (the
// user sends from there). Mirrors the task main-agent console's upload, adapted to
// the ChatGPT-style lazy-create flow.
async function pickFiles(files: FileList | null) {
if (!files || files.length === 0 || !agentKey || uploading || sending) return;
setUploading(true);
try {
const c = await api.createConversation(agentKey, "", llmProfileId);
const r = await api.chatUpload("session", `conv-${c.id}`, Array.from(files));
onStarted(c, { input, attachments: r.attachments });
} catch (e) {
toast.error("上传失败:" + (e as Error).message);
setUploading(false);
}
}
const agentPicker = (
);
return (
<>
{/* empty / landing state fills the panel */}
开始和「{agent?.name ?? "Agent"}」对话
{agent?.description &&
{agent.description}
}
>
);
}
// ChatView is the right pane for one conversation — mirrors the task detail's
// main-agent console: header with agent + live badge + token/duration meta, a
// scroll-stick transcript (chat mode), and the composer.
function ChatView({
conv,
agents,
profiles,
initial,
onTitleMaybeChanged,
onConvUpdated,
}: {
conv: Conversation;
agents: Agent[];
profiles: LLMProfile[];
// pending text + already-uploaded attachments handed off from a draft that
// created this conversation via the paperclip (consumed once, on mount).
initial?: { input?: string; attachments?: ChatAttachment[] };
onTitleMaybeChanged: () => void;
onConvUpdated: () => void;
}) {
const [messages, setMessages] = React.useState([]);
const [running, setRunning] = React.useState(false);
const [input, setInput] = React.useState(initial?.input ?? "");
const [sending, setSending] = React.useState(false);
const [stopping, setStopping] = React.useState(false);
// 方式1 文件上传:已上传的附件(落到 sessions/conv-/uploads/),随下条消息一起发。
const [attachments, setAttachments] = React.useState(initial?.attachments ?? []);
const [uploading, setUploading] = React.useState(false);
const cursorRef = React.useRef(0); // newest loaded id — incremental-tail anchor
const earliestRef = React.useRef(0); // earliest loaded id — reverse-pagination anchor
const hasMoreRef = React.useRef(false); // older history remains above the loaded window
const loadingMoreRef = React.useRef(false); // guard: one scroll-up load at a time
const [hasMore, setHasMore] = React.useState(false); // drives the "load earlier" hint
const agent = agents.find((a) => a.key === conv.agent_key);
const currentProfileId = conv.llm_profile_id ?? null;
async function changeProfile(id: number | null) {
try {
await api.updateConversationProfile(conv.id, id);
onConvUpdated();
} catch (e) {
toast.error("切换 LLM 失败:" + (e as Error).message);
}
}
// conversation-scoped detail fetcher for the reused Transcript renderer.
const fetchDetail = React.useCallback((seq: number) => api.conversationMsgDetail(conv.id, seq), [conv.id]);
// seq of the most-recent TodoWrite tool call (for the Todo popover); null if none.
const latestTodoSeq = React.useMemo(() => {
for (let i = messages.length - 1; i >= 0; i--) {
const a = messages[i];
if (a.kind === "tool_use" && a.tool === "TodoWrite") return a.seq;
}
return null;
}, [messages]);
// reset + load whenever the selected conversation changes. Load only the LATEST
// page on open — a long thread's final answer sits at the very end, so the newest
// page shows it immediately (issue #3: opening/refresh used to load the oldest
// page, so the completed result was missing until another message advanced the
// cursor). Older history streams in on scroll-up (loadEarlier below).
React.useEffect(() => {
cursorRef.current = 0;
earliestRef.current = 0;
hasMoreRef.current = false;
setHasMore(false);
setMessages([]);
setRunning(false);
let live = true;
api
.conversationHistory(conv.id, 0, HISTORY_PAGE)
.then((r) => {
if (!live) return;
setMessages(r.items);
cursorRef.current = r.cursor; // newest id → incremental-tail anchor
earliestRef.current = r.items.length ? r.items[0].seq : 0;
hasMoreRef.current = r.hasMore;
setHasMore(r.hasMore);
setRunning(r.running);
})
.catch(() => {
/* The empty state remains usable when history loading fails. */
});
return () => {
live = false;
};
}, [conv.id]);
// poll while a turn is running: pull new steps after the cursor.
React.useEffect(() => {
if (!running) return;
let live = true;
const tick = async () => {
try {
const r = await api.conversationMessages(conv.id, cursorRef.current);
if (!live) return;
if (r.items.length) {
setMessages((prev) => [...prev, ...r.items]);
cursorRef.current = r.cursor;
}
setRunning(r.running);
if (!r.running) onTitleMaybeChanged(); // first-turn auto-title landed
} catch {
/* transient — keep polling */
}
};
const h = setInterval(tick, 1000);
return () => {
live = false;
clearInterval(h);
};
}, [running, conv.id, onTitleMaybeChanged]);
// ---- transcript auto-scroll (open → bottom; stick to bottom unless scrolled up) ----
const contentRef = React.useRef(null);
const atBottomRef = React.useRef(true);
const viewport = React.useCallback(
() => (contentRef.current?.closest('[data-slot="scroll-area-viewport"]') as HTMLElement | null) ?? null,
[],
);
// Scroll-up loads one older page and prepends it, preserving the visual position
// so the view doesn't jump (record height/offset before, restore the delta after).
const loadEarlier = React.useCallback(async () => {
if (loadingMoreRef.current || !hasMoreRef.current) return;
const vp = viewport();
if (!vp) return;
loadingMoreRef.current = true;
const prevH = vp.scrollHeight;
const prevTop = vp.scrollTop;
try {
const r = await api.conversationHistory(conv.id, earliestRef.current, HISTORY_PAGE);
if (r.items.length) {
setMessages((prev) => {
const seen = new Set(prev.map((a) => a.seq));
return [...r.items.filter((a) => !seen.has(a.seq)), ...prev];
});
earliestRef.current = r.items[0].seq;
}
hasMoreRef.current = r.hasMore;
setHasMore(r.hasMore);
requestAnimationFrame(() => {
const v = viewport();
if (v) v.scrollTop = prevTop + (v.scrollHeight - prevH);
});
} catch {
/* transient — a later scroll retries */
} finally {
loadingMoreRef.current = false;
}
}, [conv.id, viewport]);
React.useEffect(() => {
const vp = viewport();
if (!vp) return;
const onScroll = () => {
atBottomRef.current = vp.scrollTop + vp.clientHeight >= vp.scrollHeight - 60;
if (vp.scrollTop <= 80) void loadEarlier(); // near top → pull an older page
};
vp.addEventListener("scroll", onScroll, { passive: true });
return () => vp.removeEventListener("scroll", onScroll);
}, [viewport, loadEarlier]);
// open/switch a conversation → jump to the latest (bottom)
// biome-ignore lint/correctness/useExhaustiveDependencies: changing conversations intentionally retriggers the scroll reset.
React.useLayoutEffect(() => {
const vp = viewport();
if (vp) {
vp.scrollTop = vp.scrollHeight;
atBottomRef.current = true;
}
}, [conv.id, viewport]);
// new activity → stick to bottom only if the user is already pinned there
// biome-ignore lint/correctness/useExhaustiveDependencies: message and running changes intentionally retrigger bottom anchoring.
React.useLayoutEffect(() => {
if (!atBottomRef.current) return;
const vp = viewport();
if (vp) vp.scrollTop = vp.scrollHeight;
}, [messages, running, viewport]);
// Per-conversation token total, live — same accounting as the main-agent
// console: completed runs' `result` sum + the in-progress run's latest `usage`.
const tokenTotal = React.useMemo(() => {
let i = 0,
o = 0,
cr = 0;
let li = 0,
lo = 0,
lcr = 0;
let turns = 0; // agent 循环轮次 = 模型调用次数(每次一条 kind='usage')
for (const a of messages) {
if (a.kind === "result") {
i += a.input_tokens ?? 0;
o += a.output_tokens ?? 0;
cr += a.cache_read_tokens ?? 0;
li = lo = lcr = 0;
} else if (a.kind === "usage") {
turns += 1;
li = a.input_tokens ?? 0;
lo = a.output_tokens ?? 0;
lcr = a.cache_read_tokens ?? 0;
}
}
const I = i + li,
O = o + lo,
CR = cr + lcr;
return { i: I, o: O, cr: CR, turns, any: I + O + CR > 0 };
}, [messages]);
// pickFiles uploads into this conversation's session dir (sessions/conv-/
// uploads/) and queues the returned metadata to send with the next message.
async function pickFiles(files: FileList | null) {
if (!files || files.length === 0) return;
setUploading(true);
try {
const r = await api.chatUpload("session", `conv-${conv.id}`, Array.from(files));
setAttachments((prev) => [...prev, ...r.attachments]);
} catch (e) {
toast.error("上传失败:" + (e as Error).message);
} finally {
setUploading(false);
}
}
async function send() {
const msg = input.trim();
const atts = attachments;
if ((!msg && atts.length === 0) || sending || running) return;
setSending(true);
setInput("");
setAttachments([]);
try {
await api.sendConversationMessage(conv.id, msg, atts.length ? atts : undefined);
setRunning(true);
// pull the just-persisted human turn immediately.
const r = await api.conversationMessages(conv.id, cursorRef.current);
setMessages((prev) => [...prev, ...r.items]);
cursorRef.current = r.cursor;
} catch (e) {
toast.error("发送失败:" + (e as Error).message);
setInput(msg); // restore so the user doesn't lose their text
setAttachments(atts); // and their attachments
} finally {
setSending(false);
}
}
// stop aborts the in-flight run for this conversation. running flips to false on
// the next 1s poll once the backend unwinds the agent; the trigger queue is not
// affected — the agent's next queued fire still starts.
async function stop() {
if (stopping) return;
setStopping(true);
try {
await api.stopConversation(conv.id);
} catch (e) {
toast.error("停止失败:" + (e as Error).message);
} finally {
setStopping(false);
}
}
return (
<>
{/* header: which agent + live + token meta */}