fix(assistant): green CI round after the shared ChatGPT plan

- Tests that still knew the ChatGPT sign-in as personal only follow the
  admin's shared plan: the service takes the caller with their role, the
  admin tiles show ChatGPT, the controller tests cover the admin routes.
- The table refused an instance ChatGPT connection with a CHECK, so
  sharing the plan failed. A new migration rebuilds ai_connections
  without that check; the shipped migration stays as it was.
- useChatgptConnect grew past the function size limit: reading the
  clipboard and noticing the return to the tab are helpers of their own.
- The file link factory hands its overrides over apart from the row,
  like every other factory, which ends the deep type instantiation.
- Knip: exports only their own file used are private again, and the
  booking cap reads MAX_WRITES_PER_STEP instead of an alias.
- lint:i18n-keys reaches the tools' own action names through a key
  builder and the connection hints through literal keys.
- MMehrSheet stays in the assistant hints pair only.
This commit is contained in:
Maurice
2026-10-21 21:40:44 +00:00
parent 70c7d1ba3f
commit f0a3fe9dbb
23 changed files with 238 additions and 98 deletions
@@ -95,7 +95,8 @@ describe('the connection and the assistant', () => {
expect(screen.getByText('Everyone uses the connection below unless they connect their own.')).toBeInTheDocument();
expect(screen.getByText('No connection yet.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Own server/ })).toBeInTheDocument();
expect(screen.queryByText('Sign in with ChatGPT')).not.toBeInTheDocument();
// The admin may share their own ChatGPT plan with everyone, so its tile is offered too.
expect(screen.getByRole('button', { name: /Sign in with ChatGPT/ })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'AI Assistant' }));
expect(screen.getByDisplayValue('50')).toBeInTheDocument();
expect(screen.getByText('Keep chats')).toBeInTheDocument();
@@ -7,7 +7,7 @@ import type { Addon } from './addonModel';
* and MCP (TREK inside other AI apps). Their ids, rows and settings stay their
* own; only the page groups them. Assistant and parsing share one connection.
*/
export const AI_ADDON_IDS = ['ai_assistant', 'llm_parsing', 'mcp'] as const;
const AI_ADDON_IDS = ['ai_assistant', 'llm_parsing', 'mcp'] as const;
export type AiAddonId = (typeof AI_ADDON_IDS)[number];
/** Each one's glyph, keyed by id: the icon column of an existing install still holds what it was seeded with. */
@@ -230,7 +230,8 @@ describe('AssistantChangeCard: on the map', () => {
fireEvent.mouseEnter(screen.getByText('Ryoan-ji'));
expect(useAssistantStore.getState().mapLink?.hoveredId).toBeNull();
const row = screen.getByText('Pantheon').closest('[class*="py-2.5"]');
const row = screen.getByText('Pantheon').closest('[class*="rounded-[12px]"]');
expect(row).not.toBeNull();
expect(row).not.toHaveClass('bg-surface-hover');
act(() => useAssistantStore.setState({ mapLink: { tripId: TRIP, hoveredId: 'c1', source: 'map' } }));
expect(row).toHaveClass('bg-surface-hover');
@@ -123,10 +123,12 @@ function KindTile({
);
}
/** The verb as a quiet line over the name of what it touches. */
/** The key of a tool's own action name, for the tools TREK names one for. */
const toolKey = (tool: string) => `assistant.tool.${tool}`;
/** What the change does: the tool's own action where TREK names it, else add, change or remove. */
function verbLabel(preview: AssistantChangePreview, t: (key: string) => string): string {
const own = preview.tool ? `assistant.tool.${preview.tool}` : null;
const own = preview.tool ? toolKey(preview.tool) : null;
const named = own ? t(own) : null;
return named && named !== own ? named : t(`assistant.change.verb.${preview.verbKey}`);
}
@@ -6,7 +6,7 @@ import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useToast } from '../shared/Toast';
/** What the booking import reads (the server checks again), and how big one file may be. */
export const ATTACH_EXTENSIONS: readonly string[] = [
const ATTACH_EXTENSIONS: readonly string[] = [
'.pdf',
'.eml',
'.pkpass',
@@ -1,4 +1,4 @@
// FE-COMP-AI-CONNECT-PANEL-001 to FE-COMP-AI-CONNECT-PANEL-008: the two tiles, the key field, the ChatGPT paste step.
// FE-COMP-AI-CONNECT-PANEL-001 to FE-COMP-AI-CONNECT-PANEL-009: the mode tiles, the key field, the ChatGPT paste step.
import userEvent from '@testing-library/user-event';
import type { AiStatusResponse } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -63,7 +63,7 @@ describe('AiConnectPanel', () => {
expect(repo.chatgptStart).not.toHaveBeenCalled();
});
it('FE-COMP-AI-CONNECT-PANEL-002: the admin picks between a key and an own server, prefilled from AI parsing', () => {
it('FE-COMP-AI-CONNECT-PANEL-002: the admin picks between a key, their ChatGPT plan and an own server, prefilled from AI parsing', () => {
render(
<AiConnectPanel
scope="instance"
@@ -71,7 +71,9 @@ describe('AiConnectPanel', () => {
prefill={{ kind: 'custom', baseUrl: 'http://ollama:11434/v1', model: 'qwen3:8b' }}
/>
);
expect(screen.queryByText('Sign in with ChatGPT')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /Paste an API key/ })).toHaveAttribute('aria-pressed', 'false');
expect(screen.getByRole('button', { name: /Sign in with ChatGPT/ })).toHaveAttribute('aria-pressed', 'false');
expect(repo.chatgptStart).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: /Own server/ })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByText('Taken over from AI Parsing.')).toBeInTheDocument();
expect(screen.getByDisplayValue('http://ollama:11434/v1')).toBeInTheDocument();
@@ -183,4 +185,22 @@ describe('AiConnectPanel', () => {
render(<AiConnectPanel scope="user" onConnected={vi.fn()} />);
expect(screen.getByRole('button', { name: 'Using Claude? Connect in Claude' })).toBeInTheDocument();
});
it('FE-COMP-AI-CONNECT-PANEL-009: the admin signing in with ChatGPT is told the plan is shared, and the sign-in is for everyone', async () => {
const user = userEvent.setup();
const { unmount } = render(<AiConnectPanel scope="user" onConnected={vi.fn()} initialMode="chatgpt" />);
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledWith('user'));
expect(screen.queryByRole('note')).not.toBeInTheDocument();
unmount();
render(<AiConnectPanel scope="instance" onConnected={vi.fn()} />);
await user.click(screen.getByRole('button', { name: /Sign in with ChatGPT/ }));
expect(screen.getByRole('note')).toHaveTextContent(
'You share your own ChatGPT plan with everyone on this server: their chats count against your plan.'
);
await waitFor(() =>
expect(screen.getByRole('link', { name: /Open ChatGPT sign-in/ })).toHaveAttribute('href', FLOW.authorizeUrl)
);
expect(repo.chatgptStart).toHaveBeenLastCalledWith('instance');
});
});
@@ -384,11 +384,11 @@ function prefillModeOf(prefill: AiParsingPrefill | null): AiConnectMode | null {
}
/**
* Connecting a provider in under a minute: two tiles, and the form of the one
* picked below them. A user picks between signing in with ChatGPT and pasting
* a key; the admin, setting up the connection for everyone, between a key and
* an own server. ChatGPT is never shared across an instance, an own server
* never named by a user (#1772): the server refuses both, so they are not offered.
* Connecting a provider in under a minute: a tile for each way, and the form
* of the one picked below them. A user picks between signing in with ChatGPT
* and pasting a key; the admin, setting up the connection for everyone, between
* a key, their own ChatGPT plan and an own server. An own server is never named
* by a user (#1772): the server refuses it, so it is not offered.
*/
export default function AiConnectPanel({ scope, onConnected, initialMode, prefill = null }: AiConnectPanelProps) {
const { t } = useTranslation();
@@ -128,8 +128,6 @@ export function svgDataUrl(svg: string): string {
*/
export function aiSectionText(assistant: boolean, parsing: boolean): { titleKey: string; hintKey: string } {
if (!assistant) return { titleKey: 'settings.aiParsing.title', hintKey: 'assistant.connect.descriptionParsingOnly' };
return {
titleKey: 'assistant.connect.title',
hintKey: parsing ? 'assistant.connect.descriptionWithParsing' : 'assistant.connect.description',
};
if (parsing) return { titleKey: 'assistant.connect.title', hintKey: 'assistant.connect.descriptionWithParsing' };
return { titleKey: 'assistant.connect.title', hintKey: 'assistant.connect.description' };
}
@@ -1,5 +1,5 @@
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-012: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
import { act, renderHook, waitFor } from '@testing-library/react';
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-013: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
import { MemoryRouter, useLocation } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -218,6 +218,37 @@ describe('useChatgptConnect', () => {
expect(onConnected).not.toHaveBeenCalled();
expect(repo.chatgptStart).toHaveBeenCalledTimes(1);
});
it('FE-HOOK-AI-CONNECT-013: the clipboard fills the field where the browser lets it be read, else the field gets the cursor', async () => {
const readText = vi.fn(async () => 'not an address');
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { readText } });
Object.defineProperty(window, 'isSecureContext', { configurable: true, value: true });
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected: vi.fn() }), {
wrapper: wrapperAt(),
});
await waitFor(() => expect(result.current.flow).not.toBeNull());
const input = document.createElement('input');
document.body.append(input);
result.current.inputRef.current = input;
act(() => result.current.pasteFromClipboard());
await waitFor(() => expect(result.current.pasted).toBe('not an address'));
expect(repo.chatgptFinish).not.toHaveBeenCalled();
// Without a readable clipboard the button and the return from the sign-in window both focus the field.
Object.defineProperty(window, 'isSecureContext', { configurable: true, value: false });
act(() => result.current.pasteFromClipboard());
expect(document.activeElement).toBe(input);
input.blur();
act(() => {
result.current.change('');
result.current.markOpened();
});
fireEvent.focus(window);
expect(document.activeElement).toBe(input);
expect(readText).toHaveBeenCalledTimes(1);
input.remove();
});
});
describe('OpenRouter', () => {
@@ -150,6 +150,35 @@ export function useCustomConnect({
return { baseUrl, setBaseUrl, apiKey, setApiKey, model, setModel, host, ready, saving, error, submit };
}
/**
* Hands `onText` what the clipboard holds where the browser lets the page read
* it; where it does not, or the user refuses, `onUnreadable` runs instead.
*/
function readClipboard(onText: (text: string) => void, onUnreadable: () => void) {
if (!navigator.clipboard?.readText || !window.isSecureContext) {
onUnreadable();
return;
}
navigator.clipboard.readText().then(onText, onUnreadable);
}
/** Runs `onBack` each time the user comes back to this tab while `watching` holds. */
function useOnReturnToTab(watching: boolean, onBack: () => void) {
const back = useEffectEvent(onBack);
useEffect(() => {
if (!watching) return;
const onVisible = () => {
if (document.visibilityState === 'visible') back();
};
document.addEventListener('visibilitychange', onVisible);
window.addEventListener('focus', onVisible);
return () => {
document.removeEventListener('visibilitychange', onVisible);
window.removeEventListener('focus', onVisible);
};
}, [watching]);
}
/**
* Signing in with ChatGPT (K3). The sign-in address is fetched as soon as the
* step shows, so opening it is a plain link and no popup blocker interferes.
@@ -241,47 +270,22 @@ export function useChatgptConnect({
return true;
};
const focusField = () => inputRef.current?.focus();
/** Reads the address off the clipboard where the browser allows it, else hands the field the cursor. */
const pasteFromClipboard = () => {
if (!navigator.clipboard?.readText || !window.isSecureContext) {
inputRef.current?.focus();
return;
}
navigator.clipboard.readText().then(
(text) => {
if (!paste(text)) change(text);
},
() => inputRef.current?.focus()
);
};
const pasteFromClipboard = () =>
readClipboard((text) => {
if (!paste(text)) change(text);
}, focusField);
// Back from the sign-in window: the address the user just copied is taken
// off the clipboard where the browser allows it, else the field has the cursor.
const takeCopied = useEffectEvent(() => {
useOnReturnToTab(opened, () => {
if (pasted.trim() || busy) return;
if (!navigator.clipboard?.readText || !window.isSecureContext) {
inputRef.current?.focus();
return;
}
navigator.clipboard.readText().then(
(text) => {
if (!paste(text)) inputRef.current?.focus();
},
() => inputRef.current?.focus()
);
readClipboard((text) => {
if (!paste(text)) focusField();
}, focusField);
});
useEffect(() => {
if (!opened) return;
const onBack = () => {
if (document.visibilityState === 'visible') takeCopied();
};
document.addEventListener('visibilitychange', onBack);
window.addEventListener('focus', onBack);
return () => {
document.removeEventListener('visibilitychange', onBack);
window.removeEventListener('focus', onBack);
};
}, [opened]);
return {
flow,