Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions TESTING_COVERAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ Mobile AI chat navigation: Chromium covers opening the left sidebar above chat,
Back dismissal without leaving the page, the AI settings link, an empty composer
without vertical overflow, and messages without a redundant sender row. History
unit tests cover StrictMode, explicit close, and navigation to another page.
Resource links dismiss mobile chat even for the already-open resource; Chromium
covers current/different targets, retained conversation and desktop staying open.
Link unit tests check dismissal waits for navigation; history tests protect
destinations when navigation inherits the chat marker.

Included AI: managed transport tests cover signed-out status, explicit consent,
backend errors, streaming credit failure and non-streaming title generation without
Expand Down Expand Up @@ -2282,6 +2286,8 @@ repositories and rejects dependency lockfile drift before builds.

`browser/e2e/tests/ai-mobile.spec.ts` checks full-width phone layout and message bodies, long titles keeping the header menu on-screen, the chat resource menu targeting the saved conversation and opening its full-page view, a composer that fits above a simulated keyboard inset, options and token visibility, closing the panel, desktop composer bounds, and model selection with focus returning to the editor. A long-response regression reproduces the final sentence being clipped after keyboard resize, verifies bottom-following and the small gap above the composer, and preserves reading position when scrolled up. AI responses are mocked; a physical mobile keyboard is not exercised.

AI credit display: `helpers/managed/ai.test.ts` verifies usage notification when the SDK cancels a hosted stream; `components/AI/useHostedAI.test.tsx` verifies the immediate refresh and one delayed settlement refresh without ongoing polling. `HostedAICredits.test.tsx` covers fractional monthly and purchased balances. `ai-mobile.spec.ts` verifies the balance stays hidden until AI Chat options opens, refreshes from the account API, and links to the configured portal. These use mocked account/provider responses and do not verify live billing.

Recovery read fan-out: `recovery-fetch.test.ts` verifies concurrent reads share
one in-flight request per API/account, settled responses are not cached, failures
can be retried, and signed-out callers make no request. The SaaS legacy recovery
Expand Down
2 changes: 2 additions & 0 deletions browser/data-browser/UI_COMPONENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ This document might not be entirely up to date. If you need anything that is not

## Disclosure And Navigation UI

- `src/components/AtomicLink.tsx` - Resource and app links; overlays can provide `ResourceLinkNavigationContext` to dismiss after resource navigation, including activating the current resource.

- `src/components/Tabs.tsx` - Radix-based tabs with config-driven tab lists, panel children, rounded variant, and error styling.
- `src/components/Collapse.tsx` - Animated expand/collapse wrapper, used in the Details component.
- `src/components/Details.tsx` - Disclosure component similar to `<details>`, with a caret row or custom title control.
Expand Down
10 changes: 8 additions & 2 deletions browser/data-browser/src/chunks/AI/AISidebar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { styled } from 'styled-components';
import { ResourceLinkNavigationContext } from '@components/ResourceLinkNavigationContext';
import { useMediaQuery } from '@hooks/useMediaQuery';
import React, {
useCallback,
useEffect,
Expand Down Expand Up @@ -47,6 +49,7 @@ const handleSidebarMessageSaveError = (error: unknown) => {

const AISidebar: React.FC = () => {
const store = useStore();
const mobile = useMediaQuery('(max-width: 600px)', false);
const [rerenderKey, updateRenderKey] = useReducer(prev => prev + 1, 0);
const { shouldGenerateTitles } = useAISettings();
const {
Expand Down Expand Up @@ -497,7 +500,10 @@ const AISidebar: React.FC = () => {
}, [messages]);

return (
<React.Fragment key={rerenderKey}>
<ResourceLinkNavigationContext
key={rerenderKey}
value={mobile ? () => setIsOpen(false) : undefined}
>
{/* When resetting the chat it is better to refresh the whole component because the useChat hook keeps internal state that is not easy to reset. */}
<RealAIChat
autoSubmitMessage={autoSubmitMessage}
Expand Down Expand Up @@ -554,7 +560,7 @@ const AISidebar: React.FC = () => {
</Row>
</Row>
</RealAIChat>
</React.Fragment>
</ResourceLinkNavigationContext>
);
};

Expand Down
35 changes: 35 additions & 0 deletions browser/data-browser/src/chunks/AI/HostedAICredits.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// @vitest-environment jsdom
// @wc-ignore-file
import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, expect, it } from 'vitest';
import { HostedAICredits } from './HostedAICredits';

afterEach(cleanup);

it('shows fractional charges and separates purchased credits from the resetting allowance', () => {
render(
<HostedAICredits
portalUrl='https://portal.example'
status={{
enabled: true,
consent: true,
model: 'test',
paid: true,
allowance_micros: 5_000_000,
used_micros: 1,
remaining_micros: 9_999_999,
purchased_remaining_micros: 5_000_000,
resets_at: 1790812800,
}}
/>,
);
expect(
screen.getByText('4,999.999 of 5,000 monthly credits left'),
).toBeTruthy();
expect(
screen.getByText('5,000 purchased credits · carries over'),
).toBeTruthy();
expect(
screen.getByRole('link', { name: 'Get more credits' }).getAttribute('href'),
).toBe('https://portal.example/dashboard');
});
37 changes: 37 additions & 0 deletions browser/data-browser/src/chunks/AI/HostedAICredits.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Column } from '@components/Row';
import type { HostedAIStatus } from '@helpers/managed/ai';

const credits = (micros: number) =>
(micros / 1000).toLocaleString(undefined, { maximumFractionDigits: 3 });

export function HostedAICredits({
status,
portalUrl,
}: {
status: HostedAIStatus;
portalUrl: string;
}) {
const purchased = status.purchased_remaining_micros ?? 0;
const monthly = Math.max(0, status.remaining_micros - purchased);

const purchasedSummary =
purchased > 0 ? (
<span>{`${credits(purchased)} purchased credits · carries over`}</span>
) : null;

return (
<Column gap='0.35rem'>
<strong>AI credits</strong>
<span>{`${credits(monthly)} of ${credits(status.allowance_micros)} monthly credits left`}</span>
<span>{`Account-wide · resets ${new Date(status.resets_at * 1000).toLocaleDateString(undefined, { dateStyle: 'medium' })}`}</span>
{purchasedSummary}
<a
href={`${portalUrl}/dashboard`}
target='_blank'
rel='noopener noreferrer'
>
Get more credits
</a>
</Column>
);
}
44 changes: 29 additions & 15 deletions browser/data-browser/src/chunks/AI/RealAIChat.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { HOSTED_AI_USAGE_EVENT } from '@helpers/managed/ai';
import { getManagedApiBase } from '@helpers/managed/api';
import { HostedAICredits } from './HostedAICredits';
import { useNavigateWithTransition } from '@hooks/useNavigateWithTransition';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Column, Row } from '@components/Row';
Expand Down Expand Up @@ -827,20 +830,14 @@ const RealAIChatInner: React.FC<React.PropsWithChildren<RealAIChatProps>> = ({
)}
{!readonly && (
<>
{activeModel.provider === AIProvider.Hosted && hostedAI && (
<Column gap='0.5rem'>
{activeModel.provider === AIProvider.Hosted &&
hostedAI &&
!hostedAI.consent && (
<span>
{`${Math.floor(hostedAI.remaining_micros / 1000)} of ${Math.floor(hostedAI.allowance_micros / 1000)} AI credits left · account-wide · resets ${new Date(hostedAI.resets_at * 1000).toLocaleDateString()}`}
By sending, you enable included AI. Your messages and selected
document context are sent through Atomic to its AI providers.
</span>
{!hostedAI.consent && (
<span>
By sending, you enable included AI. Your messages and
selected document context are sent through Atomic to its AI
providers.
</span>
)}
</Column>
)}
)}
{providerNotice && (
<ProviderNotice>
<span>{providerNotice}</span>
Expand Down Expand Up @@ -1040,7 +1037,13 @@ const RealAIChatInner: React.FC<React.PropsWithChildren<RealAIChatProps>> = ({
>
<Popover
open={controlsOpen}
onOpenChange={setControlsOpen}
onOpenChange={open => {
setControlsOpen(open);
if (open)
window.dispatchEvent(
new Event(HOSTED_AI_USAGE_EVENT),
);
}}
onOpenAutoFocus={event => {
if (!focusModelOnOpen.current) return;
focusModelOnOpen.current = false;
Expand All @@ -1062,14 +1065,14 @@ const RealAIChatInner: React.FC<React.PropsWithChildren<RealAIChatProps>> = ({
side='top'
Trigger={
<PopoverTrigger asChild>
<IconButton title='Chat options'>
<IconButton title='AI Chat options'>
<FaSliders />
</IconButton>
</PopoverTrigger>
}
>
<ChatControls>
<strong>Chat options</strong>
<strong>AI Chat options</strong>
<ControlLabel>Agent</ControlLabel>
<SubtleButton
onClick={() => {
Expand Down Expand Up @@ -1138,6 +1141,17 @@ const RealAIChatInner: React.FC<React.PropsWithChildren<RealAIChatProps>> = ({
/>
</ModelSelectWrapper>
)}
{hostedAI?.enabled && (
<HostedAICredits
status={hostedAI}
portalUrl={
new URL(
getManagedApiBase(),
window.location.origin,
).origin
}
/>
)}
{showTokenUsage && totalTokensUsed > 0 && (
<TokensUsed>
Tokens used:{' '}
Expand Down
52 changes: 52 additions & 0 deletions browser/data-browser/src/components/AI/useHostedAI.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// @vitest-environment jsdom
// @wc-ignore-file
import { act, cleanup, renderHook } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import { useHostedAI } from './useHostedAI';
import { getHostedAIStatus, HOSTED_AI_USAGE_EVENT } from '@helpers/managed/ai';

vi.mock('@helpers/managed/ai', () => ({
getHostedAIStatus: vi.fn(),
HOSTED_AI_USAGE_EVENT: 'atomic-hosted-ai-usage',
}));
vi.mock('@helpers/managed/session', () => ({
onManagedLogout: () => () => {},
}));
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.resetAllMocks();
});

it('refreshes after usage and once more after server settlement, then stops', async () => {
vi.useFakeTimers();
const status = (remaining_micros: number) => ({
enabled: true,
consent: true,
model: 'test',
paid: true,
allowance_micros: 5_000_000,
used_micros: 0,
remaining_micros,
resets_at: 1790812800,
});
vi.mocked(getHostedAIStatus)
.mockResolvedValueOnce(status(5_000_000))
.mockResolvedValueOnce(status(4_950_000))
.mockResolvedValueOnce(status(4_999_123));
const { result } = renderHook(useHostedAI);
await act(async () => {});
expect(result.current.hostedAI?.remaining_micros).toBe(5_000_000);
await act(async () => {
window.dispatchEvent(new Event(HOSTED_AI_USAGE_EVENT));
});
expect(result.current.hostedAI?.remaining_micros).toBe(4_950_000);
await act(async () => {
await vi.advanceTimersByTimeAsync(1000);
});
expect(result.current.hostedAI?.remaining_micros).toBe(4_999_123);
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000);
});
expect(getHostedAIStatus).toHaveBeenCalledTimes(3);
});
14 changes: 12 additions & 2 deletions browser/data-browser/src/components/AI/useHostedAI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export function useHostedAI() {
useEffect(() => {
let generation = 0;
let active = true;
let settlementRefresh: ReturnType<typeof setTimeout> | undefined;

const refresh = async () => {
const request = ++generation;
Expand All @@ -24,18 +25,27 @@ export function useHostedAI() {
}
};

const refreshUsage = () => {
void refresh();
clearTimeout(settlementRefresh);
// The server finishes metering even after the SDK cancels its stream.
settlementRefresh = setTimeout(() => void refresh(), 1000);
};

void refresh();
window.addEventListener(HOSTED_AI_USAGE_EVENT, refresh);
window.addEventListener(HOSTED_AI_USAGE_EVENT, refreshUsage);
window.addEventListener('focus', refresh);
const removeLogout = onManagedLogout(() => {
generation++;
clearTimeout(settlementRefresh);
setStatus(undefined);
});

return () => {
active = false;
clearTimeout(settlementRefresh);
removeLogout();
window.removeEventListener(HOSTED_AI_USAGE_EVENT, refresh);
window.removeEventListener(HOSTED_AI_USAGE_EVENT, refreshUsage);
window.removeEventListener('focus', refresh);
};
}, []);
Expand Down
63 changes: 63 additions & 0 deletions browser/data-browser/src/components/AtomicLink.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// @vitest-environment jsdom
import {
fireEvent,
render,
screen,
act,
cleanup,
} from '@testing-library/react';
import { ThemeProvider } from 'styled-components';
import { expect, it, vi, afterEach } from 'vitest';
import { AtomicLink } from './AtomicLink';
import { ResourceLinkNavigationContext } from './ResourceLinkNavigationContext';

afterEach(cleanup);

const fixture = vi.hoisted(() => ({ navigate: vi.fn() }));
vi.mock('../hooks/useNavigateWithTransition', () => ({
useNavigateWithTransition: () => fixture.navigate,
}));
vi.mock('../helpers/navigation', () => ({
constructOpenURL: (subject: string) =>
subject === 'current' ? window.location.href : '/app/open?subject=next',
pathToURL: (path: string) => path,
}));
vi.mock('@components/ResourceContextMenu/ResourceContextMenuContext', () => ({
useResourceContextMenu: () => ({ openResourceMenu: vi.fn() }),
}));
vi.mock('@hooks/useIsInRTE', () => ({ useIsInRTE: () => false }));

function show(subject: string, onNavigate?: () => void) {
return render(
<ThemeProvider theme={{ colors: { text: 'black', main: 'blue' } } as never}>
<ResourceLinkNavigationContext value={onNavigate}>
<AtomicLink subject={subject}>Open resource</AtomicLink>
</ResourceLinkNavigationContext>
</ThemeProvider>,
);
}

it('activates the already-open resource so mobile chat can dismiss', () => {
const close = vi.fn();
show('current', close);
const link = screen.getByRole('link', { name: 'Open resource' });
expect(link.tabIndex).toBe(0);
fireEvent.click(link);
expect(close).toHaveBeenCalledOnce();
});

it('waits for resource navigation before dismissing the overlay', async () => {
const close = vi.fn();
let finish!: () => void;
fixture.navigate.mockImplementationOnce(
() =>
new Promise<void>(resolve => {
finish = resolve;
}),
);
show('next', close);
fireEvent.click(screen.getByRole('link', { name: 'Open resource' }));
expect(close).not.toHaveBeenCalled();
await act(async () => finish());
expect(close).toHaveBeenCalledOnce();
});
Loading
Loading