Preserve partial creation replies on stream failure
CI / verify (push) Has been cancelled

This commit is contained in:
kdletters
2026-05-05 11:31:50 +08:00
parent 100fee7e7a
commit 995661e7cc
299 changed files with 13805 additions and 1429 deletions
@@ -107,12 +107,17 @@ test('creation hub reflects updated draft title summary and counts after rerende
const rpgButton = screen.getByRole('button', { name: //u });
const puzzleButton = screen.getByRole('button', { name: /.*/u });
const match3dButton = screen.getByRole('button', { name: //u });
const squareHoleButton = screen.getByRole('button', { name: //u });
expect(
rpgButton.compareDocumentPosition(puzzleButton) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expect((rpgButton as HTMLButtonElement).disabled).toBe(false);
expect((match3dButton as HTMLButtonElement).disabled).toBe(false);
expect((squareHoleButton as HTMLButtonElement).disabled).toBe(false);
expect(
within(squareHoleButton).getAllByText('反直觉形状分拣').length,
).toBeGreaterThan(0);
expect(
within(match3dButton).getAllByText('经典消除玩法').length,
).toBeGreaterThan(0);
@@ -4,6 +4,7 @@ import type { BigFishWorkSummary } from '../../../packages/shared/src/contracts/
import type { CustomWorldWorkSummary } from '../../../packages/shared/src/contracts/customWorldAgent';
import type { Match3DWorkSummary } from '../../../packages/shared/src/contracts/match3dWorks';
import type { PuzzleWorkSummary } from '../../../packages/shared/src/contracts/puzzleWorkSummary';
import type { SquareHoleWorkSummary } from '../../../packages/shared/src/contracts/squareHoleWorks';
import type { CustomWorldLibraryEntry } from '../../../packages/shared/src/contracts/runtime';
import type { CustomWorldProfile } from '../../types';
import type { PlatformCreationTypeId } from '../platform-entry/platformEntryCreationTypes';
@@ -48,6 +49,9 @@ type CustomWorldCreationHubProps = {
match3dItems?: Match3DWorkSummary[];
onOpenMatch3DDetail?: (item: Match3DWorkSummary) => void;
onDeleteMatch3D?: ((item: Match3DWorkSummary) => void) | null;
squareHoleItems?: SquareHoleWorkSummary[];
onOpenSquareHoleDetail?: (item: SquareHoleWorkSummary) => void;
onDeleteSquareHole?: ((item: SquareHoleWorkSummary) => void) | null;
puzzleItems?: PuzzleWorkSummary[];
onOpenPuzzleDetail?: (item: PuzzleWorkSummary) => void;
onDeletePuzzle?: ((item: PuzzleWorkSummary) => void) | null;
@@ -137,6 +141,9 @@ export function CustomWorldCreationHub({
match3dItems = [],
onOpenMatch3DDetail,
onDeleteMatch3D = null,
squareHoleItems = [],
onOpenSquareHoleDetail,
onDeleteSquareHole = null,
puzzleItems = [],
onOpenPuzzleDetail,
onDeletePuzzle = null,
@@ -152,10 +159,12 @@ export function CustomWorldCreationHub({
rpgLibraryEntries,
bigFishItems,
match3dItems,
squareHoleItems,
puzzleItems,
canDeleteRpg: Boolean(onDeletePublished),
canDeleteBigFish: Boolean(onDeleteBigFish),
canDeleteMatch3D: Boolean(onDeleteMatch3D),
canDeleteSquareHole: Boolean(onDeleteSquareHole),
canDeletePuzzle: Boolean(onDeletePuzzle),
}),
[
@@ -164,10 +173,12 @@ export function CustomWorldCreationHub({
match3dItems,
onDeleteBigFish,
onDeleteMatch3D,
onDeleteSquareHole,
onDeletePublished,
onDeletePuzzle,
puzzleItems,
rpgLibraryEntries,
squareHoleItems,
],
);
const [metricSnapshot] = useState<WorkMetricSnapshot>(() =>
@@ -201,6 +212,9 @@ export function CustomWorldCreationHub({
case 'match3d':
onOpenMatch3DDetail?.(item.source.item);
return;
case 'square-hole':
onOpenSquareHoleDetail?.(item.source.item);
return;
case 'rpg':
if (item.status === 'draft') {
onOpenDraft(item.source.item);
@@ -237,6 +251,12 @@ export function CustomWorldCreationHub({
onDeleteMatch3D?.(sourceItem);
};
}
case 'square-hole': {
const sourceItem = item.source.item;
return () => {
onDeleteSquareHole?.(sourceItem);
};
}
case 'rpg': {
const sourceItem = item.source.item;
return () => {
@@ -40,7 +40,7 @@ export function CustomWorldCreationStartCard({
</span>
</div>
<div className="-mx-1 flex snap-x gap-2 overflow-x-auto px-1 pb-1 scrollbar-hide sm:mx-0 sm:grid sm:gap-3 sm:overflow-visible sm:px-0 sm:pb-0 sm:grid-cols-2 xl:grid-cols-5 xl:gap-2.5">
<div className="-mx-1 flex snap-x gap-2 overflow-x-auto px-1 pb-1 scrollbar-hide sm:mx-0 sm:grid sm:gap-3 sm:overflow-visible sm:px-0 sm:pb-0 sm:grid-cols-2 xl:grid-cols-6 xl:gap-2.5">
{visibleCreationTypes.map((item) => {
const disabled = item.locked || busy;
@@ -2,16 +2,23 @@ import type { BigFishWorkSummary } from '../../../packages/shared/src/contracts/
import type { CustomWorldWorkSummary } from '../../../packages/shared/src/contracts/customWorldAgent';
import type { Match3DWorkSummary } from '../../../packages/shared/src/contracts/match3dWorks';
import type { PuzzleWorkSummary } from '../../../packages/shared/src/contracts/puzzleWorkSummary';
import type { SquareHoleWorkSummary } from '../../../packages/shared/src/contracts/squareHoleWorks';
import type { CustomWorldLibraryEntry } from '../../../packages/shared/src/contracts/runtime';
import { buildPublicWorkStagePath } from '../../routing/appPageRoutes';
import {
buildBigFishPublicWorkCode,
buildMatch3DPublicWorkCode,
buildPuzzlePublicWorkCode,
buildSquareHolePublicWorkCode,
} from '../../services/publicWorkCode';
import type { CustomWorldProfile } from '../../types';
export type CreationWorkShelfKind = 'rpg' | 'big-fish' | 'match3d' | 'puzzle';
export type CreationWorkShelfKind =
| 'rpg'
| 'big-fish'
| 'match3d'
| 'square-hole'
| 'puzzle';
export type CreationWorkShelfStatus = 'draft' | 'published';
export type CreationWorkShelfBadgeTone = 'warm' | 'success' | 'neutral';
@@ -56,6 +63,10 @@ export type CreationWorkShelfSource =
kind: 'match3d';
item: Match3DWorkSummary;
}
| {
kind: 'square-hole';
item: SquareHoleWorkSummary;
}
| {
kind: 'puzzle';
item: PuzzleWorkSummary;
@@ -87,10 +98,12 @@ export function buildCreationWorkShelfItems(params: {
rpgLibraryEntries?: CustomWorldLibraryEntry<CustomWorldProfile>[];
bigFishItems: BigFishWorkSummary[];
match3dItems?: Match3DWorkSummary[];
squareHoleItems?: SquareHoleWorkSummary[];
puzzleItems: PuzzleWorkSummary[];
canDeleteRpg?: boolean;
canDeleteBigFish?: boolean;
canDeleteMatch3D?: boolean;
canDeleteSquareHole?: boolean;
canDeletePuzzle?: boolean;
}) {
const {
@@ -98,10 +111,12 @@ export function buildCreationWorkShelfItems(params: {
rpgLibraryEntries = [],
bigFishItems,
match3dItems = [],
squareHoleItems = [],
puzzleItems,
canDeleteRpg = false,
canDeleteBigFish = false,
canDeleteMatch3D = false,
canDeleteSquareHole = false,
canDeletePuzzle = false,
} = params;
@@ -115,6 +130,9 @@ export function buildCreationWorkShelfItems(params: {
...match3dItems.map((item) =>
mapMatch3DWorkToShelfItem(item, canDeleteMatch3D),
),
...squareHoleItems.map((item) =>
mapSquareHoleWorkToShelfItem(item, canDeleteSquareHole),
),
...puzzleItems.map((item) =>
mapPuzzleWorkToShelfItem(item, canDeletePuzzle),
),
@@ -319,6 +337,50 @@ function mapPuzzleWorkToShelfItem(
};
}
function mapSquareHoleWorkToShelfItem(
item: SquareHoleWorkSummary,
canDelete: boolean,
): CreationWorkShelfItem {
const status = item.publicationStatus === 'published' ? 'published' : 'draft';
const publicWorkCode =
status === 'published'
? buildSquareHolePublicWorkCode(item.profileId)
: null;
return {
id: item.workId,
kind: 'square-hole',
status,
title: item.gameName,
summary: item.summary,
updatedAt: item.updatedAt,
coverImageSrc: item.coverImageSrc ?? null,
coverRenderMode: 'image',
coverCharacterImageSrcs: [],
publicWorkCode,
sharePath:
publicWorkCode && status === 'published'
? buildPublicWorkStagePath('work-detail', publicWorkCode)
: null,
openActionLabel: status === 'published' ? '查看详情' : '继续创作',
canDelete,
canShare: status === 'published' && Boolean(publicWorkCode),
badges: [
buildStatusBadge(status),
{ id: 'type', label: '方洞', tone: 'neutral' },
],
metrics:
status === 'published'
? buildPublishedMetrics({
playCount: item.playCount,
remixCount: 0,
likeCount: 0,
})
: [],
source: { kind: 'square-hole', item },
};
}
function buildPublishedMetrics(params: {
playCount?: number | null;
remixCount?: number | null;
@@ -12,6 +12,7 @@ export interface PlatformEntryCreationTypeModalProps {
onSelectRpg: () => void;
onSelectBigFish: () => void;
onSelectMatch3D: () => void;
onSelectSquareHole: () => void;
onSelectPuzzle: () => void;
}
@@ -74,6 +75,7 @@ export function PlatformEntryCreationTypeModal({
onSelectRpg,
onSelectBigFish,
onSelectMatch3D,
onSelectSquareHole,
onSelectPuzzle,
}: PlatformEntryCreationTypeModalProps) {
if (!isOpen) {
@@ -93,7 +95,7 @@ export function PlatformEntryCreationTypeModal({
closeDisabled={isBusy}
size="lg"
>
<div className="grid gap-3 sm:grid-cols-5">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{visibleCreationTypes.map((item) => (
<CreationTypeCard
key={item.id}
@@ -109,6 +111,9 @@ export function PlatformEntryCreationTypeModal({
if (item.id === 'match3d') {
onSelectMatch3D();
}
if (item.id === 'square-hole') {
onSelectSquareHole();
}
if (item.id === 'puzzle') {
onSelectPuzzle();
}
File diff suppressed because it is too large Load Diff
@@ -60,6 +60,9 @@ function getSourceLabel(entry: PlatformPublicGalleryCard) {
if ('sourceType' in entry && entry.sourceType === 'match3d') {
return '抓大鹅';
}
if ('sourceType' in entry && entry.sourceType === 'square-hole') {
return '方洞挑战';
}
return 'RPG';
}
@@ -35,6 +35,7 @@ test('new work entry config controls visibility and open order', () => {
'rpg',
'puzzle',
'match3d',
'square-hole',
'airp',
'visual-novel',
]);
@@ -25,6 +25,9 @@ export type SelectionStage =
| 'match3d-agent-workspace'
| 'match3d-result'
| 'match3d-runtime'
| 'square-hole-agent-workspace'
| 'square-hole-result'
| 'square-hole-runtime'
| 'puzzle-agent-workspace'
| 'puzzle-generating'
| 'puzzle-result'
@@ -0,0 +1,137 @@
/* @vitest-environment jsdom */
import { act, render, screen, waitFor } from '@testing-library/react';
import { useEffect } from 'react';
import { expect, test, vi } from 'vitest';
import { usePlatformCreationAgentFlowController } from './usePlatformCreationAgentFlowController';
type TestSession = {
sessionId: string;
messages: Array<{
id: string;
role: string;
kind?: string;
text: string;
createdAt?: string;
}>;
};
type TestMessagePayload = {
clientMessageId: string;
text: string;
};
function TestHarness({
streamMessage,
}: {
streamMessage: (
sessionId: string,
payload: TestMessagePayload,
options?: { onUpdate?: (text: string) => void },
) => Promise<TestSession>;
}) {
const flow = usePlatformCreationAgentFlowController<
TestSession,
Record<string, never>,
{ session: TestSession },
TestMessagePayload,
{ action: string },
{ session: TestSession }
>({
client: {
createSession: async () => ({
session: {
sessionId: 'session-1',
messages: [],
},
}),
getSession: async () => ({
session: {
sessionId: 'session-1',
messages: [],
},
}),
streamMessage,
executeAction: async () => ({
session: {
sessionId: 'session-1',
messages: [],
},
}),
selectSession: (response) => response.session,
},
createPayload: {},
workspaceStage: 'match3d-agent-workspace',
resultStage: 'match3d-result',
platformStage: 'platform',
isCompileAction: () => false,
resolveErrorMessage: (error, fallback) =>
error instanceof Error ? error.message : fallback,
errorMessages: {
open: '打开失败',
restoreMissingSession: '缺少会话',
restore: '恢复失败',
submit: '发送失败',
execute: '执行失败',
},
enterCreateTab: () => {},
setSelectionStage: () => {},
});
useEffect(() => {
void flow.openWorkspace({});
}, []);
return (
<div>
<button
type="button"
onClick={() => {
void flow.submitMessage({
clientMessageId: 'client-message-1',
text: '做一个办公室文具方洞挑战',
});
}}
>
</button>
<div data-testid="messages">
{flow.session?.messages.map((message) => (
<div key={message.id}>{`${message.role}:${message.kind}:${message.text}`}</div>
))}
</div>
{flow.error ? <div>{flow.error}</div> : null}
</div>
);
}
test('creation agent flow preserves streamed assistant text when stream fails', async () => {
const streamMessage = vi.fn(async (_sessionId, _payload, options) => {
options?.onUpdate?.('先把方洞万能的反差定住。');
throw new Error('方洞挑战聊天生成失败:LLM 请求超时');
});
render(<TestHarness streamMessage={streamMessage} />);
await waitFor(() => {
expect(screen.getByRole('button', { name: '发送' })).toBeTruthy();
});
await act(async () => {
screen.getByRole('button', { name: '发送' }).click();
});
await waitFor(() => {
expect(
screen.getByText('方洞挑战聊天生成失败:LLM 请求超时'),
).toBeTruthy();
});
expect(screen.getByTestId('messages').textContent).toContain(
'user:chat:做一个办公室文具方洞挑战',
);
expect(screen.getByTestId('messages').textContent).toContain(
'assistant:warning:先把方洞万能的反差定住。',
);
});
@@ -1,4 +1,4 @@
import { useCallback, useState } from 'react';
import { useCallback, useRef, useState } from 'react';
import type { TextStreamOptions } from '../../services/aiTypes';
import type { SelectionStage } from './platformEntryTypes';
@@ -104,6 +104,16 @@ function buildOptimisticMessage<TMessagePayload extends CreationAgentMessageLike
};
}
function buildInterruptedAssistantMessage(text: string) {
return {
id: `assistant-interrupted-${Date.now().toString(36)}`,
role: 'assistant',
kind: 'warning',
text: text.trim(),
createdAt: new Date().toISOString(),
};
}
/**
* 轻量作品 Agent 创作流程的通用前端控制器。
* 这里只处理跨玩法一致的会话、流式消息、忙碌态与草稿恢复,玩法结果页和运行态动作留给外层。
@@ -130,6 +140,18 @@ export function usePlatformCreationAgentFlowController<
const [isBusy, setIsBusy] = useState(false);
const [streamingReplyText, setStreamingReplyText] = useState('');
const [isStreamingReply, setIsStreamingReply] = useState(false);
const latestStreamingReplyTextRef = useRef('');
const updateStreamingReplyText = useCallback((text: string) => {
latestStreamingReplyTextRef.current = text;
setStreamingReplyText(text);
}, []);
const resetStreamingReply = useCallback(() => {
latestStreamingReplyTextRef.current = '';
setStreamingReplyText('');
setIsStreamingReply(false);
}, []);
const openWorkspace = useCallback(async (createPayload?: TCreatePayload) => {
if (isBusy) {
@@ -138,8 +160,7 @@ export function usePlatformCreationAgentFlowController<
setIsBusy(true);
setError(null);
setStreamingReplyText('');
setIsStreamingReply(false);
resetStreamingReply();
try {
const response = await options.client.createSession(
@@ -159,7 +180,7 @@ export function usePlatformCreationAgentFlowController<
} finally {
setIsBusy(false);
}
}, [isBusy, options]);
}, [isBusy, options, resetStreamingReply]);
const restoreDraft = useCallback(
async (sessionId: string | null | undefined) => {
@@ -171,8 +192,7 @@ export function usePlatformCreationAgentFlowController<
setIsBusy(true);
setError(null);
setStreamingReplyText('');
setIsStreamingReply(false);
resetStreamingReply();
try {
const response = await options.client.getSession(normalizedSessionId);
@@ -194,7 +214,7 @@ export function usePlatformCreationAgentFlowController<
setIsBusy(false);
}
},
[options],
[options, resetStreamingReply],
);
const submitMessage = useCallback(
@@ -206,7 +226,7 @@ export function usePlatformCreationAgentFlowController<
const optimisticMessage = buildOptimisticMessage(payload);
setError(null);
setStreamingReplyText('');
updateStreamingReplyText('');
setIsStreamingReply(true);
setSession((current) =>
current
@@ -223,12 +243,28 @@ export function usePlatformCreationAgentFlowController<
session.sessionId,
payload,
{
onUpdate: setStreamingReplyText,
onUpdate: updateStreamingReplyText,
},
);
setSession(nextSession);
setStreamingReplyText('');
updateStreamingReplyText('');
} catch (caughtError) {
const interruptedReplyText =
latestStreamingReplyTextRef.current.trim();
// 上游流可能在已经吐出可读回复后才失败;把这段回复落进本地消息列表,避免 UI 收尾时突然消失。
if (interruptedReplyText) {
const interruptedMessage =
buildInterruptedAssistantMessage(interruptedReplyText);
setSession((current) =>
current
? {
...current,
messages: [...current.messages, interruptedMessage],
updatedAt: interruptedMessage.createdAt,
}
: current,
);
}
setError(
options.resolveErrorMessage(caughtError, options.errorMessages.submit),
);
@@ -236,7 +272,7 @@ export function usePlatformCreationAgentFlowController<
setIsStreamingReply(false);
}
},
[isStreamingReply, options, session],
[isStreamingReply, options, session, updateStreamingReplyText],
);
const executeAction = useCallback(
@@ -284,17 +320,15 @@ export function usePlatformCreationAgentFlowController<
const leaveFlow = useCallback(() => {
setError(null);
setStreamingReplyText('');
setIsStreamingReply(false);
resetStreamingReply();
options.enterCreateTab();
options.setSelectionStage(options.platformStage);
}, [options]);
}, [options, resetStreamingReply]);
const resetTransientState = useCallback(() => {
setError(null);
setStreamingReplyText('');
setIsStreamingReply(false);
}, []);
resetStreamingReply();
}, [resetStreamingReply]);
return {
session,
+13 -2
View File
@@ -82,6 +82,7 @@ import {
isBigFishGalleryEntry,
isMatch3DGalleryEntry,
isPuzzleGalleryEntry,
isSquareHoleGalleryEntry,
type PlatformPublicGalleryCard,
type PlatformWorldCardLike,
resolvePlatformWorldCoverImage,
@@ -1134,7 +1135,9 @@ function buildPublicGalleryCardKey(entry: PlatformPublicGalleryCard) {
? 'puzzle'
: isMatch3DGalleryEntry(entry)
? 'match3d'
: 'rpg';
: isSquareHoleGalleryEntry(entry)
? 'square-hole'
: 'rpg';
return `${kind}:${entry.ownerUserId}:${entry.profileId}`;
}
@@ -1242,7 +1245,9 @@ function describePublicGalleryCardKind(entry: PlatformPublicGalleryCard) {
? '拼图'
: isMatch3DGalleryEntry(entry)
? '抓鹅'
: describePlatformThemeLabel(entry.themeMode);
: isSquareHoleGalleryEntry(entry)
? '方洞'
: describePlatformThemeLabel(entry.themeMode);
return formatPlatformWorkDisplayTag(kind);
}
@@ -1514,6 +1519,12 @@ function formatPlayedWorkType(value: string | null | undefined) {
if (normalizedValue === 'puzzle') {
return '拼图';
}
if (normalizedValue === 'match3d' || normalizedValue === 'match_3d') {
return '抓鹅';
}
if (normalizedValue === 'square-hole' || normalizedValue === 'square_hole') {
return '方洞';
}
if (normalizedValue === 'big_fish' || normalizedValue === 'big-fish') {
return '大鱼';
}
@@ -2,6 +2,7 @@ import type { BigFishWorkSummary } from '../../../packages/shared/src/contracts/
import type { Match3DWorkSummary } from '../../../packages/shared/src/contracts/match3dWorks';
import type { PuzzleDraftLevel } from '../../../packages/shared/src/contracts/puzzleAgentDraft';
import type { PuzzleWorkSummary } from '../../../packages/shared/src/contracts/puzzleWorkSummary';
import type { SquareHoleWorkSummary } from '../../../packages/shared/src/contracts/squareHoleWorks';
import type {
CustomWorldGalleryCard,
CustomWorldLibraryEntry,
@@ -12,6 +13,7 @@ import {
buildBigFishPublicWorkCode,
buildMatch3DPublicWorkCode,
buildPuzzlePublicWorkCode,
buildSquareHolePublicWorkCode,
} from '../../services/publicWorkCode';
import type { CustomWorldProfile } from '../../types';
@@ -23,6 +25,7 @@ export type PlatformWorldCardLike =
| CustomWorldLibraryEntry<CustomWorldProfile>
| PlatformBigFishGalleryCard
| PlatformMatch3DGalleryCard
| PlatformSquareHoleGalleryCard
| PlatformPuzzleGalleryCard;
export type PlatformPuzzleGalleryCard = {
@@ -97,10 +100,33 @@ export type PlatformMatch3DGalleryCard = {
updatedAt: string;
};
export type PlatformSquareHoleGalleryCard = {
sourceType: 'square-hole';
workId: string;
profileId: string;
sourceSessionId?: string | null;
publicWorkCode: string;
ownerUserId: string;
authorDisplayName: string;
worldName: string;
subtitle: string;
summaryText: string;
coverImageSrc: string | null;
themeTags: string[];
playCount?: number;
remixCount?: number;
likeCount?: number;
recentPlayCount7d?: number;
visibility: 'published';
publishedAt: string | null;
updatedAt: string;
};
export type PlatformPublicGalleryCard =
| CustomWorldGalleryCard
| PlatformBigFishGalleryCard
| PlatformMatch3DGalleryCard
| PlatformSquareHoleGalleryCard
| PlatformPuzzleGalleryCard;
export function isLibraryWorldEntry(
@@ -127,6 +153,12 @@ export function isMatch3DGalleryEntry(
return 'sourceType' in entry && entry.sourceType === 'match3d';
}
export function isSquareHoleGalleryEntry(
entry: PlatformWorldCardLike,
): entry is PlatformSquareHoleGalleryCard {
return 'sourceType' in entry && entry.sourceType === 'square-hole';
}
export function mapPuzzleWorkToPlatformGalleryCard(
work: PuzzleWorkSummary,
): PlatformPuzzleGalleryCard {
@@ -180,6 +212,33 @@ export function mapMatch3DWorkToPlatformGalleryCard(
};
}
export function mapSquareHoleWorkToPlatformGalleryCard(
work: SquareHoleWorkSummary,
): PlatformSquareHoleGalleryCard {
return {
sourceType: 'square-hole',
workId: work.workId,
profileId: work.profileId,
sourceSessionId: work.sourceSessionId ?? null,
publicWorkCode: buildSquareHolePublicWorkCode(work.profileId),
ownerUserId: work.ownerUserId,
authorDisplayName: '玩家',
worldName: work.gameName,
subtitle: '反直觉形状分拣',
summaryText: work.summary,
coverImageSrc: work.coverImageSrc ?? null,
themeTags:
work.tags.length > 0 ? work.tags : [work.themeText, '方洞挑战'],
playCount: work.playCount ?? 0,
remixCount: 0,
likeCount: 0,
recentPlayCount7d: 0,
visibility: 'published',
publishedAt: work.publishedAt ?? null,
updatedAt: work.updatedAt,
};
}
export function mapBigFishWorkToPlatformGalleryCard(
work: BigFishWorkSummary,
): PlatformBigFishGalleryCard {
@@ -371,6 +430,12 @@ export function buildPlatformWorldTags(entry: PlatformWorldCardLike) {
return entry.themeTags.length > 0 ? entry.themeTags.slice(0, 3) : ['抓大鹅'];
}
if (isSquareHoleGalleryEntry(entry)) {
return entry.themeTags.length > 0
? entry.themeTags.slice(0, 3)
: ['方洞'];
}
if (!isLibraryWorldEntry(entry)) {
return [
describePlatformThemeLabel(entry.themeMode),
@@ -449,6 +514,10 @@ export function resolvePlatformPublicWorkCode(
return entry.publicWorkCode;
}
if (isSquareHoleGalleryEntry(entry)) {
return entry.publicWorkCode;
}
return entry.publicWorkCode;
}
@@ -0,0 +1,149 @@
import type {
ExecuteSquareHoleActionRequest,
SendSquareHoleMessageRequest,
SquareHoleAnchorItemResponse,
SquareHoleSessionSnapshot,
} from '../../../packages/shared/src/contracts/squareHoleAgent';
import {
buildCreationAgentChatMessage,
createCreationAgentChatQuickActions,
createCreationAgentClientMessageId,
resolveCreationAgentQuickActionMessage,
} from '../../services/creation-agent';
import {
type CreationAgentAnchorView,
type CreationAgentSessionView,
type CreationAgentTheme,
CreationAgentWorkspace,
} from '../creation-agent';
type SquareHoleAgentWorkspaceProps = {
session: SquareHoleSessionSnapshot | null;
streamingReplyText?: string;
isStreamingReply?: boolean;
isBusy?: boolean;
error?: string | null;
onBack: () => void;
onSubmitMessage: (payload: SendSquareHoleMessageRequest) => void;
onExecuteAction: (payload: ExecuteSquareHoleActionRequest) => void;
};
const SQUARE_HOLE_AGENT_THEME: CreationAgentTheme = {
accentTextClass: 'text-sky-100/86',
accentBgClass: 'bg-cyan-200',
accentButtonClass: 'bg-cyan-200 shadow-slate-950/20',
userBubbleClass: 'bg-slate-950 text-white',
heroClass:
'border border-cyan-100/18 bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.28),transparent_34%),radial-gradient(circle_at_bottom_right,rgba(248,113,113,0.2),transparent_32%),linear-gradient(135deg,rgba(15,23,42,0.96),rgba(20,83,45,0.92))]',
anchorGridClass: 'grid gap-2 sm:grid-cols-4',
};
const SQUARE_HOLE_QUICK_ACTIONS = [
...createCreationAgentChatQuickActions(),
{
key: 'square-hole-auto-config',
label: '自动配置',
},
];
function mapSquareHoleAnchor(
anchor: SquareHoleAnchorItemResponse,
): CreationAgentAnchorView {
return {
key: anchor.key,
label: anchor.label,
value: anchor.value,
status: anchor.status,
};
}
function mapSquareHoleSession(
session: SquareHoleSessionSnapshot,
): CreationAgentSessionView {
// 中文注释:方洞工作台只展示共创对话和四个创作锚点,正式运行规则由后端运行态快照裁决。
const chatMessages = session.messages.filter(
(message) =>
message.kind === 'chat' ||
message.kind === 'summary' ||
message.kind === 'warning',
);
return {
sessionId: session.sessionId,
title: null,
assistantSummary: null,
currentTurn: session.currentTurn,
progressPercent: session.progressPercent,
anchors: [
session.anchorPack.theme,
session.anchorPack.twistRule,
session.anchorPack.shapeCount,
session.anchorPack.difficulty,
].map(mapSquareHoleAnchor),
messages: chatMessages,
recommendedReplies: [],
};
}
function buildSquareHoleChatPayload({
text,
quickFillRequested = false,
}: {
text: string;
quickFillRequested?: boolean;
}) {
return buildCreationAgentChatMessage({
clientMessageId: createCreationAgentClientMessageId('square-hole'),
text,
quickFillRequested,
});
}
export function SquareHoleAgentWorkspace({
session,
streamingReplyText = '',
isStreamingReply = false,
isBusy = false,
error = null,
onBack,
onSubmitMessage,
onExecuteAction,
}: SquareHoleAgentWorkspaceProps) {
return (
<CreationAgentWorkspace
session={session ? mapSquareHoleSession(session) : null}
theme={SQUARE_HOLE_AGENT_THEME}
loadingText="正在准备方洞挑战共创工作区..."
composerPlaceholder="题材、反差规则、形状数量、难度..."
primaryActionLabel="生成结果页"
streamingReplyText={streamingReplyText}
isStreamingReply={isStreamingReply}
isBusy={isBusy}
error={error}
quickActions={SQUARE_HOLE_QUICK_ACTIONS}
onBack={onBack}
onSubmitText={(text) => {
onSubmitMessage(buildSquareHoleChatPayload({ text }));
}}
onPrimaryAction={() => {
onExecuteAction({ action: 'square_hole_compile_draft' });
}}
onQuickAction={(action) => {
const quickActionMessage =
action.key === 'square-hole-auto-config'
? {
text: '自动配置',
quickFillRequested: true,
}
: resolveCreationAgentQuickActionMessage(
action.key,
'请总结一下当前方洞挑战设定。',
);
onSubmitMessage(buildSquareHoleChatPayload(quickActionMessage));
}}
/>
);
}
export default SquareHoleAgentWorkspace;
@@ -0,0 +1 @@
export { SquareHoleAgentWorkspace } from './SquareHoleAgentWorkspace';
File diff suppressed because it is too large Load Diff
@@ -0,0 +1 @@
export { SquareHoleResultView } from './SquareHoleResultView';
@@ -0,0 +1,380 @@
import {
ArrowLeft,
CheckCircle2,
Clock3,
RotateCcw,
Shapes,
Sparkles,
XCircle,
} from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import type {
DropSquareHoleShapeRequest,
SquareHoleDropResponse,
SquareHoleHoleSnapshot,
SquareHoleRunSnapshot,
} from '../../../packages/shared/src/contracts/squareHoleRuntime';
type SquareHoleRuntimeShellProps = {
run: SquareHoleRunSnapshot | null;
isBusy?: boolean;
error?: string | null;
onBack: () => void;
onRestart: () => void;
onDropShape: (
payload: DropSquareHoleShapeRequest,
) => Promise<SquareHoleDropResponse>;
onOptimisticRunChange?: (run: SquareHoleRunSnapshot) => void;
onTimeExpired?: () => void;
};
type PendingDrop = {
clientEventId: string;
holeId: string;
};
function isRunning(run: SquareHoleRunSnapshot) {
return run.status.toLowerCase() === 'running';
}
function formatTimer(value: number) {
const totalSeconds = Math.max(0, Math.ceil(value / 1000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
function buildClientEventId(runId: string, holeId: string) {
return `square-hole-drop-${runId}-${holeId}-${Date.now()}-${Math.round(
Math.random() * 1_000_000,
)}`;
}
function getHoleShapeClass(hole: SquareHoleHoleSnapshot) {
const kind = hole.holeKind.toLowerCase();
if (kind.includes('circle')) {
return 'rounded-full';
}
if (kind.includes('triangle')) {
return 'square-hole-runtime__hole-cut--triangle';
}
if (kind.includes('diamond')) {
return 'rotate-45 rounded-[0.75rem]';
}
if (kind.includes('star')) {
return 'square-hole-runtime__hole-cut--star';
}
if (kind.includes('arch')) {
return 'rounded-t-full rounded-b-[0.85rem]';
}
return 'rounded-[0.85rem]';
}
function getShapePreviewClass(shapeKind: string) {
const kind = shapeKind.toLowerCase();
if (kind.includes('circle')) {
return 'rounded-full';
}
if (kind.includes('triangle')) {
return 'square-hole-runtime__shape--triangle';
}
if (kind.includes('diamond')) {
return 'rotate-45 rounded-[0.8rem]';
}
if (kind.includes('star')) {
return 'square-hole-runtime__shape--star';
}
if (kind.includes('arch')) {
return 'rounded-t-full rounded-b-[0.9rem]';
}
return 'rounded-[0.9rem]';
}
function SquareHoleSettlement({
run,
onBack,
onRestart,
}: {
run: SquareHoleRunSnapshot;
onBack: () => void;
onRestart: () => void;
}) {
if (isRunning(run)) {
return null;
}
const won = run.status.toLowerCase() === 'won';
const stopped = run.status.toLowerCase() === 'stopped';
const title = won ? '挑战完成' : stopped ? '已停止' : '本轮失败';
return (
<div className="absolute inset-0 z-[80] flex items-center justify-center bg-slate-950/64 px-5 backdrop-blur-sm">
<section
className="w-full max-w-sm rounded-[1.5rem] border border-white/18 bg-white/94 p-5 text-slate-950 shadow-[0_26px_70px_rgba(15,23,42,0.34)]"
role="dialog"
aria-label={title}
>
<div className="mb-4 flex items-center gap-3">
<span
className={`flex h-11 w-11 items-center justify-center rounded-full ${
won
? 'bg-emerald-100 text-emerald-700'
: 'bg-rose-100 text-rose-700'
}`}
>
{won ? <CheckCircle2 size={24} /> : <XCircle size={24} />}
</span>
<div>
<h2 className="text-xl font-black">{title}</h2>
<p className="text-sm font-semibold text-slate-500">
{run.completedShapeCount}/{run.totalShapeCount} · {run.score}
</p>
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<button
type="button"
className="rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-black text-slate-700"
onClick={onBack}
>
</button>
<button
type="button"
className="rounded-xl bg-slate-950 px-4 py-3 text-sm font-black text-white"
onClick={onRestart}
>
</button>
</div>
</section>
</div>
);
}
export function SquareHoleRuntimeShell({
run,
isBusy = false,
error = null,
onBack,
onRestart,
onDropShape,
onOptimisticRunChange,
onTimeExpired,
}: SquareHoleRuntimeShellProps) {
const [pendingDrop, setPendingDrop] = useState<PendingDrop | null>(null);
const [timeLeftMs, setTimeLeftMs] = useState(run?.remainingMs ?? 0);
const [feedbackPulseId, setFeedbackPulseId] = useState<string | null>(null);
useEffect(() => {
setTimeLeftMs(run?.remainingMs ?? 0);
}, [run?.remainingMs, run?.snapshotVersion]);
useEffect(() => {
if (!run || !isRunning(run)) {
return undefined;
}
const timer = window.setInterval(() => {
setTimeLeftMs((current) => {
const next = Math.max(0, current - 1000);
if (next <= 0) {
onTimeExpired?.();
}
return next;
});
}, 1000);
return () => window.clearInterval(timer);
}, [onTimeExpired, run]);
useEffect(() => {
if (!feedbackPulseId) {
return undefined;
}
const timer = window.setTimeout(() => setFeedbackPulseId(null), 620);
return () => window.clearTimeout(timer);
}, [feedbackPulseId]);
const progressText = useMemo(() => {
if (!run) {
return '0/0';
}
return `${run.completedShapeCount}/${run.totalShapeCount}`;
}, [run]);
const dropToHole = async (holeId: string) => {
if (!run || !isRunning(run) || pendingDrop || isBusy) {
return;
}
const clientEventId = buildClientEventId(run.runId, holeId);
setPendingDrop({ clientEventId, holeId });
setFeedbackPulseId(null);
try {
const response = await onDropShape({
runId: run.runId,
holeId,
clientSnapshotVersion: run.snapshotVersion,
clientEventId,
droppedAtMs: Date.now(),
});
setFeedbackPulseId(clientEventId);
onOptimisticRunChange?.(response.run);
} finally {
setPendingDrop(null);
}
};
if (!run) {
return (
<div className="flex min-h-dvh items-center justify-center bg-slate-950 text-white">
{isBusy ? '载入中' : (error ?? '暂无运行态')}
</div>
);
}
const currentShape = run.currentShape;
const feedback = run.lastFeedback;
return (
<main className="relative flex min-h-dvh w-full justify-center overflow-hidden bg-[#101827] text-white">
<div className="absolute inset-0 bg-[radial-gradient(circle_at_50%_10%,rgba(125,211,252,0.32),transparent_27%),radial-gradient(circle_at_80%_80%,rgba(248,113,113,0.24),transparent_34%),linear-gradient(180deg,#1f3a5f_0%,#152238_48%,#111827_100%)]" />
<div
className="relative flex min-h-dvh min-w-0 flex-col overflow-hidden px-3 pb-[calc(env(safe-area-inset-bottom,0px)+0.8rem)] pt-[calc(env(safe-area-inset-top,0px)+0.65rem)]"
style={{
boxSizing: 'border-box',
maxWidth: '100vw',
width: 'min(100vw, 24rem)',
}}
>
<header className="flex items-center justify-between gap-2">
<button
type="button"
className="flex h-10 w-10 items-center justify-center rounded-full border border-white/16 bg-black/24 text-white backdrop-blur"
onClick={onBack}
aria-label="返回"
>
<ArrowLeft size={20} />
</button>
<div className="flex items-center gap-2 rounded-full border border-white/16 bg-black/26 px-3 py-2 text-sm font-black backdrop-blur">
<Clock3 size={16} />
<span>{formatTimer(timeLeftMs)}</span>
</div>
<button
type="button"
className="flex h-10 w-10 items-center justify-center rounded-full border border-white/16 bg-black/24 text-white backdrop-blur"
onClick={onRestart}
aria-label="重新开始"
>
<RotateCcw size={18} />
</button>
</header>
<section className="mt-3 grid w-full min-w-0 grid-cols-3 gap-2 overflow-hidden text-center text-[0.72rem] font-black">
<div className="rounded-2xl border border-white/14 bg-black/20 px-2 py-2 backdrop-blur">
{progressText}
</div>
<div className="rounded-2xl border border-white/14 bg-black/20 px-2 py-2 backdrop-blur">
{run.score}
</div>
<div className="rounded-2xl border border-white/14 bg-black/20 px-2 py-2 backdrop-blur">
{run.combo}
</div>
</section>
<section className="mt-3 rounded-[1.5rem] border border-white/14 bg-black/18 p-3 shadow-[0_18px_42px_rgba(15,23,42,0.28)] backdrop-blur">
<div className="flex items-center justify-between gap-2 text-xs font-bold text-white/68">
<span>{run.ruleLabel}</span>
<span>v{run.snapshotVersion}</span>
</div>
<div className="mt-3 flex min-h-[12rem] items-center justify-center rounded-[1.35rem] border border-white/10 bg-white/10">
{currentShape ? (
<div className="flex flex-col items-center gap-3">
<div
className={`h-24 w-24 shadow-[0_18px_38px_rgba(15,23,42,0.34)] ${getShapePreviewClass(
currentShape.shapeKind,
)}`}
style={{
background:
currentShape.color ||
'linear-gradient(135deg,#f8fafc,#38bdf8)',
}}
/>
<div className="flex items-center gap-2 text-base font-black">
<Shapes size={18} />
<span>{currentShape.label}</span>
</div>
</div>
) : (
<div className="text-sm font-bold text-white/70"></div>
)}
</div>
</section>
<section className="mt-3 grid grid-cols-2 gap-2">
{run.holes.map((hole) => {
const isPending = pendingDrop?.holeId === hole.holeId;
return (
<button
key={hole.holeId}
type="button"
disabled={!isRunning(run) || Boolean(pendingDrop) || isBusy}
className={`min-h-[6.25rem] rounded-[1.35rem] border border-white/14 bg-black/22 p-2 text-white shadow-[0_12px_28px_rgba(15,23,42,0.24)] backdrop-blur transition active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-58 ${
isPending ? 'ring-2 ring-cyan-200/70' : ''
}`}
onClick={() => {
void dropToHole(hole.holeId);
}}
aria-label={`投入 ${hole.label}`}
>
<span className="mx-auto grid h-12 w-12 place-items-center rounded-2xl bg-white/88 p-2">
<span
className={`block h-full w-full bg-slate-950 ${getHoleShapeClass(
hole,
)}`}
/>
</span>
<span className="mt-2 block truncate text-sm font-black">
{hole.label}
</span>
</button>
);
})}
</section>
<section className="mt-auto min-h-[3.5rem] pt-3">
{feedback ? (
<div
className={`rounded-[1.2rem] border px-3 py-2 text-center text-sm font-black ${
feedback.accepted
? 'border-emerald-200/35 bg-emerald-400/18 text-emerald-50'
: 'border-rose-200/35 bg-rose-400/18 text-rose-50'
}`}
>
{feedback.message}
</div>
) : error ? (
<div className="rounded-[1.2rem] border border-rose-200/35 bg-rose-400/18 px-3 py-2 text-center text-sm font-black text-rose-50">
{error}
</div>
) : null}
</section>
</div>
{feedbackPulseId && feedback?.accepted ? (
<div className="pointer-events-none absolute inset-0 z-[70] flex items-center justify-center">
<div className="flex h-24 w-24 items-center justify-center rounded-full bg-white/24 text-cyan-100 shadow-[0_0_42px_rgba(255,255,255,0.72)] backdrop-blur-sm">
<Sparkles size={42} />
</div>
</div>
) : null}
<SquareHoleSettlement run={run} onBack={onBack} onRestart={onRestart} />
</main>
);
}
export default SquareHoleRuntimeShell;
@@ -0,0 +1 @@
export { SquareHoleRuntimeShell } from './SquareHoleRuntimeShell';
+8
View File
@@ -46,6 +46,14 @@ export const NEW_WORK_ENTRY_CONFIG = {
visible: true,
open: true,
},
{
id: 'square-hole',
title: '方洞挑战',
subtitle: '反直觉形状分拣',
badge: '可创建',
visible: true,
open: true,
},
{
id: 'airp',
title: 'AIRP',
+21
View File
@@ -1528,6 +1528,27 @@ body {
opacity: 0.52;
}
.square-hole-runtime__shape--triangle,
.square-hole-runtime__hole-cut--triangle {
clip-path: polygon(50% 5%, 94% 92%, 6% 92%);
}
.square-hole-runtime__shape--star,
.square-hole-runtime__hole-cut--star {
clip-path: polygon(
50% 4%,
61% 36%,
95% 36%,
67% 55%,
79% 88%,
50% 68%,
21% 88%,
33% 55%,
5% 36%,
39% 36%
);
}
.platform-tab {
border: 1px solid var(--platform-subpanel-border);
border-radius: 9999px;
+3
View File
@@ -17,6 +17,9 @@ const STAGE_ROUTE_ENTRIES = [
['match3d-agent-workspace', '/creation/match3d/agent'],
['match3d-result', '/creation/match3d/result'],
['match3d-runtime', '/runtime/match3d'],
['square-hole-agent-workspace', '/creation/square-hole/agent'],
['square-hole-result', '/creation/square-hole/result'],
['square-hole-runtime', '/runtime/square-hole'],
['puzzle-agent-workspace', '/creation/puzzle/agent'],
['puzzle-result', '/creation/puzzle/result'],
['puzzle-gallery-detail', '/gallery/puzzle/detail'],
@@ -51,3 +51,28 @@ test('readCreationAgentSessionFromSse flushes decoder tail and handles CRLF boun
title: '世界共创',
});
});
test('readCreationAgentSessionFromSse keeps streamed updates before error event', async () => {
const encoder = new TextEncoder();
const response = createChunkedStreamResponse([
encoder.encode(
'event: reply_delta\ndata: {"text":"先把方洞万能的反差定住。"}\n\n',
),
encoder.encode(
'event: error\ndata: {"message":"方洞挑战聊天生成失败:LLM 请求超时"}\n\n',
),
]);
const updates: string[] = [];
await expect(
readCreationAgentSessionFromSse(response, {
fallbackMessage: '发送失败',
incompleteMessage: '结果不完整',
onUpdate: (text) => {
updates.push(text);
},
}),
).rejects.toThrow('方洞挑战聊天生成失败:LLM 请求超时');
expect(updates).toEqual(['先把方洞万能的反差定住。']);
});
+21
View File
@@ -29,6 +29,14 @@ export function buildMatch3DPublicWorkCode(profileId: string) {
return `M3-${suffix}`;
}
export function buildSquareHolePublicWorkCode(profileId: string) {
const normalized = normalizePublicCodeText(profileId);
const fallback = normalized || '00000000';
const suffix = fallback.slice(-8).padStart(8, '0');
return `SH-${suffix}`;
}
export function isSamePuzzlePublicWorkCode(keyword: string, profileId: string) {
const normalizedKeyword = normalizePublicCodeText(keyword);
@@ -61,3 +69,16 @@ export function isSameMatch3DPublicWorkCode(keyword: string, profileId: string)
normalizedKeyword === normalizePublicCodeText(profileId)
);
}
export function isSameSquareHolePublicWorkCode(
keyword: string,
profileId: string,
) {
const normalizedKeyword = normalizePublicCodeText(keyword);
return (
normalizedKeyword ===
normalizePublicCodeText(buildSquareHolePublicWorkCode(profileId)) ||
normalizedKeyword === normalizePublicCodeText(profileId)
);
}
@@ -0,0 +1,8 @@
export {
createSquareHoleCreationSession,
executeSquareHoleCreationAction,
getSquareHoleCreationSession,
sendSquareHoleCreationMessage,
squareHoleCreationClient,
streamSquareHoleCreationMessage,
} from './squareHoleCreationClient';

Some files were not shown because too many files have changed in this diff Show More