fix: restore puzzle runtime url state

This commit is contained in:
2026-05-25 22:52:38 +08:00
parent 30cf8abbf7
commit eb6ab404e2
12 changed files with 1917 additions and 177 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -300,6 +300,161 @@ function ActionCompleteHarness({
);
}
function SessionChangeHarness({
onSessionChanged,
}: {
onSessionChanged: (session: TestSession | null) => void;
}) {
const flow = usePlatformCreationAgentFlowController<
TestSession,
Record<string, never>,
{ session: TestSession },
TestMessagePayload,
{ action: string },
{ session: TestSession }
>({
client: {
createSession: async () => ({
session: {
sessionId: 'session-open',
messages: [],
},
}),
getSession: async () => ({
session: {
sessionId: 'session-restore',
messages: [],
},
}),
streamMessage: async () => ({
sessionId: 'session-open',
messages: [],
}),
executeAction: async () => ({
session: {
sessionId: 'session-compile',
messages: [],
},
}),
selectSession: (response) => response.session,
},
createPayload: {},
workspaceStage: 'match3d-agent-workspace',
resultStage: 'match3d-result',
platformStage: 'platform',
isCompileAction: (payload) => payload.action === 'match3d_compile_draft',
resolveErrorMessage: (error, fallback) =>
error instanceof Error ? error.message : fallback,
errorMessages: {
open: '打开失败',
restoreMissingSession: '缺少会话',
restore: '恢复失败',
submit: '发送失败',
execute: '执行失败',
},
enterCreateTab: () => {},
setSelectionStage: () => {},
onSessionChanged,
onActionComplete: ({ response, setSession }) => {
setSession(response.session);
},
});
return (
<div>
<button type="button" onClick={() => void flow.openWorkspace({})}>
</button>
<button
type="button"
onClick={() => void flow.restoreDraft('session-restore')}
>
</button>
<button
type="button"
onClick={() =>
void flow.executeAction({ action: 'match3d_compile_draft' })
}
>
</button>
</div>
);
}
function SessionSetterIdentityHarness({
onSetterIdentity,
}: {
onSetterIdentity: (setter: unknown) => void;
}) {
const [renderCount, setRenderCount] = useState(0);
const flow = usePlatformCreationAgentFlowController<
TestSession,
Record<string, never>,
{ session: TestSession },
TestMessagePayload,
{ action: string },
{ session: TestSession }
>({
client: {
createSession: async () => ({
session: {
sessionId: 'session-open',
messages: [],
},
}),
getSession: async () => ({
session: {
sessionId: 'session-restore',
messages: [],
},
}),
streamMessage: async () => ({
sessionId: 'session-open',
messages: [],
}),
executeAction: async () => ({
session: {
sessionId: 'session-compile',
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: () => {},
onSessionChanged: () => {},
});
useEffect(() => {
onSetterIdentity(flow.setSession);
});
return (
<button
type="button"
onClick={() => setRenderCount((current) => current + 1)}
>
{renderCount}
</button>
);
}
test('creation agent flow preserves streamed assistant text when stream fails', async () => {
const streamMessage = vi.fn(async (_sessionId, _payload, options) => {
options?.onUpdate?.('先把方洞万能的反差定住。');
@@ -391,3 +546,48 @@ test('creation agent flow suppresses compile result stage for background complet
'match3d-agent-workspace',
);
});
test('creation agent flow notifies session changes after open restore and compile', async () => {
const onSessionChanged = vi.fn();
render(<SessionChangeHarness onSessionChanged={onSessionChanged} />);
await act(async () => {
screen.getByRole('button', { name: '打开' }).click();
});
await act(async () => {
screen.getByRole('button', { name: '恢复' }).click();
});
await act(async () => {
screen.getByRole('button', { name: '编译' }).click();
});
await waitFor(() => {
expect(onSessionChanged).toHaveBeenCalledTimes(3);
});
expect(
onSessionChanged.mock.calls.map(([session]) => session?.sessionId),
).toEqual(['session-open', 'session-restore', 'session-compile']);
});
test('creation agent flow keeps session setter stable across parent rerenders', async () => {
const onSetterIdentity = vi.fn();
render(<SessionSetterIdentityHarness onSetterIdentity={onSetterIdentity} />);
await waitFor(() => {
expect(onSetterIdentity).toHaveBeenCalledTimes(1);
});
const initialSetter = onSetterIdentity.mock.calls[0]?.[0];
await act(async () => {
screen.getByRole('button', { name: //u }).click();
});
await waitFor(() => {
expect(onSetterIdentity).toHaveBeenCalledTimes(2);
});
expect(onSetterIdentity.mock.calls[1]?.[0]).toBe(initialSetter);
});

View File

@@ -1,4 +1,5 @@
import { useCallback, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import type { Dispatch, SetStateAction } from 'react';
import type { TextStreamOptions } from '../../services/aiTypes';
import type { SelectionStage } from './platformEntryTypes';
@@ -75,12 +76,13 @@ type PlatformCreationAgentFlowControllerOptions<
enterCreateTab: () => void;
setSelectionStage: (stage: SelectionStage) => void;
onSessionOpened?: () => void;
onSessionChanged?: (session: TSession | null) => void;
onOpenError?: (params: { error: unknown; errorMessage: string }) => void;
onActionComplete?: (params: {
payload: TActionPayload;
response: TActionResponse;
session: TSession;
setSession: (session: TSession) => void;
setSession: Dispatch<SetStateAction<TSession | null>>;
}) =>
| Promise<{ openResult?: boolean } | void>
| { openResult?: boolean }
@@ -94,7 +96,7 @@ type PlatformCreationAgentFlowControllerOptions<
error: unknown;
errorMessage: string;
session: TSession;
setSession: (session: TSession) => void;
setSession: Dispatch<SetStateAction<TSession | null>>;
}) => void | Promise<void>;
};
@@ -141,12 +143,27 @@ export function usePlatformCreationAgentFlowController<
TActionResponse
>,
) {
const [session, setSession] = useState<TSession | null>(null);
const [session, rawSetSession] = useState<TSession | null>(null);
const [error, setError] = useState<string | null>(null);
const [isBusy, setIsBusy] = useState(false);
const [streamingReplyText, setStreamingReplyText] = useState('');
const [isStreamingReply, setIsStreamingReply] = useState(false);
const latestStreamingReplyTextRef = useRef('');
const onSessionChangedRef = useRef(options.onSessionChanged);
useEffect(() => {
onSessionChangedRef.current = options.onSessionChanged;
}, [options.onSessionChanged]);
const setSession = useCallback(
(nextSessionOrUpdater: SetStateAction<TSession | null>) => {
rawSetSession(nextSessionOrUpdater);
if (typeof nextSessionOrUpdater !== 'function') {
onSessionChangedRef.current?.(nextSessionOrUpdater);
}
},
[],
);
const updateStreamingReplyText = useCallback((text: string) => {
latestStreamingReplyTextRef.current = text;
@@ -174,10 +191,10 @@ export function usePlatformCreationAgentFlowController<
createPayload ?? options.createPayload,
);
const nextSession = options.client.selectSession(response);
setSession(nextSession);
options.enterCreateTab();
options.onSessionOpened?.();
options.setSelectionStage(options.workspaceStage);
setSession(nextSession);
return nextSession;
} catch (caughtError) {
const errorMessage = options.resolveErrorMessage(
@@ -212,11 +229,11 @@ export function usePlatformCreationAgentFlowController<
try {
const response = await options.client.getSession(normalizedSessionId);
const nextSession = options.client.selectSession(response);
setSession(nextSession);
options.enterCreateTab();
options.setSelectionStage(
nextSession.draft ? options.resultStage : options.workspaceStage,
);
setSession(nextSession);
return nextSession;
} catch (caughtError) {
setError(