Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
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
47 changes: 47 additions & 0 deletions packages/web-shell/client/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ type ChatEditorTestProps = {
gitStatus?: DaemonWorkspaceGitStatus;
onOpenGitDiff?: () => void;
visibleToolbarActions?: string[];
tokenCount?: number;
contextWindow?: number;
onShowContextUsage?: () => void;
onChatWidthModeChange?: (mode: '1000' | 'wide') => void;
};

Expand Down Expand Up @@ -6841,6 +6844,50 @@ describe('App session callbacks', () => {
);
});

it('wires the composer context ring from the connection and opens /context on click', async () => {
const usageConnection = mockConnection as typeof mockConnection & {
tokenCount?: number;
contextWindow?: number;
};
usageConnection.tokenCount = 338;
usageConnection.contextWindow = 1000;

renderApp();
await flush();

expect(testState.latestChatEditorProps?.visibleToolbarActions).toContain(
'contextUsage',
);
expect(testState.latestChatEditorProps?.tokenCount).toBe(338);
expect(testState.latestChatEditorProps?.contextWindow).toBe(1000);

await act(async () => {
testState.latestChatEditorProps?.onShowContextUsage?.();
});
await flush();

expect(mockSessionActions.getContextUsage).toHaveBeenCalledWith({
detail: false,
});
});

it('defaults the composer ring props to 0 before any usage arrives', async () => {
// The state right after connecting (or for sessions that never emit
// usage): the `?? 0` fallbacks must keep NaN out of the ring math.
const usageConnection = mockConnection as typeof mockConnection & {
tokenCount?: number;
contextWindow?: number;
};
usageConnection.tokenCount = undefined;
usageConnection.contextWindow = undefined;

renderApp();
await flush();

expect(testState.latestChatEditorProps?.tokenCount).toBe(0);
expect(testState.latestChatEditorProps?.contextWindow).toBe(0);
});

it('keeps legacy task status for a custom header without explicit header configuration', () => {
const monitor: DaemonSessionMonitorTaskStatus = {
kind: 'monitor',
Expand Down
10 changes: 10 additions & 0 deletions packages/web-shell/client/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ function getFullscreenSurfaceTabEdges(
}
const DEFAULT_COMPOSER_TOOLBAR_ACTIONS = [
'approvalMode',
'contextUsage',
'model',
'widthMode',
'voice',
Expand Down Expand Up @@ -6255,6 +6256,12 @@ export function App({
reportError,
],
);
// Stable identity: ChatEditor is memoized and an inline closure would
// re-render it on every app render.
const handleShowContextUsage = useCallback(
() => showContextUsage('/context', false),
[showContextUsage],
);

// Stable reference: this travels through the memoized MessageList →
// MessageItem chain, so an inline closure would defeat their memo.
Expand Down Expand Up @@ -10628,6 +10635,9 @@ export function App({
? DEFAULT_EMPTY_COMPOSER_TOOLBAR_ACTIONS
: DEFAULT_COMPOSER_TOOLBAR_ACTIONS)
}
tokenCount={connection.tokenCount ?? 0}
contextWindow={connection.contextWindow ?? 0}
Comment on lines +10638 to +10639

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已处理(30d7248):App.test.tsx 新增用例——connection.tokenCount/contextWindow 为 undefined(刚连接、尚无 usage)时 ChatEditor 收到 0/0,圆环隐藏,?? 0 fallback 不再是测试盲区。

onShowContextUsage={handleShowContextUsage}
Comment on lines +10638 to +10640

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已处理(30d7248):App.test.tsx 新增接线用例——默认 visibleToolbarActions 包含 contextUsage、connection.tokenCount/contextWindow 传导到 ChatEditor props、onShowContextUsage 点击触发 getContextUsage({ detail: false })。

availableModels={availableModels}
onSelectMode={handleSetMode}
onSelectModel={handleModelSelect}
Expand Down
28 changes: 28 additions & 0 deletions packages/web-shell/client/components/ChatEditor.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -1399,6 +1399,34 @@
flex-shrink: 0;
}

.contextUsageBtn {
flex-shrink: 0;
padding: 0 4px;
}

.contextRingTrack {
stroke: var(--border);
}

.contextRingValue {
stroke: var(--agent-blue-500);
transition: stroke-dashoffset 0.25s ease;
Comment on lines +1411 to +1413

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已处理(30d7248):为 .contextRingValue 增加 @media (prefers-reduced-motion: reduce) { transition: none; },与文件内其它装饰性动画的抑制方式一致。

}

.contextRingValueWarning {
stroke: var(--warning-color);
}

.contextRingValueError {
stroke: var(--error-color);
}

@media (prefers-reduced-motion: reduce) {
.contextRingValue {
transition: none;
}
}

.widthModeBtn .toolBtnIcon svg {
width: 18px;
height: 18px;
Expand Down
143 changes: 143 additions & 0 deletions packages/web-shell/client/components/ChatEditor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
} from '../hooks/useComposerCore';
import type { UseDaemonFollowupSuggestionReturn } from '@qwen-code/webui/daemon-react-sdk';
import { ChatEditor, type ComposerToolbarAction } from './ChatEditor';
import { formatContextUsageDetail } from '../utils/formatTokenCount';
import { WebShellPortalRootContext } from '../portalRoot';

Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
Expand Down Expand Up @@ -265,6 +266,9 @@ function renderChatEditor(props: {
onSelectMode?: (mode: string) => void;
onSelectModel?: (model: string) => void;
onAttachmentsChange?: (hasAttachments: boolean) => void;
tokenCount?: number;
contextWindow?: number;
onShowContextUsage?: () => void;
placeholderText?: string;
animatePlaceholder?: boolean;
disabled?: boolean;
Expand Down Expand Up @@ -343,6 +347,145 @@ describe('ChatEditor voice toolbar integration', () => {
});
});

describe('ChatEditor context usage ring', () => {
const ring = (container: HTMLElement) =>
container.querySelector<HTMLButtonElement>(
'[data-web-shell-context-usage]',
);

it('renders in toolbarRight before the voice actions', () => {
const container = renderChatEditor({
tokenCount: 34_298,
contextWindow: 100_000,
onShowContextUsage: vi.fn(),
});

const button = ring(container)!;
expect(button).not.toBeNull();
expect(button.getAttribute('aria-label')).toBe('34.3% context used');
const liveVoice = container.querySelector(
'[data-testid="live-voice-button"]',
)!;
// The ring sits immediately left of the voice cluster.
expect(
button.compareDocumentPosition(liveVoice) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
});

it('is controlled by the contextUsage toolbar action', () => {
const shown = renderChatEditor({
tokenCount: 100,
contextWindow: 1000,
visibleToolbarActions: ['contextUsage'],
});
const hidden = renderChatEditor({
tokenCount: 100,
contextWindow: 1000,
visibleToolbarActions: ['voice'],
});

expect(ring(shown)).not.toBeNull();
expect(ring(hidden)).toBeNull();
});

it('stays hidden while usage or the context window is unknown', () => {
const noUsage = renderChatEditor({ tokenCount: 0, contextWindow: 1000 });
const noWindow = renderChatEditor({ tokenCount: 100, contextWindow: 0 });

expect(ring(noUsage)).toBeNull();
expect(ring(noWindow)).toBeNull();
});

it('opens the context breakdown when clicked', () => {
const onShowContextUsage = vi.fn();
const container = renderChatEditor({
tokenCount: 100,
contextWindow: 1000,
onShowContextUsage,
});

act(() => {
ring(container)!.dispatchEvent(
new MouseEvent('click', { bubbles: true, cancelable: true }),
);
});

expect(onShowContextUsage).toHaveBeenCalledTimes(1);
});

it('shows the used/total detail in a tooltip on focus', async () => {
const container = renderChatEditor({
tokenCount: 53_600,
contextWindow: 1_000_000,
onShowContextUsage: vi.fn(),
});

await act(async () => {
ring(container)!.focus();
});

expect(document.body.textContent).toContain('53.6k / 1.0M tokens (5.4%)');
// The arrow must be the Radix-positioned element: a pseudo-element pinned
// to the content center stops pointing at the trigger once collision
// avoidance shifts the content near the viewport edge. jsdom has no
// layout, so pin the positioning classes the rendered arrow depends on —
// a shadcn regeneration that drops them would detach the arrow visually
// while an existence check stayed green.
const arrowClass = document
.querySelector('[data-slot="tooltip-arrow"]')
?.getAttribute('class');
expect(arrowClass).toContain('rotate-45');
expect(arrowClass).toContain('translate-y-[calc(-50%_-_2px)]');
});

it('escalates the arc color at the /context panel thresholds', () => {
const arcClass = (container: HTMLElement) =>
ring(container)!.querySelectorAll('circle')[1].getAttribute('class') ??
'';

const warn = renderChatEditor({ tokenCount: 61, contextWindow: 100 });
const error = renderChatEditor({ tokenCount: 81, contextWindow: 100 });
const normal = renderChatEditor({ tokenCount: 60, contextWindow: 100 });
Comment on lines +446 to +448

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已处理(30d7248):补了 80 整点用例,断言 exactly 80% 仍是 warning 且不是 error,把严格 > 的两侧边界都钉住(60 侧原有用例保持)。

// Both thresholds are strict: exactly 80% is still warning, matching the
// /context panel.
const atError = renderChatEditor({ tokenCount: 80, contextWindow: 100 });

expect(arcClass(warn)).toContain('contextRingValueWarning');
expect(arcClass(error)).toContain('contextRingValueError');
expect(arcClass(normal)).not.toContain('Warning');
expect(arcClass(normal)).not.toContain('Error');
expect(arcClass(atError)).toContain('contextRingValueWarning');
expect(arcClass(atError)).not.toContain('contextRingValueError');
});

it('caps the arc at 100% while the label keeps the real overflow', () => {
const container = renderChatEditor({
tokenCount: 150,
contextWindow: 100,
});

const button = ring(container)!;
expect(button.getAttribute('aria-label')).toBe('150.0% context used');
const arc = button.querySelectorAll('circle')[1];
expect(arc.getAttribute('stroke-dashoffset')).toBe('0');
});
});

describe('formatContextUsageDetail', () => {
it('formats used/total with k/M units and one decimal', () => {
expect(formatContextUsageDetail(53_600, 1_000_000)).toBe(
'53.6k / 1.0M tokens (5.4%)',
);
expect(formatContextUsageDetail(338_108, 1_000_000)).toBe(
'338.1k / 1.0M tokens (33.8%)',
);
expect(formatContextUsageDetail(512, 2000)).toBe(
'512 / 2.0k tokens (25.6%)',
);
});
});

describe('ChatEditor animation layers', () => {
it('mounts the inert specular layer without replacing composer controls', () => {
const container = renderChatEditor({});
Expand Down
Loading
Loading