feat(learning): replace courses with project catalog

This commit is contained in:
2026-08-20 00:08:04 +08:00
parent 2cb8a7aef4
commit 38db1589e2
56 changed files with 1741 additions and 8725 deletions

View File

@@ -1,15 +1,14 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
downloadLearningCourse,
listInstalledLearningCourses,
saveLearningProgress,
streamLearningRuntime,
downloadLearningProject,
fetchLearningProject,
fetchLearningProjectMedia,
fetchLearningProjects,
openLearningExternalLink,
} from '@/lib/learning';
import type { LearningProgressWrite, LearningRuntimeBridgeRequest } from '../../shared/learning';
const hostApiFetchMock = vi.hoisted(() => vi.fn());
const invokeIpcMock = vi.hoisted(() => vi.fn());
const subscribeIpcEventMock = vi.hoisted(() => vi.fn());
vi.mock('@/lib/host-api', () => ({
hostApiFetch: (...args: unknown[]) => hostApiFetchMock(...args),
@@ -17,138 +16,74 @@ vi.mock('@/lib/host-api', () => ({
vi.mock('@/lib/api-client', () => ({
invokeIpc: (...args: unknown[]) => invokeIpcMock(...args),
subscribeIpcEvent: (...args: unknown[]) => subscribeIpcEventMock(...args),
}));
describe('Learning renderer client', () => {
describe('Learning project renderer client', () => {
beforeEach(() => {
hostApiFetchMock.mockReset();
invokeIpcMock.mockReset();
subscribeIpcEventMock.mockReset();
hostApiFetchMock.mockResolvedValue({
success: true,
data: {
courseId: 'course-1',
contentHash: 'a'.repeat(64),
moduleId: 'module-1',
sceneOrder: 2,
actionIndex: 1,
positionMs: 300,
completed: false,
updatedAt: '2026-08-16T00:00:00.000Z',
},
});
});
it('projects installed course IPC results without exposing Main archive paths', async () => {
const course = {
id: 'course-1',
origin: 'ops_large',
status: 'published',
title: 'Python 入门',
};
const mainRecord = {
schemaVersion: 1,
course,
installedAt: '2026-08-16T00:00:00.000Z',
archivePath: 'C:\\Users\\private\\course.zip',
};
invokeIpcMock
.mockResolvedValueOnce(mainRecord)
.mockResolvedValueOnce([mainRecord]);
it('reads paged projects and project detail through the Host API', async () => {
const page = { items: [], nextCursor: 'next' };
const detail = { id: 'project-1', name: '机械臂' };
hostApiFetchMock
.mockResolvedValueOnce({ success: true, data: page })
.mockResolvedValueOnce({ success: true, data: detail });
await expect(downloadLearningCourse('course-1')).resolves.toEqual({
schemaVersion: 1,
course,
installedAt: '2026-08-16T00:00:00.000Z',
});
await expect(listInstalledLearningCourses()).resolves.toEqual([{
schemaVersion: 1,
course,
installedAt: '2026-08-16T00:00:00.000Z',
}]);
await expect(fetchLearningProjects({ cursor: 'cursor one', limit: 24 })).resolves.toBe(page);
await expect(fetchLearningProject('project/one')).resolves.toBe(detail);
expect(hostApiFetchMock).toHaveBeenNthCalledWith(
1,
'/api/works/learning/projects?cursor=cursor+one&limit=24',
undefined,
);
expect(hostApiFetchMock).toHaveBeenNthCalledWith(
2,
'/api/works/learning/projects/project%2Fone',
undefined,
);
});
it('writes only the strict cloud progress contract and keeps module hashes local', async () => {
const progress: LearningProgressWrite & { moduleContentHash: string } = {
contentHash: 'a'.repeat(64),
moduleId: 'module-1',
moduleContentHash: 'b'.repeat(64),
sceneOrder: 2,
actionIndex: 1,
positionMs: 300,
completed: false,
};
it('starts the native Main-owned download through a fixed Host route', async () => {
hostApiFetchMock.mockResolvedValue({ success: true, data: { status: 'saved' } });
await saveLearningProgress('course-1', progress);
await expect(downloadLearningProject('project-1')).resolves.toEqual({ status: 'saved' });
expect(hostApiFetchMock).toHaveBeenCalledWith(
'/api/works/learning/courses/course-1/progress',
expect.objectContaining({ method: 'PUT' }),
'/api/works/learning/projects/project-1/download',
{ method: 'POST' },
);
const init = hostApiFetchMock.mock.calls[0][1] as RequestInit;
expect(JSON.parse(String(init.body))).toEqual({
contentHash: 'a'.repeat(64),
moduleId: 'module-1',
sceneOrder: 2,
actionIndex: 1,
positionMs: 300,
completed: false,
});
expect(invokeIpcMock).not.toHaveBeenCalled();
});
it('subscribes through the allowlisted API seam, rejects malformed runtime events, and cleans up', async () => {
const request: LearningRuntimeBridgeRequest = {
requestId: 'request-1',
courseId: 'course-1',
contentHash: 'a'.repeat(64),
capability: 'quiz/v1/submit',
method: 'POST',
context: {},
body: { answer: 'A' },
};
const cleanup = vi.fn();
let listener: ((payload: unknown) => void) | undefined;
subscribeIpcEventMock.mockImplementation((channel: string, callback: (payload: unknown) => void) => {
expect(channel).toBe('learning:runtime-event');
listener = callback;
return cleanup;
});
invokeIpcMock.mockImplementation(async () => {
listener?.({ requestId: 'request-1', type: 'chunk', chunk: 'not-bytes' });
listener?.({ requestId: 'other-request', type: 'end' });
listener?.({ requestId: 'request-1', type: 'start', status: 200, contentType: 'application/json' });
listener?.({ requestId: 'request-1', type: 'chunk', chunk: new Uint8Array([1, 2]) });
listener?.({ requestId: 'request-1', type: 'end' });
});
const events: unknown[] = [];
it('accepts only fixed project media paths and validated raster data', async () => {
hostApiFetchMock.mockResolvedValue({ mimeType: 'image/png', dataBase64: 'AQID' });
await streamLearningRuntime(request, (event) => events.push(event));
await expect(fetchLearningProjectMedia(
'/api/learning/projects/project-1/media/readme-1',
)).resolves.toBe('data:image/png;base64,AQID');
expect(hostApiFetchMock).toHaveBeenCalledWith(
'/api/works/learning/projects/project-1/media/readme-1',
);
expect(invokeIpcMock).toHaveBeenCalledWith('learning:runtimeRequest', request);
expect(events).toEqual([
{ requestId: 'request-1', type: 'start', status: 200, contentType: 'application/json' },
{ requestId: 'request-1', type: 'chunk', chunk: new Uint8Array([1, 2]) },
{ requestId: 'request-1', type: 'end' },
]);
expect(cleanup).toHaveBeenCalledTimes(1);
await expect(fetchLearningProjectMedia('https://tracker.example/image.png')).rejects.toMatchObject({
code: 'LEARNING_INVALID_MEDIA_URL',
});
hostApiFetchMock.mockResolvedValueOnce({ mimeType: 'image/svg+xml', dataBase64: 'AQID' });
await expect(fetchLearningProjectMedia(
'/api/learning/projects/project-1/media/readme-2',
)).rejects.toMatchObject({ code: 'LEARNING_INVALID_MEDIA_RESPONSE' });
});
it('cleans up the runtime subscription when the IPC request fails', async () => {
const cleanup = vi.fn();
subscribeIpcEventMock.mockReturnValue(cleanup);
invokeIpcMock.mockRejectedValue(new Error('request failed'));
it('opens only credential-free HTTPS README links through the IPC facade', async () => {
invokeIpcMock.mockResolvedValue(undefined);
await expect(streamLearningRuntime({
requestId: 'request-2',
courseId: 'course-1',
contentHash: 'a'.repeat(64),
capability: 'quiz/v1/submit',
method: 'POST',
context: {},
body: {},
}, vi.fn())).rejects.toThrow('request failed');
expect(cleanup).toHaveBeenCalledTimes(1);
await openLearningExternalLink('https://example.com/guide');
expect(invokeIpcMock).toHaveBeenCalledWith('shell:openExternal', 'https://example.com/guide');
await expect(openLearningExternalLink('http://example.com')).rejects.toMatchObject({
code: 'LEARNING_INVALID_LINK',
});
});
});