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
2 changes: 1 addition & 1 deletion frontend/components/studio/canvas-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function CanvasPanel({ items, onRemove }: CanvasPanelProps) {
const roleName = useRoleLabel();
const roleLabel = (type: string) => {
const role = ITEM_ROLE[type];
return role ? roleName(role) : type;
return role ? roleName(role) : typeLabel(type);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Unknown types stay in English

When a canvas or studio item has a type with no matching catalog entry, typeLabel calls useCatalogLabel, which falls back to title-cased raw text for an absent type, so the item label remains in English instead of the current locale.

Provide a localized fallback for types that are absent from the catalog instead of displaying humanized raw text.

Also at frontend/tests/studio-panels-i18n.test.tsx:24.

Prompt for AI agents
In `frontend/components/studio/canvas-panel.tsx` at line 23:

**Unknown types stay in English**

When a canvas or studio item has a type with no matching catalog entry, `typeLabel` calls `useCatalogLabel`, which falls back to title-cased raw text for an absent type, so the item label remains in English instead of the current locale.

Provide a localized fallback for types that are absent from the catalog instead of displaying humanized raw text.

Also at `frontend/tests/studio-panels-i18n.test.tsx:24`.

};
if (items.length === 0) {
return (
Expand Down
5 changes: 3 additions & 2 deletions frontend/components/studio/details-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export function DetailsPanel({
onAiMerge,
}: DetailsPanelProps) {
const typeLabel = useTypeLabel();
const itemLabel = (item: StudioItem) => item.name || typeLabel(item.type);
const t = useTranslations('outfits.details');
const [aiLoading, setAiLoading] = useState(false);
const warnings = computeWarnings(items, t);
Expand All @@ -68,9 +69,9 @@ export function DetailsPanel({
onAiMerge(merged);

if (skipped.length > 0) {
for (const { item, reason } of skipped) {
for (const { item, conflict } of skipped) {
toast.info(
t('skippedItem', { name: item.name || typeLabel(item.type), reason })
t('skippedItem', { name: itemLabel(item), other: itemLabel(conflict) })
);
}
} else if (merged.length > items.length) {
Expand Down
16 changes: 9 additions & 7 deletions frontend/lib/studio/ai-assist-merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,31 @@ import { canonicalItemOrder, slotsForType } from '@/lib/studio/canonical-order';

export interface MergeResult<T extends { id: string; type: string }> {
merged: T[];
skipped: Array<{ item: T; reason: string }>;
skipped: Array<{ item: T; conflict: T }>;
}

export function mergeAiAssist<T extends { id: string; type: string }>(
canvas: T[],
aiItems: T[]
): MergeResult<T> {
const existingSlots = new Set<string>(canvas.flatMap((item) => slotsForType(item.type)));
const slotHolders = new Map<string, T>(
canvas.flatMap((item) => slotsForType(item.type).map((slot) => [slot, item] as const))
);

const canvasIds = new Set(canvas.map((c) => c.id));
const merged: T[] = [...canvas];
const skipped: Array<{ item: T; reason: string }> = [];
const skipped: Array<{ item: T; conflict: T }> = [];

for (const item of aiItems) {
if (canvasIds.has(item.id)) continue;
const slots = slotsForType(item.type);
const taken = slots.find((slot) => existingSlots.has(slot));
if (taken) {
skipped.push({ item, reason: `already have a ${taken.replace('_', ' ')}` });
const conflict = slots.map((slot) => slotHolders.get(slot)).find(Boolean);
if (conflict) {
skipped.push({ item, conflict });
continue;
}
merged.push(item);
slots.forEach((slot) => existingSlots.add(slot));
slots.forEach((slot) => slotHolders.set(slot, item));
}

return { merged: canonicalItemOrder(merged), skipped };
Expand Down
2 changes: 1 addition & 1 deletion frontend/messages/de/outfits.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"required": "erforderlich",
"occasion": "Anlass",
"pickOccasion": "Wähle vor dem Speichern einen Anlass.",
"skippedItem": "{name} übersprungen: {reason}",
"skippedItem": "{name} übersprungen: Platz bereits belegt durch {other}",
"warnings": {
"multipleBottoms": "Mehrere Unterteile ausgewählt.",
"noBottoms": "Kein Unterteil ausgewählt.",
Expand Down
2 changes: 1 addition & 1 deletion frontend/messages/en/outfits.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"required": "required",
"occasion": "Occasion",
"pickOccasion": "Pick an occasion before saving.",
"skippedItem": "Skipped {name}: {reason}",
"skippedItem": "Skipped {name}: that spot is already taken by {other}",
"warnings": {
"multipleBottoms": "Multiple bottoms selected.",
"noBottoms": "No bottoms selected.",
Expand Down
2 changes: 1 addition & 1 deletion frontend/messages/fr/outfits.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"required": "obligatoire",
"occasion": "Occasion",
"pickOccasion": "Choisissez une occasion avant de sauvegarder.",
"skippedItem": "{name} ignoré : {reason}",
"skippedItem": "Impossible d’ajouter {name} : la place est déjà prise par {other}",
"warnings": {
"multipleBottoms": "Plusieurs bas sélectionnés.",
"noBottoms": "Aucun bas sélectionné.",
Expand Down
2 changes: 1 addition & 1 deletion frontend/messages/it/outfits.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"required": "obbligatorio",
"occasion": "Occasione",
"pickOccasion": "Scegli un'occasione prima di salvare.",
"skippedItem": "{name} saltato: {reason}",
"skippedItem": "Impossibile aggiungere {name}: il posto è già occupato da {other}",
"warnings": {
"multipleBottoms": "Più bassi selezionati.",
"noBottoms": "Nessun basso selezionato.",
Expand Down
2 changes: 1 addition & 1 deletion frontend/messages/ja/outfits.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"required": "必須",
"occasion": "シーン",
"pickOccasion": "保存する前にシーンを選んでください。",
"skippedItem": "{name}をスキップ:{reason}",
"skippedItem": "{name}をスキップ:その位置には既に{other}があります",
"warnings": {
"multipleBottoms": "ボトムスが複数選択されています。",
"noBottoms": "ボトムスが選択されていません。",
Expand Down
2 changes: 1 addition & 1 deletion frontend/messages/ko/outfits.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"required": "필수",
"occasion": "상황",
"pickOccasion": "저장하기 전에 상황을 선택하세요.",
"skippedItem": "{name} 건너뜀: {reason}",
"skippedItem": "{name} 아이템은 건너뛰었어요. 같은 자리에 {other} 아이템이 이미 있어요",
"warnings": {
"multipleBottoms": "하의가 여러 개 선택되었어요.",
"noBottoms": "하의가 선택되지 않았어요.",
Expand Down
2 changes: 1 addition & 1 deletion frontend/messages/zh-CN/outfits.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"required": "必填",
"occasion": "场合",
"pickOccasion": "保存前请选择一个场合。",
"skippedItem": "已跳过 {name}:{reason}",
"skippedItem": "已跳过 {name}:该位置已有 {other}",
"warnings": {
"multipleBottoms": "选择了多件下装。",
"noBottoms": "未选择下装。",
Expand Down
2 changes: 1 addition & 1 deletion frontend/messages/zh-TW/outfits.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"required": "必填",
"occasion": "場合",
"pickOccasion": "儲存前請先選擇場合。",
"skippedItem": "已略過 {name}:{reason}",
"skippedItem": "已略過 {name}:該位置已有 {other}",
"warnings": {
"multipleBottoms": "選擇了多件下身單品。",
"noBottoms": "未選擇下身單品。",
Expand Down
82 changes: 82 additions & 0 deletions frontend/tests/studio-panels-i18n.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'

const post = vi.hoisted(() => vi.fn())
const toast = vi.hoisted(() => ({ info: vi.fn(), success: vi.fn(), error: vi.fn() }))

vi.mock('@/lib/api', () => ({ api: { post }, getErrorMessage: (_: unknown, fallback: string) => fallback }))
vi.mock('sonner', () => ({ toast }))
// The global next-intl mock drops the namespace and ICU values, so this one keeps both to
// prove each label comes from the catalogs rather than from raw values.
vi.mock('next-intl', () => ({
useLocale: () => 'en',
useFormatter: () => ({
number: (value: number) => String(value),
list: (items: string[]) => items.join(', '),
}),
useTranslations: (namespace: string) => {
const t = (key: string, values?: Record<string, unknown>) =>
`${namespace}.${key}${values ? ` ${JSON.stringify(values)}` : ''}`
t.raw = t
t.rich = t
t.markup = t
t.has = () => true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Unknown type expects a nonexistent translation

When the test is meant to verify the label produced with the real catalog, when kimono is absent from the real English type catalog, useCatalogLabel correctly falls back to Kimono, but this mock forces t.has to return true and fabricates constants.types.kimono, so the CanvasPanel assertion passes with output the real catalog would not produce.

Use a type present in the catalog for the translation assertion, or assert the readable fallback for kimono and make the mock's has reflect catalog membership.

Prompt for AI agents
In `frontend/tests/studio-panels-i18n.test.tsx` at line 23:

**Unknown type expects a nonexistent translation**

When the test is meant to verify the label produced with the real catalog, when `kimono` is absent from the real English type catalog, `useCatalogLabel` correctly falls back to `Kimono`, but this mock forces `t.has` to return true and fabricates `constants.types.kimono`, so the CanvasPanel assertion passes with output the real catalog would not produce.

Use a type present in the catalog for the translation assertion, or assert the readable fallback for `kimono` and make the mock's `has` reflect catalog membership.

return t
},
}))

import { CanvasPanel } from '@/components/studio/canvas-panel'
import { DetailsPanel } from '@/components/studio/details-panel'
import type { StudioItem } from '@/lib/studio/editor-state'

function studioItem(id: string, type: string, name: string | null = null): StudioItem {
return { id, type, name, thumbnail_url: null, image_url: null, primary_color: 'blue' }
}

function assistWith(canvas: StudioItem[], suggested: StudioItem[]) {
post.mockResolvedValue({ items: suggested })
render(
<DetailsPanel
items={canvas}
name=""
occasion="casual"
onNameChange={vi.fn()}
onOccasionChange={vi.fn()}
onAiMerge={vi.fn()}
/>
)
fireEvent.click(screen.getByText('outfits.details.letAiFinish'))
}

beforeEach(() => {
vi.clearAllMocks()
})

describe('DetailsPanel AI assist', () => {
it('names the canvas piece that already fills the spot', async () => {
assistWith([studioItem('1', 'shirt', 'Shirt')], [studioItem('2', 't-shirt', 'Tee')])
await waitFor(() =>
expect(toast.info).toHaveBeenCalledWith(
'outfits.details.skippedItem {"name":"Tee","other":"Shirt"}'
)
)
})

it('falls back to translated type labels for unnamed pieces', async () => {
assistWith([studioItem('1', 'dress')], [studioItem('2', 'shirt')])
await waitFor(() =>
expect(toast.info).toHaveBeenCalledWith(
'outfits.details.skippedItem {"name":"constants.types.shirt","other":"constants.types.dress"}'
)
)
})
})

describe('CanvasPanel', () => {
it('labels a type without a role through the type catalog', () => {
const kimono = { ...studioItem('1', 'kimono', 'Kimono'), thumbnail_url: '/kimono.jpg' }
render(<CanvasPanel items={[kimono]} onRemove={vi.fn()} />)
expect(screen.getByText('constants.types.kimono')).toBeTruthy()
expect(screen.queryByText('kimono')).toBeNull()
})
})
6 changes: 3 additions & 3 deletions frontend/tests/studio-suit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('mergeAiAssist with multi-slot items', () => {
it('skips trousers when a suit is already on the canvas', () => {
const { merged, skipped } = mergeAiAssist([makeItem('1', 'suit')], [makeItem('2', 'pants')]);
expect(merged).toHaveLength(1);
expect(skipped.map((s) => s.item.id)).toEqual(['2']);
expect(skipped.map((s) => [s.item.id, s.conflict.id])).toEqual([['2', '1']]);
});

it('skips a suit when the canvas already has trousers', () => {
Expand All @@ -41,13 +41,13 @@ describe('mergeAiAssist with multi-slot items', () => {
[makeItem('3', 'suit')]
);
expect(merged).toHaveLength(2);
expect(skipped.map((s) => s.item.id)).toEqual(['3']);
expect(skipped.map((s) => [s.item.id, s.conflict.id])).toEqual([['3', '2']]);
});

it('skips a shirt when a dress is already on the canvas', () => {
const { merged, skipped } = mergeAiAssist([makeItem('1', 'dress')], [makeItem('2', 'shirt')]);
expect(merged).toHaveLength(1);
expect(skipped[0].reason).toContain('base top');
expect(skipped[0].conflict.id).toBe('1');
});
});

Expand Down
10 changes: 9 additions & 1 deletion frontend/tests/studio.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,15 @@ describe('mergeAiAssist', () => {
expect(merged).toHaveLength(2);
expect(skipped).toHaveLength(1);
expect(skipped[0].item.id).toBe('2');
expect(skipped[0].reason).toContain('base top');
expect(skipped[0].conflict.id).toBe('1');
});

it('names an AI item merged earlier in the same call as the conflict', () => {
const canvas = [makeItem('1', 'sneakers')];
const aiItems = [makeItem('2', 'dress'), makeItem('3', 'shirt')];
const { merged, skipped } = mergeAiAssist(canvas, aiItems);
expect(merged.map((item) => item.id)).toEqual(['2', '1']);
expect(skipped.map((s) => [s.item.id, s.conflict.id])).toEqual([['3', '2']]);
});

it('skips items already on canvas', () => {
Expand Down
Loading