Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ui/messages/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "انتهى Shell برمز الخروج {code}.",
"workspace_terminal_disconnected": "انقطعت الطرفية.",
"workspace_terminal_restart": "إعادة تشغيل Shell",
"chat_show_full_conversation": "عرض المحادثة كاملة",
"chat_messages_feed": "الرسائل",
"settings_key_from": "المفتاح من",
"settings_token_from": "الرمز من",
"settings_environment_tab": "تبويب البيئة",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "Shell exited with code {code}.",
"workspace_terminal_disconnected": "The terminal disconnected.",
"workspace_terminal_restart": "Restart shell",
"chat_show_full_conversation": "Show full conversation",
"chat_messages_feed": "Messages",
"settings_key_from": "Key from",
"settings_token_from": "Token from",
"settings_environment_tab": "Environment tab",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "El shell terminó con el código {code}.",
"workspace_terminal_disconnected": "La terminal se desconectó.",
"workspace_terminal_restart": "Reiniciar shell",
"chat_show_full_conversation": "Mostrar la conversación completa",
"chat_messages_feed": "Mensajes",
"settings_key_from": "Clave tomada de la",
"settings_token_from": "Token tomado de la",
"settings_environment_tab": "pestaña Entorno",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/fa.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "پوسته با کد {code} خارج شد.",
"workspace_terminal_disconnected": "ارتباط ترمینال قطع شد.",
"workspace_terminal_restart": "راه‌اندازی دوباره پوسته",
"chat_show_full_conversation": "نمایش کامل گفتگو",
"chat_messages_feed": "پیام‌ها",
"settings_key_from": "کلید از",
"settings_token_from": "توکن از",
"settings_environment_tab": "زبانهٔ محیط",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "शेल कोड {code} के साथ बंद हो गया।",
"workspace_terminal_disconnected": "टर्मिनल डिस्कनेक्ट हो गया।",
"workspace_terminal_restart": "शेल फिर से शुरू करें",
"chat_show_full_conversation": "पूरी बातचीत दिखाएं",
"chat_messages_feed": "संदेश",
"settings_key_from": "की स्रोत",
"settings_token_from": "टोकन स्रोत",
"settings_environment_tab": "एनवायरनमेंट टैब",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "シェルがコード {code} で終了しました。",
"workspace_terminal_disconnected": "ターミナルの接続が切れました。",
"workspace_terminal_restart": "シェルを再起動",
"chat_show_full_conversation": "会話全体を表示",
"chat_messages_feed": "メッセージ",
"settings_key_from": "キーの取得元",
"settings_token_from": "トークンの取得元",
"settings_environment_tab": "環境タブ",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "셸이 코드 {code}로 종료되었습니다.",
"workspace_terminal_disconnected": "터미널 연결이 끊어졌습니다.",
"workspace_terminal_restart": "셸 다시 시작",
"chat_show_full_conversation": "전체 대화 보기",
"chat_messages_feed": "메시지",
"settings_key_from": "키 발급처",
"settings_token_from": "토큰 발급처",
"settings_environment_tab": "환경 탭",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"workspace_terminal_exited": "Powłoka zakończyła działanie z kodem {code}.",
"workspace_terminal_disconnected": "Utracono połączenie z terminalem.",
"workspace_terminal_restart": "Uruchom ponownie powłokę",
"chat_show_full_conversation": "Pokaż całą rozmowę",
"chat_messages_feed": "Wiadomości",
"settings_key_from": "Klucz z",
"settings_token_from": "Token z",
"settings_environment_tab": "Karta środowiska",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "Оболочка завершилась с кодом {code}.",
"workspace_terminal_disconnected": "Терминал отключился.",
"workspace_terminal_restart": "Перезапустить оболочку",
"chat_show_full_conversation": "Показать весь разговор",
"chat_messages_feed": "Сообщения",
"settings_key_from": "Ключ из",
"settings_token_from": "Токен из",
"settings_environment_tab": "вкладки «Окружение»",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "Kabuk {code} koduyla çıktı.",
"workspace_terminal_disconnected": "Terminal bağlantısı kesildi.",
"workspace_terminal_restart": "Kabuğu yeniden başlat",
"chat_show_full_conversation": "Tüm konuşmayı göster",
"chat_messages_feed": "Mesajlar",
"settings_key_from": "Anahtar kaynağı",
"settings_token_from": "Token kaynağı",
"settings_environment_tab": "Ortam sekmesi",
Expand Down
2 changes: 1 addition & 1 deletion ui/messages/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"workspace_terminal_exited": "Shell 已退出,退出码 {code}。",
"workspace_terminal_disconnected": "终端连接已断开。",
"workspace_terminal_restart": "重新启动 Shell",
"chat_show_full_conversation": "显示完整对话",
"chat_messages_feed": "消息",
"settings_key_from": "密钥来自",
"settings_token_from": "令牌来自",
"settings_environment_tab": "环境标签页",
Expand Down
84 changes: 70 additions & 14 deletions ui/src/components/ChatPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4129,6 +4129,8 @@ const Transcript = memo(function Transcript({
onOpenDelegate,
focusedMessageId,
focusNonce,
assistantLabel,
onLeaveFeed,
}: {
/** The branch on screen, oldest first. */
messages: ChatMessage[];
Expand Down Expand Up @@ -4160,6 +4162,10 @@ const Transcript = memo(function Transcript({
onOpenDelegate?: (sessionId: string) => void;
focusedMessageId?: string | null;
focusNonce?: number;
/** Names each assistant article, as the Markdown export does. */
assistantLabel: string;
/** Ctrl+End and Ctrl+Home leave the feed, forward or back. */
onLeaveFeed: (forward: boolean) => void;
}) {
useLocale();
const replies = useMemo(() => questionReplies(messages), [messages]);
Expand Down Expand Up @@ -4195,16 +4201,15 @@ const Transcript = memo(function Transcript({
}, [messages, visibleMessages, allMessages]);
// ponytail: interacted rows stay mounted for this visit; lift row state if retention becomes costly.
const retainedRows = useRef(new Set<string>());
const [fullHistory, setFullHistory] = useState(false);
const [focusedRow, setFocusedRow] = useState<string | null>(null);
const getItemKey = useCallback((index: number) => visibleMessages[index][0].id, [visibleMessages]);
const rangeExtractor = useCallback((range: VirtualRange) => {
if (fullHistory) return visibleMessages.map((_, index) => index);
const indexes = new Set(defaultRangeExtractor(range));
visibleMessages.forEach((group, index) => {
if (retainedRows.current.has(group[0].id)) indexes.add(index);
if (group[0].id === focusedRow || retainedRows.current.has(group[0].id)) indexes.add(index);
});
return [...indexes].sort((a, b) => a - b);
}, [visibleMessages, fullHistory]);
}, [visibleMessages, focusedRow]);
// Seed via the measurement cache, not estimateSize, so remembered rows count as measured for anchoring.
const [initialMeasurementsCache] = useState(() => visibleMessages.flatMap((group, index) => {
const remembered = transcriptRowSizes.get(group[0].id);
Expand Down Expand Up @@ -4292,42 +4297,89 @@ const Transcript = memo(function Transcript({
const timer = window.setTimeout(() => setMarkedRowId(null), 1600);
return () => window.clearTimeout(timer);
}, [markedRowId]);
useLayoutEffect(() => {
const scroll = scrollRef.current;
const row = focusedRow ? scroll?.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(focusedRow)}"]`) : null;
if (!scroll || !row || row.contains(document.activeElement)) return;
row.focus({ preventScroll: true });
const viewport = scroll.getBoundingClientRect();
const bounds = row.getBoundingClientRect();
if (bounds.top >= viewport.top && bounds.bottom <= viewport.bottom) return;
virtualizer.scrollToIndex(Number(row.dataset.index), { align: bounds.height > viewport.height ? "start" : "auto" });
}, [focusedRow, scrollRef, virtualizer]);
const activeMessage = messages.at(-1);
const transcriptAnnouncement = useTranscriptAnnouncement(messages);
const pendingTailTool = busy ? streamTailTool(messages) : null;
const userLabel = m.chat_export_you();
const headingPrefix = useId();
return (
<>
<span className="sr-only" role="status" aria-live="polite">
<span key={transcriptAnnouncement.sequence}>{transcriptAnnouncement.text}</span>
</span>
<button type="button" className="sr-only focus:not-sr-only" aria-pressed={fullHistory} onClick={() => setFullHistory((value) => !value)}>
{m.chat_show_full_conversation()}
</button>
<div className="relative" style={{ height: virtualizer.getTotalSize() }}>
{/* The WAI-ARIA feed pattern: assistive technology moves focus between articles, and the virtualizer mounts around it. */}
<div
role="feed"
aria-label={m.chat_messages_feed()}
className="relative"
style={{ height: virtualizer.getTotalSize() }}
onKeyDown={(event) => {
const target = event.target;
if (!(target instanceof HTMLElement) || target.isContentEditable || target.matches("input, textarea, select")) return;
if (event.altKey || event.metaKey || event.shiftKey) return;
if (event.ctrlKey && (event.key === "Home" || event.key === "End")) {
event.preventDefault();
onLeaveFeed(event.key === "End");
return;
}
const step = event.ctrlKey ? 0 : event.key === "PageDown" ? 1 : event.key === "PageUp" ? -1 : 0;
const article = target.closest<HTMLElement>("[role=article]");
const next = step && article ? visibleMessages[Number(article.dataset.index) + step] : undefined;
if (!next) return;
event.preventDefault();
setFocusedRow(next[0].id);
}}
>
{virtualizer.getVirtualItems().map((item) => {
const group = visibleMessages[item.index];
const m = group[group.length - 1];
const rowId = group[0].id;
const headingId = `${headingPrefix}${rowId}`;

// A session owns one turn slot, so one recovery disables every status
// card until its durable admission resolves.
const recoveryDisabled = busy || recoveringTurnId !== null;
return (
<div
key={rowId}
role="article"
tabIndex={0}
aria-labelledby={headingId}
aria-posinset={item.index + 1}
aria-setsize={visibleMessages.length}
data-index={item.index}
data-message-id={rowId}
ref={virtualizer.measureElement}
className={`absolute left-0 w-full pb-4 isolate before:-z-10 before:pointer-events-none before:absolute before:-inset-x-2 before:-top-2 before:bottom-2 before:rounded-lg before:bg-highlight before:transition-opacity before:duration-700 motion-reduce:before:transition-none ${rowId === markedRowId ? "before:opacity-60" : "before:opacity-0"}`}
className={`absolute left-0 w-full pb-4 isolate outline-none before:-z-10 before:pointer-events-none before:absolute before:-inset-x-2 before:-top-2 before:bottom-2 before:rounded-lg before:bg-highlight before:transition-opacity before:duration-700 motion-reduce:before:transition-none after:pointer-events-none after:absolute after:-inset-x-2 after:-top-2 after:bottom-2 after:rounded-lg focus-visible:after:outline-2 focus-visible:after:outline-focus ${rowId === markedRowId ? "before:opacity-60" : "before:opacity-0"}`}
style={{ top: item.start }}
onClickCapture={(event) => {
retainedRows.current.add(rowId);
if (!(event.target instanceof Element) || !event.target.closest("[data-work-toggle]")) return;
stickToBottom.current = false;
virtualizer.setOptions({ ...virtualizer.options, anchorTo: "start" });
}}
onPointerDownCapture={() => retainedRows.current.add(rowId)}
onFocusCapture={() => retainedRows.current.add(rowId)}
onInputCapture={() => retainedRows.current.add(rowId)}
// Screen readers can move focus through every row as they read, so focus holds a row only while it lasts.
onFocusCapture={() => setFocusedRow(rowId)}
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) setFocusedRow((current) => current === rowId ? null : current);
}}
>
{/* NVDA leaves article names unspoken by default, so a hidden heading names the author. A reply nests under its prompt. */}
{group[0].role === "user"
? <h5 id={headingId} className="sr-only select-none">{userLabel}</h5>
: <h6 id={headingId} className="sr-only select-none">{assistantLabel}</h6>}
<Message
message={m}
responseMessages={group}
Expand Down Expand Up @@ -5489,6 +5541,7 @@ export function ChatPanel({
// The open session, if any (its harness is locked; its model/mode/reasoning
// are what the composer should reflect and edit).
const openSession = sessions.find((s) => s.id === activeId);
const assistantLabel = openSession ? harnessLabel(openSession.harness, openSession.harnessName) : m.chat_the_agent();

// The selection the composer displays and edits:
// * with a session open — that session's stored settings, with any unsent
Expand Down Expand Up @@ -5866,7 +5919,7 @@ export function ChatPanel({
const markdown = openSession
? transcriptMarkdown(title, messages, {
user: m.chat_export_you(),
assistant: harnessLabel(openSession.harness, openSession.harnessName),
assistant: assistantLabel,
})
: null;
if (markdown) downloadMarkdown(transcriptFileName(title), markdown);
Expand Down Expand Up @@ -6359,6 +6412,9 @@ export function ChatPanel({
setTranscriptAtBottom(true);
scrollToEndRef.current?.();
}, []);
const leaveTranscriptFeed = useCallback((forward: boolean) => {
(forward ? composerRef.current : threadRef.current)?.focus();
}, []);
useEffect(() => {
const el = threadRef.current;
const inner = threadInnerRef.current;
Expand Down Expand Up @@ -7654,6 +7710,8 @@ export function ChatPanel({
onOpenDelegate={onOpenDelegate}
focusedMessageId={focusedMessage?.sessionId === activeId ? focusedMessage.messageId : null}
focusNonce={focusedMessage?.nonce}
assistantLabel={assistantLabel}
onLeaveFeed={leaveTranscriptFeed}
/>
</ChatLinksContext>
</ChatImageScope>
Expand Down Expand Up @@ -7729,9 +7787,7 @@ export function ChatPanel({
{pendingPlan && !(revisingPlan && pendingPlan.promptId === revisingPlan.promptId) && (
<PlanStrip
synthesized={pendingPlan.synthesized}
agentLabel={
activeSession ? harnessLabel(activeSession.harness, activeSession.harnessName) : m.chat_the_agent()
}
agentLabel={assistantLabel}
showResumeModes={activeSession?.harness === "claude-code"}
onView={(intent) => openPlan?.(pendingPlan.plan, pendingPlan.promptId, intent)}
onApprove={(resumeMode) =>
Expand Down
72 changes: 67 additions & 5 deletions ui/tests/transcriptVirtualization.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ test("virtual history retains interacted rows outside the viewport and drops abs
useCallback: callback => callback,
visibleMessages: ["a", "b", "c", "d", "e"].map(id => [{ id }]),
retainedRows,
fullHistory: false,
focusedRow: null,
defaultRangeExtractor,
});
assert.deepEqual(extract({ startIndex: 3, endIndex: 4, overscan: 0, count: 5 }), [0, 3, 4]);
Expand All @@ -51,14 +51,76 @@ test("tool labels reuse immutable parts but refresh after stream replacement or
assert.equal(calls, 3);
});

test("accessible full history includes every message", () => {
test("the focused article stays mounted outside the viewport without being retained", () => {
const expression = find(node => ts.isVariableDeclaration(node) && node.name.getText(file) === "rangeExtractor").initializer;
const extract = evaluate(`return ${expression.getText(file)}`, {
const retainedRows = { current: new Set() };
const extract = focusedRow => evaluate(`return ${expression.getText(file)}`, {
useCallback: callback => callback,
visibleMessages: ["a", "b", "c"].map(id => [{ id }]),
retainedRows: { current: new Set() }, fullHistory: true, defaultRangeExtractor,
retainedRows, focusedRow, defaultRangeExtractor,
});
const range = { startIndex: 2, endIndex: 2, overscan: 0, count: 3 };
assert.deepEqual(extract("a")(range), [0, 2]);
assert.deepEqual(extract(null)(range), [2]);
assert.equal(retainedRows.current.size, 0);
});

test("focus holds a row only while it lasts; clicks and typing retain it for the visit", () => {
const handler = name => find(node => ts.isJsxAttribute(node) && node.name.getText(file) === name && node.parent.getText(file).includes('role="article"')).initializer.expression;
const retainedRows = { current: new Set() };
let focusedRow = null;
const bindings = {
retainedRows, rowId: "a",
setFocusedRow: id => { focusedRow = id; },
stickToBottom: { current: true },
virtualizer: { options: {}, setOptions() {} },
Element: class {},
};
const run = (name, event = {}) => evaluate(`return ${handler(name).getText(file)}`, bindings)(event);
run("onFocusCapture");
assert.equal(focusedRow, "a");
assert.equal(retainedRows.current.size, 0, "a screen reader moving focus while reading retains nothing");
run("onClickCapture", { target: {} });
assert.deepEqual([...retainedRows.current], ["a"]);
retainedRows.current.clear();
run("onInputCapture");
assert.deepEqual([...retainedRows.current], ["a"]);
});

test("feed keys move focus between articles and leave the feed", () => {
const handler = find(node => ts.isJsxAttribute(node) && node.name.getText(file) === "onKeyDown" && node.getText(file).includes("PageDown")).initializer.expression;
const focused = [], left = [];
class HTMLElement {
constructor(index, editable) { Object.assign(this, { index, editable, isContentEditable: false }); }
matches() { return this.editable; }
closest() { return { dataset: { index: String(this.index) } }; }
}
const keydown = evaluate(`return ${handler.getText(file)}`, {
HTMLElement,
visibleMessages: ["a", "b", "c"].map(id => [{ id }]),
setFocusedRow: id => focused.push(id),
onLeaveFeed: forward => left.push(forward),
});
Comment thread
small-angel marked this conversation as resolved.
Resolved
assert.deepEqual(extract({ startIndex: 2, endIndex: 2, overscan: 0, count: 3 }), [0, 1, 2]);
const press = (key, { index = 1, ctrlKey = false, shiftKey = false, editable = false } = {}) => {
let prevented = false;
keydown({
key, ctrlKey, shiftKey, altKey: false, metaKey: false,
target: new HTMLElement(index, editable),
preventDefault: () => { prevented = true; },
});
return prevented;
};
assert.equal(press("PageDown"), true);
assert.equal(press("PageUp"), true);
assert.deepEqual(focused, ["c", "a"]);
assert.equal(press("PageDown", { index: 2 }), false, "the last article lets the page scroll");
assert.equal(press("PageDown", { editable: true }), false, "text fields keep their own keys");
assert.equal(press("PageDown", { ctrlKey: true }), false, "Ctrl+PageDown stays the browser's");
assert.equal(press("PageDown", { shiftKey: true }), false);
assert.equal(press("End", { ctrlKey: true }), true);
assert.equal(press("Home", { ctrlKey: true }), true);
assert.deepEqual(left, [true, false]);
assert.deepEqual(focused, ["c", "a"]);
});

test("viewport and footer resizing preserve bottom pin without moving a reader", () => {
Expand Down
Loading