From c4521bb4df021fcde521a75d50d86575353da1b8 Mon Sep 17 00:00:00 2001 From: lynnlink <> Date: Sun, 20 Sep 2026 17:10:18 +0800 Subject: [PATCH 01/11] refactor(presentation): adopt project store architecture --- .../embedded-powerpoint-manager.test.ts | 43 +- .../main/__tests__/excel-host-handler.test.ts | 16 + .../src/main/__tests__/excel-host.test.ts | 36 +- .../main/__tests__/word-host-handler.test.ts | 26 + .../main/__tests__/word-host-preload.test.ts | 4 +- .../src/main/embedded-powerpoint-manager.ts | 48 +- desktop/apps/electron/src/main/excel-host.ts | 20 +- .../electron/src/main/handlers/excel-host.ts | 4 +- .../electron/src/main/handlers/powerpoint.ts | 4 + .../electron/src/main/handlers/word-host.ts | 15 + .../apps/electron/src/preload/bootstrap.ts | 1 + .../apps/electron/src/preload/excel-host.ts | 2 +- .../apps/electron/src/preload/word-host.ts | 1 + .../renderer/atoms/__tests__/agent.test.ts | 18 +- .../renderer/atoms/__tests__/office.test.ts | 3 +- .../atoms/__tests__/presentation.test.ts | 61 +- .../apps/electron/src/renderer/atoms/agent.ts | 14 +- .../src/renderer/atoms/presentation.ts | 106 +- .../amphi/__tests__/MessageBubble.test.tsx | 4 +- .../components/app/ExcelWorkbenchPanel.tsx | 45 +- .../components/app/OfficeLaunchEmptyState.tsx | 90 +- .../components/app/PresentationRibbon.tsx | 2 +- .../app/PresentationSlidePreview.tsx | 1 + .../app/PresentationWorkbenchPanel.tsx | 322 ++-- .../EmbeddedPowerPointPanel.test.tsx | 2 + .../__tests__/OfficeLaunchEmptyState.test.tsx | 63 + .../PresentationChartDisplay.test.tsx | 23 +- .../PresentationInsertIntegration.test.tsx | 52 +- .../PresentationInsertRuntime.test.tsx | 82 +- .../PresentationSlideshowPlayback.test.tsx | 34 +- .../PresentationStoreWorkbench.test.tsx | 67 + .../PresentationWorkbenchPanel.test.tsx | 141 +- .../__tests__/SessionResourcePanel.test.tsx | 87 +- .../components/word/SessionWordEditor.tsx | 12 +- .../components/word/WordLaunchEmptyState.tsx | 37 - .../word/__tests__/SessionWordEditor.test.tsx | 9 +- .../src/renderer/excel/ExcelHostApp.tsx | 29 +- .../__tests__/UniverSheetEditor.test.tsx | 19 +- .../apps/electron/src/renderer/excel/main.tsx | 2 +- .../useEmbeddedPowerPointBridge.test.tsx | 1 + desktop/apps/electron/src/renderer/index.css | 1 + .../lib/__tests__/officeSurfaceStatus.test.ts | 29 +- .../lib/__tests__/powerPointProtocol.test.ts | 621 +++----- .../lib/__tests__/presentationDesign.test.ts | 4 +- .../presentationEditorDriver.test.ts | 6 +- .../presentationFileController.test.ts | 343 +++-- .../__tests__/presentationMarkdown.test.ts | 507 +------ .../__tests__/presentationPersistence.test.ts | 234 --- .../lib/__tests__/presentationPptx.test.ts | 26 +- .../presentationPptxDisplay.test.tsx | 42 +- .../__tests__/presentationPptxImages.test.ts | 10 +- .../__tests__/presentationPptxImport.test.ts | 50 +- .../presentationWorkspaceRuntime.test.ts | 277 ---- .../lib/__tests__/rendererRoots.test.ts | 10 + .../lib/__tests__/tool-display.test.ts | 23 +- .../apps/electron/src/renderer/lib/apiStub.ts | 3 + .../lib/office/officeSurfaceStatus.ts | 12 +- .../src/renderer/lib/powerPointProtocol.ts | 693 +++------ .../src/renderer/lib/presentationDesign.ts | 12 +- .../renderer/lib/presentationEditorDriver.ts | 10 +- .../lib/presentationFileController.ts | 137 +- .../src/renderer/lib/presentationImport.ts | 6 +- .../renderer/lib/presentationImport.worker.ts | 4 +- .../src/renderer/lib/presentationMarkdown.ts | 1333 +---------------- .../renderer/lib/presentationPersistence.ts | 123 -- .../src/renderer/lib/presentationPptx.ts | 6 +- .../renderer/lib/presentationPptxImport.ts | 18 +- .../lib/presentationWorkspaceRuntime.ts | 191 --- .../electron/src/renderer/lib/toolDisplay.ts | 27 +- .../apps/electron/src/renderer/powerpoint.tsx | 190 +-- .../presentation/__tests__/checkpoint.test.ts | 56 + .../presentation/__tests__/project.test.ts | 82 +- .../presentation/__tests__/store.test.ts | 213 +++ .../renderer/presentation/agentCommands.ts | 417 ++++++ .../src/renderer/presentation/checkpoint.ts | 93 ++ .../src/renderer/presentation/history.ts | 88 ++ .../renderer/presentation/model/reducer.ts | 16 +- .../src/renderer/presentation/project.ts | 64 +- .../src/renderer/presentation/store.ts | 562 +++++++ .../test-fixtures/presentation-store.ts | 40 + .../renderer/test-fixtures/presentation.ts | 8 +- .../src/renderer/word/WordHostApp.tsx | 1 + .../word/__tests__/WordHostApp.test.tsx | 3 + .../apps/electron/src/shared/ipc-channels.ts | 4 +- desktop/apps/electron/src/shared/types.ts | 36 +- desktop/office-architecture.md | 129 +- .../packages/shared/src/i18n/locales/en.json | 29 +- .../packages/shared/src/i18n/locales/zh.json | 29 +- src/amphi_agent/_tools.py | 2 + src/amphi_agent/cognitive/normal/main.py | 7 + .../cognitive/presentation/base.py | 4 +- .../cognitive/presentation/compose.py | 15 + .../cognitive/presentation/review.py | 15 + src/amphi_agent/powerpoint.py | 1019 ++++++------- .../prompts/presentation/shared.py | 5 +- src/amphi_agent/security/_registry.py | 8 +- src/amphi_agent/tools/powerpoint.py | 557 ++++--- tests/agent/powerpoint/test_host.py | 596 +++----- .../agent/prompt/fixtures/persona_hashes.json | 24 +- tests/agent/prompt/test_prompt_rules.py | 1 + tests/agent/prompt/test_tool_surface.py | 37 +- .../agent/security/test_permission_engine.py | 19 +- .../agent/tools/fixtures/tool_contracts.json | 125 +- tests/agent/tools/test_powerpoint_tools.py | 247 ++- tests/agent/tools/test_tool_modules.py | 21 +- 105 files changed, 4854 insertions(+), 6212 deletions(-) create mode 100644 desktop/apps/electron/src/renderer/components/app/__tests__/OfficeLaunchEmptyState.test.tsx create mode 100644 desktop/apps/electron/src/renderer/components/app/__tests__/PresentationStoreWorkbench.test.tsx delete mode 100644 desktop/apps/electron/src/renderer/components/word/WordLaunchEmptyState.tsx delete mode 100644 desktop/apps/electron/src/renderer/lib/__tests__/presentationPersistence.test.ts delete mode 100644 desktop/apps/electron/src/renderer/lib/__tests__/presentationWorkspaceRuntime.test.ts create mode 100644 desktop/apps/electron/src/renderer/lib/__tests__/rendererRoots.test.ts delete mode 100644 desktop/apps/electron/src/renderer/lib/presentationPersistence.ts delete mode 100644 desktop/apps/electron/src/renderer/lib/presentationWorkspaceRuntime.ts create mode 100644 desktop/apps/electron/src/renderer/presentation/__tests__/checkpoint.test.ts create mode 100644 desktop/apps/electron/src/renderer/presentation/__tests__/store.test.ts create mode 100644 desktop/apps/electron/src/renderer/presentation/agentCommands.ts create mode 100644 desktop/apps/electron/src/renderer/presentation/checkpoint.ts create mode 100644 desktop/apps/electron/src/renderer/presentation/history.ts create mode 100644 desktop/apps/electron/src/renderer/presentation/store.ts create mode 100644 desktop/apps/electron/src/renderer/test-fixtures/presentation-store.ts diff --git a/desktop/apps/electron/src/main/__tests__/embedded-powerpoint-manager.test.ts b/desktop/apps/electron/src/main/__tests__/embedded-powerpoint-manager.test.ts index 6ec843a3..12553a22 100644 --- a/desktop/apps/electron/src/main/__tests__/embedded-powerpoint-manager.test.ts +++ b/desktop/apps/electron/src/main/__tests__/embedded-powerpoint-manager.test.ts @@ -39,8 +39,8 @@ class FakeContents { return { ok: true, value: { - identity: { document_id: 'opened-document', name: 'Opened deck' }, - meta: { total_pages: 3 }, + document_id: 'opened-document', + deck: { id: 'opened-document', title: 'Opened deck', total_pages: 3 }, reused: false, }, } @@ -93,6 +93,8 @@ it('owns exactly one CDP target per Session and presents only the active one', a const second = await manager.ensureSession('session-b') expect(first.targetId).toBe('ppt-target-1') expect(second.targetId).toBe('ppt-target-2') + expect(first.documentCount).toBeNull() + expect(second.documentCount).toBeNull() expect(views).toHaveLength(2) manager.setBounds({ x: 12, y: 24, width: 900, height: 600 }) @@ -117,7 +119,7 @@ it('owns exactly one CDP target per Session and presents only the active one', a slideCount: 3, title: 'Opened deck', }) - expect(views[0]!.webContents.executedScripts.at(-1)).toContain('"method":"view_ppt"') + expect(views[0]!.webContents.executedScripts.at(-1)).toContain('"method":"open"') expect(views[0]!.webContents.executedScripts.at(-1)).toContain('"content_base64":"BAUG"') await expect(manager.openFile('session-a', path.join(presentationDirectory, 'deck.txt'))) .rejects.toThrow('must end with .pptx') @@ -130,6 +132,41 @@ it('owns exactly one CDP target per Session and presents only the active one', a expect(manager.snapshot().sessions.map((item) => item.sessionId)).toEqual(['session-a']) }) +it('publishes authoritative project counts without treating the native target as a document', async () => { + const views: FakeView[] = [] + const snapshots: Array> = [] + const manager = new EmbeddedPowerPointManager( + () => { + const view = new FakeView(views.length + 1) + views.push(view) + return view as unknown as WebContentsView + }, + async () => {}, + (snapshot) => snapshots.push(snapshot), + ) + manager.attachHost({ + isDestroyed: () => false, + contentView: { addChildView: () => {}, removeChildView: () => {} }, + } as unknown as BrowserWindow) + + const session = await manager.ensureSession('session-a') + expect(session.documentCount).toBeNull() + manager.reportState(session.webContentsId, { documentCount: 0 }) + expect(manager.sessionInfo('session-a')?.documentCount).toBe(0) + manager.reportState(session.webContentsId, { documentCount: 2 }) + expect(manager.snapshot().sessions[0]?.documentCount).toBe(2) + const publishCount = snapshots.length + manager.reportState(session.webContentsId, { documentCount: 2 }) + expect(snapshots).toHaveLength(publishCount) + + views[0]!.webContents.emit('did-start-loading') + expect(manager.sessionInfo('session-a')?.documentCount).toBeNull() + expect(() => manager.reportState(session.webContentsId, { documentCount: -1 })) + .toThrow('Invalid PowerPoint runtime document count') + expect(() => manager.reportState(999, { documentCount: 1 })).toThrow('does not own') + manager.closeAll() +}) + it('rejects unknown close senders and preserves a replacement target during deferred close', async () => { const views: FakeView[] = [] const manager = new EmbeddedPowerPointManager( diff --git a/desktop/apps/electron/src/main/__tests__/excel-host-handler.test.ts b/desktop/apps/electron/src/main/__tests__/excel-host-handler.test.ts index 1945319a..d133997e 100644 --- a/desktop/apps/electron/src/main/__tests__/excel-host-handler.test.ts +++ b/desktop/apps/electron/src/main/__tests__/excel-host-handler.test.ts @@ -11,6 +11,22 @@ const { IPC } = await import('../../shared/ipc-channels') const { registerExcelHostHandlers } = await import('../handlers/excel-host') describe('Excel host close requests', () => { + it('binds renderer state reports to the sending Excel target', async () => { + const calls: unknown[][] = [] + const excel = { + reportState: (sender: number, state: unknown) => { calls.push([sender, state]) }, + } as unknown as ExcelHost + testIpcHandlers.clear() + registerExcelHostHandlers(excel, {} as EmbeddedBrowserManager, () => undefined) + + await testIpcHandlers.get(IPC.excelHost.reportState)?.( + { sender: { id: 17 } } as IpcMainInvokeEvent, + { documentCount: 0, dirty: false }, + ) + + expect(calls).toEqual([[17, { documentCount: 0, dirty: false }]]) + }) + it('resolves the owning Session from the sender and retracts its panel before deferred destruction', async () => { const events: unknown[][] = [] const closed: number[] = [] diff --git a/desktop/apps/electron/src/main/__tests__/excel-host.test.ts b/desktop/apps/electron/src/main/__tests__/excel-host.test.ts index a6f15a5d..846f279a 100644 --- a/desktop/apps/electron/src/main/__tests__/excel-host.test.ts +++ b/desktop/apps/electron/src/main/__tests__/excel-host.test.ts @@ -131,6 +131,36 @@ function setup(openExternal?: (url: string) => void) { } describe('ExcelHost Session target ownership', () => { + it('publishes the renderer-owned workbook inventory only for its Session target', async () => { + const snapshots: Array> = [] + const views: FakeView[] = [] + const host = fakeHost() + const manager = new ExcelHost( + () => { + const view = new FakeView(new FakeWebContents(views.length + 1, `excel-target-${views.length + 1}`)) + views.push(view) + return view as unknown as WebContentsView + }, + '/dist/excel-host-preload.cjs', + 'http://localhost:5173', + '/dist/renderer/excel.html', + (snapshot) => snapshots.push(snapshot), + ) + manager.attachHost(host.window) + const session = await manager.ensureSession('session-a', { + sessionId: 'session-a', locale: 'en-US', theme: 'light', + }, false) + + expect(session.documentCount).toBeNull() + manager.reportState(session.webContentsId, { documentCount: 0, dirty: false }) + expect(manager.snapshot().sessions[0]?.documentCount).toBe(0) + manager.reportState(session.webContentsId, { documentCount: 2, dirty: true }) + expect(manager.snapshot().sessions[0]).toMatchObject({ documentCount: 2, dirty: true }) + expect(snapshots.at(-1)?.sessions[0]).toMatchObject({ documentCount: 2, dirty: true }) + expect(() => manager.reportState(session.webContentsId, { documentCount: -1, dirty: false })).toThrow('Invalid Excel runtime') + expect(() => manager.reportState(-1, { documentCount: 0, dirty: false })).toThrow('does not own') + }) + it('keeps serialized recovery scoped to the owning Session renderer', async () => { const { manager } = setup() const first = await manager.ensureSession('session-a', { sessionId: 'session-a', locale: 'en-US', theme: 'light' }) @@ -227,7 +257,7 @@ describe('ExcelHost Session target ownership', () => { const config = { sessionId: 'session-a', locale: 'en-US' as const, theme: 'light' as const } const first = await manager.ensureSession('session-a', config) await manager.ensureSession('session-b', { ...config, sessionId: 'session-b' }) - manager.setDirty(first.webContentsId, true) + manager.reportState(first.webContentsId, { documentCount: 1, dirty: true }) manager.setRecoveryState(first.webContentsId, '{"version":1}') manager.activateSession('session-b') manager.setVisible(true) @@ -251,7 +281,7 @@ describe('ExcelHost Session target ownership', () => { }) const checkpoint = JSON.stringify({ version: 1, tabs: [{ tabId: 'tab-a' }] }) manager.setRecoveryState(first.webContentsId, checkpoint) - manager.setDirty(first.webContentsId, true) + manager.reportState(first.webContentsId, { documentCount: 1, dirty: true }) views[0]?.webContents.emit('render-process-gone', {}, { reason: 'crashed' }) const recovered = await manager.ensureSession('session-a', { @@ -270,7 +300,7 @@ describe('ExcelHost Session target ownership', () => { const { manager, views, host } = setup() for (const sessionId of ['session-a', 'session-b']) { const session = await manager.ensureSession(sessionId, { sessionId, locale: 'en-US', theme: 'light' }) - manager.setDirty(session.webContentsId, true) + manager.reportState(session.webContentsId, { documentCount: 1, dirty: true }) } manager.shutdown() expect(manager.snapshot().sessions).toEqual([]) diff --git a/desktop/apps/electron/src/main/__tests__/word-host-handler.test.ts b/desktop/apps/electron/src/main/__tests__/word-host-handler.test.ts index fb0c65d4..39c274aa 100644 --- a/desktop/apps/electron/src/main/__tests__/word-host-handler.test.ts +++ b/desktop/apps/electron/src/main/__tests__/word-host-handler.test.ts @@ -10,6 +10,32 @@ const { IPC } = await import('../../shared/ipc-channels') const { registerWordHostHandlers } = await import('../handlers/word-host') describe('Word host IPC boundary', () => { + it('opens a picked DOCX only in the sending child renderer Session', async () => { + const originalShowOpenDialog = electronModuleMock.dialog.showOpenDialog + const opened: unknown[][] = [] + electronModuleMock.dialog.showOpenDialog = async () => ({ canceled: false, filePaths: ['/tmp/Agent Report.docx'] }) + const word = { + sessionForContents: (sender: number) => { + expect(sender).toBe(17) + return 'session-a' + }, + openFile: async (...args: unknown[]) => { opened.push(args) }, + } as unknown as WordHost + testIpcHandlers.clear() + registerWordHostHandlers(word, () => undefined) + try { + await testIpcHandlers.get(IPC.wordHost.openDocument)?.({ sender: { id: 17 } } as IpcMainInvokeEvent) + expect(opened).toEqual([['session-a', { + id: 'renderer-open', + name: 'Agent Report.docx', + path: '/tmp/Agent Report.docx', + sessionId: 'session-a', + }]]) + } finally { + electronModuleMock.dialog.showOpenDialog = originalShowOpenDialog + } + }) + it('uses the sending child identity for runtime reports, completion and close requests', async () => { const calls: unknown[][] = [] const events: unknown[][] = [] diff --git a/desktop/apps/electron/src/main/__tests__/word-host-preload.test.ts b/desktop/apps/electron/src/main/__tests__/word-host-preload.test.ts index efcaf4ca..e983e7c6 100644 --- a/desktop/apps/electron/src/main/__tests__/word-host-preload.test.ts +++ b/desktop/apps/electron/src/main/__tests__/word-host-preload.test.ts @@ -32,6 +32,7 @@ it('buffers early Word runtime events and exposes only its narrow Session API', emit(IPC.events.wordHostOpenFileRequested, { ...request, id: 'second-ticket' }); exposed.api.onOpenFileRequested((value) => received.push(['replayed', value])); await exposed.api.readDocument('/tmp/a.docx'); + await exposed.api.openDocument(); await exposed.api.completeOpenFile('opaque-ticket'); await exposed.api.completeFlush('flush-ticket', true); await exposed.api.reportState({ documentCount: 1, persistenceStatus: 'saved' }); @@ -46,13 +47,14 @@ it('buffers early Word runtime events and exposes only its narrow Session API', const result = JSON.parse(stdout) as { name: string; keys: string[]; received: unknown[][]; invocations: unknown[][] } expect(result.name).toBe('wordHostApi') expect(result.keys.sort()).toEqual([ - 'completeFlush', 'completeOpenFile', 'getConfig', 'onConfigChanged', 'onExpandedChanged', + 'completeFlush', 'completeOpenFile', 'getConfig', 'onConfigChanged', 'onExpandedChanged', 'openDocument', 'onFlushRequested', 'onOpenFileRequested', 'readDocument', 'reportState', 'requestClose', 'setExpanded', ].sort()) expect(result.received.map(([kind]) => kind)).toEqual(['open', 'flush', 'config', 'expanded', 'replayed']) expect(result.received[2]).toEqual(['config', { locale: 'zh' }]) expect(result.invocations).toEqual([ ['word:read-document', '/tmp/a.docx'], + ['word-host:openDocument'], ['word-host:completeOpenFile', 'opaque-ticket', null], ['word-host:completeFlush', 'flush-ticket', true], ['word-host:reportState', { documentCount: 1, persistenceStatus: 'saved' }], diff --git a/desktop/apps/electron/src/main/embedded-powerpoint-manager.ts b/desktop/apps/electron/src/main/embedded-powerpoint-manager.ts index 3a01bc08..80920138 100644 --- a/desktop/apps/electron/src/main/embedded-powerpoint-manager.ts +++ b/desktop/apps/electron/src/main/embedded-powerpoint-manager.ts @@ -9,6 +9,7 @@ import path from 'node:path' import type { EmbeddedPowerPointBounds, EmbeddedPowerPointOpenFileResult, + EmbeddedPowerPointRendererState, EmbeddedPowerPointSessionInfo, EmbeddedPowerPointSnapshot, } from '../shared/types' @@ -20,6 +21,7 @@ import { OfficeSessionContainer, type OfficeSessionRecord } from './office-sessi const MAX_OPEN_PRESENTATION_BYTES = 250 * 1024 * 1024 interface EmbeddedPowerPointSurface extends OfficeSessionRecord { + documentCount: number | null loading: boolean openingFilesByPath: Map> } @@ -130,6 +132,22 @@ export class EmbeddedPowerPointManager { return surface.sessionId } + /** Accept authoritative project inventory only from the Session-owned renderer. */ + reportState(webContentsId: number, value: unknown): void { + const surface = this.container.forWebContents(webContentsId) + if (!surface) throw new Error('PowerPoint Session does not own this renderer') + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new TypeError('Invalid PowerPoint runtime state') + } + const state = value as Partial + if (!Number.isSafeInteger(state.documentCount) || state.documentCount! < 0) { + throw new TypeError('Invalid PowerPoint runtime document count') + } + if (surface.documentCount === state.documentCount) return + surface.documentCount = state.documentCount! + this.publishState() + } + /** A delayed close belongs to its sender, even if this Session has since reopened. */ closeCurrentSession(webContentsId: number): void { const surface = this.container.forWebContents(webContentsId) @@ -178,6 +196,7 @@ export class EmbeddedPowerPointManager { sessionId, view, targetId: null, + documentCount: null, loading: true, crashed: false, ready: Promise.resolve(), @@ -186,6 +205,7 @@ export class EmbeddedPowerPointManager { view.webContents.setBackgroundThrottling(false) view.webContents.on('did-start-loading', () => { if (!this.container.owns(surface)) return + surface.documentCount = null surface.loading = true this.publishState() }) @@ -206,7 +226,7 @@ export class EmbeddedPowerPointManager { ): Promise { const content = await readFile(canonicalPath) const value = await this.dispatchToSurface(surface, { - method: 'view_ppt', + method: 'open', params: { target: canonicalPath, file_name: path.basename(canonicalPath), @@ -217,26 +237,25 @@ export class EmbeddedPowerPointManager { throw new Error('PowerPoint renderer returned an invalid file-open result') } const result = value as Record - const identity = result.identity - const meta = result.meta - if (!identity || typeof identity !== 'object' || Array.isArray(identity)) { - throw new Error('PowerPoint renderer returned an invalid file identity') - } - if (!meta || typeof meta !== 'object' || Array.isArray(meta)) { + const deck = result.deck + if (!deck || typeof deck !== 'object' || Array.isArray(deck)) { throw new Error('PowerPoint renderer returned invalid file metadata') } - const identityValue = identity as Record - const metaValue = meta as Record - if (typeof identityValue.document_id !== 'string' || typeof metaValue.total_pages !== 'number') { + const deckValue = deck as Record + if ( + typeof result.document_id !== 'string' + || deckValue.id !== result.document_id + || typeof deckValue.total_pages !== 'number' + ) { throw new Error('PowerPoint renderer returned an incomplete file-open result') } return { - documentId: identityValue.document_id, + documentId: result.document_id, fileName: path.basename(canonicalPath), reused: result.reused === true, - slideCount: metaValue.total_pages, - title: typeof identityValue.name === 'string' - ? identityValue.name + slideCount: deckValue.total_pages, + title: typeof deckValue.title === 'string' && deckValue.title.trim() + ? deckValue.title : path.basename(canonicalPath, '.pptx'), } } @@ -265,6 +284,7 @@ export class EmbeddedPowerPointManager { webContentsId: surface.view.webContents.id, loading: surface.loading, crashed: surface.crashed, + documentCount: surface.documentCount, } } diff --git a/desktop/apps/electron/src/main/excel-host.ts b/desktop/apps/electron/src/main/excel-host.ts index 80e2a6c4..5547fbac 100644 --- a/desktop/apps/electron/src/main/excel-host.ts +++ b/desktop/apps/electron/src/main/excel-host.ts @@ -9,6 +9,7 @@ import { pathToFileURL } from 'node:url' import type { EmbeddedBrowserBounds, ExcelHostConfig, + ExcelHostRendererState, ExcelHostSessionInfo, ExcelHostSnapshot, ExcelWorkbookOpenRequest, @@ -37,6 +38,7 @@ const WEB_PREFERENCES: NonNullable createInitialWorkbook: boolean @@ -160,12 +162,19 @@ export class ExcelHost { return results.every((result) => result.status === 'fulfilled') } - setDirty(webContentsId: number, dirty: boolean): void { - if (typeof dirty !== 'boolean') throw new TypeError('Excel dirty state must be a boolean') + reportState(webContentsId: number, value: unknown): void { const record = this.recordForWebContents(webContentsId) if (!record) throw new Error('Excel Session does not own this renderer') - if (record.dirty === dirty) return - record.dirty = dirty + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new TypeError('Invalid Excel runtime state') + } + const state = value as Partial + if (!Number.isSafeInteger(state.documentCount) || state.documentCount! < 0 || typeof state.dirty !== 'boolean') { + throw new TypeError('Invalid Excel runtime document count or dirty state') + } + if (record.documentCount === state.documentCount && record.dirty === state.dirty) return + record.documentCount = state.documentCount! + record.dirty = state.dirty this.publishState() } @@ -218,6 +227,7 @@ export class ExcelHost { targetId: null, crashed: false, dirty: false, + documentCount: null, recoveryState: null, workbookOpenRequests: new Map(), createInitialWorkbook, @@ -247,6 +257,7 @@ export class ExcelHost { }) contents.on('render-process-gone', () => { if (!this.container.owns(record) || contents.isDestroyed()) return + record.documentCount = null this.container.invalidate(record) void this.container.reload(record, (current) => ( current.view.webContents.loadURL(this.rendererUrl(current)) @@ -296,6 +307,7 @@ export class ExcelHost { ready: record.targetId !== null && !record.crashed, crashed: record.crashed, dirty: record.dirty, + documentCount: record.documentCount, } } diff --git a/desktop/apps/electron/src/main/handlers/excel-host.ts b/desktop/apps/electron/src/main/handlers/excel-host.ts index 8a81676f..3e953acb 100644 --- a/desktop/apps/electron/src/main/handlers/excel-host.ts +++ b/desktop/apps/electron/src/main/handlers/excel-host.ts @@ -39,8 +39,8 @@ export function registerExcelHostHandlers(excelHost: ExcelHost, browser: Embedde emitToHost, }) - loggedHandle(IPC.excelHost.setDirty, (event, dirty: boolean) => { - excelHost.setDirty(event.sender.id, dirty) + loggedHandle(IPC.excelHost.reportState, (event, state: unknown) => { + excelHost.reportState(event.sender.id, state) }) loggedHandle(IPC.excelHost.getRecoveryState, (event) => { diff --git a/desktop/apps/electron/src/main/handlers/powerpoint.ts b/desktop/apps/electron/src/main/handlers/powerpoint.ts index 9336227d..ce49b2a9 100644 --- a/desktop/apps/electron/src/main/handlers/powerpoint.ts +++ b/desktop/apps/electron/src/main/handlers/powerpoint.ts @@ -51,6 +51,10 @@ export function registerPowerPointHandlers( emitToHost(IPC.events.powerPointExpandedChanged, expanded) }) + loggedHandle(IPC.powerpoint.reportState, (event, state: unknown) => { + powerpoint.reportState(event.sender.id, state) + }) + loggedHandle( IPC.powerpoint.openFile, (_event, sessionId: string, absPath: string) => powerpoint.openFile(sessionId, absPath), diff --git a/desktop/apps/electron/src/main/handlers/word-host.ts b/desktop/apps/electron/src/main/handlers/word-host.ts index 5c062d8e..e8feda4a 100644 --- a/desktop/apps/electron/src/main/handlers/word-host.ts +++ b/desktop/apps/electron/src/main/handlers/word-host.ts @@ -1,3 +1,5 @@ +import { basename } from 'node:path' +import { BrowserWindow, dialog, type OpenDialogOptions } from 'electron' import { IPC } from '../../shared/ipc-channels' import type { EmbeddedBrowserBounds, WordHostOpenRequest } from '../../shared/types' import type { WordHost } from '../word-host' @@ -23,6 +25,19 @@ export function registerWordHostHandlers(word: WordHost, emitToHost: (channel: s loggedHandle(IPC.wordHost.openFile, (_event, sessionId: string, request: WordHostOpenRequest) => word.openFile(sessionId, request), { transformLogArgs: redactLocalPathLogArgs, }) + loggedHandle(IPC.wordHost.openDocument, async (event) => { + const sessionId = word.sessionForContents(event.sender.id) + const options: OpenDialogOptions = { + title: 'Open Word Document', + properties: ['openFile'], + filters: [{ name: 'Word documents', extensions: ['docx'] }], + } + const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0] + const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options) + const path = result.filePaths[0] + if (result.canceled || !path) return + await word.openFile(sessionId, { id: 'renderer-open', name: basename(path), path, sessionId }) + }, { transformLogArgs: redactLocalPathLogArgs }) loggedHandle(IPC.wordHost.getConfig, (event) => { word.sessionForContents(event.sender.id) return word.getConfig() diff --git a/desktop/apps/electron/src/preload/bootstrap.ts b/desktop/apps/electron/src/preload/bootstrap.ts index 24499be5..5a09ef29 100644 --- a/desktop/apps/electron/src/preload/bootstrap.ts +++ b/desktop/apps/electron/src/preload/bootstrap.ts @@ -113,6 +113,7 @@ const api: ElectronAPI = { ipcRenderer.invoke(IPC.powerpoint.setVisible, visible, focusHost), requestClose: (sessionId) => ipcRenderer.invoke(IPC.powerpoint.requestClose, sessionId), setExpanded: (expanded) => ipcRenderer.invoke(IPC.powerpoint.setExpanded, expanded), + reportState: (state) => ipcRenderer.invoke(IPC.powerpoint.reportState, state), openFile: (sessionId, absPath) => ipcRenderer.invoke(IPC.powerpoint.openFile, sessionId, absPath), }, word: { diff --git a/desktop/apps/electron/src/preload/excel-host.ts b/desktop/apps/electron/src/preload/excel-host.ts index 590e6d43..c80b8d85 100644 --- a/desktop/apps/electron/src/preload/excel-host.ts +++ b/desktop/apps/electron/src/preload/excel-host.ts @@ -29,7 +29,7 @@ const api: ExcelHostPreloadAPI = { save: (request) => ipcRenderer.invoke(IPC.excel.save, request), saveAs: (request) => ipcRenderer.invoke(IPC.excel.saveAs, request), requestClose: () => ipcRenderer.invoke(IPC.excelHost.requestClose), - setDirty: (dirty) => ipcRenderer.invoke(IPC.excelHost.setDirty, dirty), + reportState: (state) => ipcRenderer.invoke(IPC.excelHost.reportState, state), getRecoveryState: () => ipcRenderer.invoke(IPC.excelHost.getRecoveryState), setRecoveryState: (state) => ipcRenderer.invoke(IPC.excelHost.setRecoveryState, state), onConfigChanged: (callback) => { diff --git a/desktop/apps/electron/src/preload/word-host.ts b/desktop/apps/electron/src/preload/word-host.ts index 5d868b5b..0072bb86 100644 --- a/desktop/apps/electron/src/preload/word-host.ts +++ b/desktop/apps/electron/src/preload/word-host.ts @@ -36,6 +36,7 @@ function latestEvent(channel: string) { const api: WordHostPreloadAPI = { getConfig: () => ipcRenderer.invoke(IPC.wordHost.getConfig), + openDocument: () => ipcRenderer.invoke(IPC.wordHost.openDocument), readDocument: (path) => ipcRenderer.invoke(IPC.word.readDocument, path), reportState: (state) => ipcRenderer.invoke(IPC.wordHost.reportState, state), requestClose: () => ipcRenderer.invoke(IPC.wordHost.requestClose), diff --git a/desktop/apps/electron/src/renderer/atoms/__tests__/agent.test.ts b/desktop/apps/electron/src/renderer/atoms/__tests__/agent.test.ts index 2bf0a6af..4264d4e5 100644 --- a/desktop/apps/electron/src/renderer/atoms/__tests__/agent.test.ts +++ b/desktop/apps/electron/src/renderer/atoms/__tests__/agent.test.ts @@ -948,18 +948,14 @@ describe('reducer: tool calls', () => { it('classifies visible PowerPoint actions and reveals their Session surface', () => { const visibleActions = [ - 'view_ppt', - 'update_ppt_design', - 'edit_ppt_page', - 'insert_ppt_element', - 'remove_ppt_element', - 'insert_ppt_page', - 'remove_ppt_page', - 'move_ppt_page', - 'goto_ppt_page', + 'ppt_open', + 'ppt_edit_page', + 'ppt_manage_deck', + 'ppt_inspect', + 'ppt_save', ] expect(visibleActions.every(isPowerPointAgentActionToolName)).toBe(true) - expect(isPowerPointAgentActionToolName('get_ppt_page')).toBe(false) + expect(isPowerPointAgentActionToolName('ppt_read_page')).toBe(false) const store = makeStore() const id = setupSession(store) @@ -976,7 +972,7 @@ describe('reducer: tool calls', () => { type: 'tool_call', messageId: 'powerpoint-write', toolUseId: 'view-deck', - toolName: 'view_ppt', + toolName: 'ppt_open', input: { target: 'quarterly-review' }, }, }) diff --git a/desktop/apps/electron/src/renderer/atoms/__tests__/office.test.ts b/desktop/apps/electron/src/renderer/atoms/__tests__/office.test.ts index 16526346..d4d41fd6 100644 --- a/desktop/apps/electron/src/renderer/atoms/__tests__/office.test.ts +++ b/desktop/apps/electron/src/renderer/atoms/__tests__/office.test.ts @@ -75,9 +75,10 @@ describe('Session-scoped Office status projection', () => { store.set(activeSessionIdAtom, 'session-a') store.set(embeddedPowerPointSnapshotAtom, { sessions: [{ sessionId: 'session-a', targetId: 'ppt-a', webContentsId: 1, loading: false, crashed: false, + documentCount: 0, }] }) store.set(excelHostSnapshotAtom, { sessions: [{ - sessionId: 'session-b', targetId: 'excel-b', webContentsId: 2, ready: true, crashed: false, dirty: true, + sessionId: 'session-b', targetId: 'excel-b', webContentsId: 2, ready: true, crashed: false, dirty: true, documentCount: 1, }] }) store.set(setPowerPointNeedsAttentionAtom, { sessionId: 'session-a', needsAttention: true }) let status = store.get(currentOfficeSurfaceStatusesAtom) diff --git a/desktop/apps/electron/src/renderer/atoms/__tests__/presentation.test.ts b/desktop/apps/electron/src/renderer/atoms/__tests__/presentation.test.ts index 8b89e1e6..3240a03d 100644 --- a/desktop/apps/electron/src/renderer/atoms/__tests__/presentation.test.ts +++ b/desktop/apps/electron/src/renderer/atoms/__tests__/presentation.test.ts @@ -4,10 +4,8 @@ import { activeSessionIdAtom } from '../sessions' import { PRESENTATION_PAGE_SIZES, createBlankPresentationSlide, - createBlankPresentationDocument, - createInitialPresentationDocument, - currentPresentationDocumentAtom, - currentPresentationWorkspaceAtom, + createBlankPresentationProject, + createInitialPresentationProject, presentationExpandedAtom, purgePresentationSessionAtom, formatPresentationText, @@ -20,8 +18,8 @@ import { describe('presentation atoms', () => { it('creates documents with an explicit widescreen page size', () => { - expect(createInitialPresentationDocument().pageSize).toEqual(PRESENTATION_PAGE_SIZES.wide) - expect(createBlankPresentationDocument('Blank').pageSize).toEqual(PRESENTATION_PAGE_SIZES.wide) + expect(createInitialPresentationProject().pageSize).toEqual(PRESENTATION_PAGE_SIZES.wide) + expect(createBlankPresentationProject('Blank').pageSize).toEqual(PRESENTATION_PAGE_SIZES.wide) }) it('gives every generated slide an explicit no-transition default', () => { @@ -29,7 +27,7 @@ describe('presentation atoms', () => { expect(blank.transition).toEqual({ effect: 'none', durationMs: 1_000 }) expect(blank.background).toBeUndefined() expect(blank.footer).toBeUndefined() - const initialDocument = createInitialPresentationDocument() + const initialDocument = createInitialPresentationProject() expect(initialDocument.slides.pages.every((slide) => ( slide.transition.effect === 'none' && slide.transition.durationMs === 1_000 ))).toBe(true) @@ -37,7 +35,7 @@ describe('presentation atoms', () => { }) it('starts with one unnamed slide containing ordinary editable text boxes instead of bundled sample content', () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() expect(document.title).toBe('') expect(document.slides.pages).toHaveLength(1) expect(document.slides.selectedPageId).toBe(document.slides.pages[0]!.id) @@ -55,7 +53,7 @@ describe('presentation atoms', () => { }) it('resolves global theme defaults while preserving page overrides', () => { - const document = createBlankPresentationDocument('Theme defaults') + const document = createBlankPresentationProject('Theme defaults') const slide = document.slides.pages[0]! document.theme = { ...document.theme, @@ -236,67 +234,26 @@ describe('presentation atoms', () => { expect(stripPresentationTextFormatting(formatPresentationText(element), element)).toBe(element.text) }) - it('keeps documents and expanded state independent between Sessions', () => { + it('keeps expanded state independent between Sessions', () => { const store = createStore() store.set(activeSessionIdAtom, 'session-a') - const sessionADocument = { - ...createInitialPresentationDocument(), - title: 'Session A deck', - } - store.set(currentPresentationDocumentAtom, sessionADocument) store.set(presentationExpandedAtom, true) store.set(activeSessionIdAtom, 'session-b') - expect(store.get(currentPresentationDocumentAtom).title).not.toBe('Session A deck') expect(store.get(presentationExpandedAtom)).toBe(false) store.set(activeSessionIdAtom, 'session-a') - expect(store.get(currentPresentationDocumentAtom).title).toBe('Session A deck') expect(store.get(presentationExpandedAtom)).toBe(true) }) - it('removes a deleted Session document and expansion state', () => { + it('removes a deleted Session expansion state', () => { const store = createStore() store.set(activeSessionIdAtom, 'session-delete') - store.set(currentPresentationDocumentAtom, { - ...createInitialPresentationDocument(), - title: 'Delete me', - }) store.set(presentationExpandedAtom, true) store.set(purgePresentationSessionAtom, 'session-delete') - expect(store.get(currentPresentationDocumentAtom).title).not.toBe('Delete me') expect(store.get(presentationExpandedAtom)).toBe(false) }) - it('keeps multiple open presentations independent within one Session', () => { - const store = createStore() - store.set(activeSessionIdAtom, 'session-tabs') - const firstWorkspace = store.get(currentPresentationWorkspaceAtom) - const firstDocument = firstWorkspace.documents[0]! - const secondDocument = createBlankPresentationDocument('Second deck') - - store.set(currentPresentationWorkspaceAtom, { - activeDocumentId: secondDocument.id, - documents: [...firstWorkspace.documents, secondDocument], - }) - store.set(currentPresentationDocumentAtom, { - ...store.get(currentPresentationDocumentAtom), - title: 'Edited second deck', - }) - - const withEditedSecond = store.get(currentPresentationWorkspaceAtom) - store.set(currentPresentationWorkspaceAtom, { - ...withEditedSecond, - activeDocumentId: firstDocument.id, - }) - - expect(store.get(currentPresentationDocumentAtom).id).toBe(firstDocument.id) - expect(store.get(currentPresentationDocumentAtom).title).toBe(firstDocument.title) - expect(store.get(currentPresentationWorkspaceAtom).documents.find((item) => ( - item.id === secondDocument.id - ))?.title).toBe('Edited second deck') - }) - }) diff --git a/desktop/apps/electron/src/renderer/atoms/agent.ts b/desktop/apps/electron/src/renderer/atoms/agent.ts index 358d54f9..816d812c 100644 --- a/desktop/apps/electron/src/renderer/atoms/agent.ts +++ b/desktop/apps/electron/src/renderer/atoms/agent.ts @@ -1041,15 +1041,11 @@ export const currentBrowserAgentActiveAtom = atom((get) => ( /** PowerPoint tools that visibly change the live presentation surface. */ const POWERPOINT_ACTION_TOOL_NAMES = new Set([ - 'view_ppt', - 'update_ppt_design', - 'edit_ppt_page', - 'insert_ppt_element', - 'remove_ppt_element', - 'insert_ppt_page', - 'remove_ppt_page', - 'move_ppt_page', - 'goto_ppt_page', + 'ppt_open', + 'ppt_edit_page', + 'ppt_manage_deck', + 'ppt_inspect', + 'ppt_save', ]) /** Whether a tool is an Agent-controlled PowerPoint operation visible to the user. */ diff --git a/desktop/apps/electron/src/renderer/atoms/presentation.ts b/desktop/apps/electron/src/renderer/atoms/presentation.ts index b3a4f81a..b998c5f3 100644 --- a/desktop/apps/electron/src/renderer/atoms/presentation.ts +++ b/desktop/apps/electron/src/renderer/atoms/presentation.ts @@ -573,12 +573,7 @@ export function selectPresentationPage(slides: PresentationSlides, selectedPageI return { ...slides, selectedPageId } } -/** - * The authoritative, serializable PowerPoint model. - * - * File handles and save bookkeeping deliberately live on PresentationDocument, - * while all deck content lives here. - */ +/** The authoritative, serializable PowerPoint model. */ export interface PresentationProject { schemaVersion: 1 version: 1 @@ -590,19 +585,6 @@ export interface PresentationProject { slides: PresentationSlides } -/** Renderer host metadata attached to a project without becoming deck content. */ -export interface PresentationDocument extends PresentationProject { - sourceProtected?: boolean - source?: import('../../shared/office-files').OfficeFileSource - savedRevision?: number - revision: number -} - -export interface PresentationWorkspace { - activeDocumentId: string - documents: PresentationDocument[] -} - export interface PresentationAgentChange { changeId: number elementIds: string[] @@ -610,9 +592,6 @@ export interface PresentationAgentChange { slideId: string } -/** One renderer-local visual transition requested by an Agent domain command. */ -export const presentationAgentChangeAtom = atom(null) - type SessionStateUpdate = T | ((current: T) => T) let generatedId = 0 @@ -632,9 +611,9 @@ export function createBlankPresentationSlide(name: string): PresentationSlide { } } -export function createInitialPresentationDocument(): PresentationDocument { - const document = createBlankPresentationDocument('') - const slide = document.slides.pages[0]! +export function createInitialPresentationProject(): PresentationProject { + const project = createBlankPresentationProject('') + const slide = project.slides.pages[0]! const createTextBox = ( kind: 'body' | 'subtitle' | 'title', geometry: Pick, @@ -653,7 +632,7 @@ export function createInitialPresentationDocument(): PresentationDocument { rotation: 0, text, fontSize, - fontFamily: isTitle ? document.theme.titleFontFamily : document.theme.bodyFontFamily, + fontFamily: isTitle ? project.theme.titleFontFamily : project.theme.bodyFontFamily, fontWeight: isTitle ? 700 : 400, italic: false, underline: false, @@ -669,19 +648,18 @@ export function createInitialPresentationDocument(): PresentationDocument { } slide.layout = 'title' slide.elements = [ - createTextBox('title', { x: 120, y: 105, width: document.pageSize.width - 240, height: 90 }), - createTextBox('subtitle', { x: 160, y: 220, width: document.pageSize.width - 320, height: 60 }), - createTextBox('body', { x: 120, y: 320, width: document.pageSize.width - 240, height: Math.max(180, document.pageSize.height - 425) }), + createTextBox('title', { x: 120, y: 105, width: project.pageSize.width - 240, height: 90 }), + createTextBox('subtitle', { x: 160, y: 220, width: project.pageSize.width - 320, height: 60 }), + createTextBox('body', { x: 120, y: 320, width: project.pageSize.width - 240, height: Math.max(180, project.pageSize.height - 425) }), ] - return document + return project } -export function createBlankPresentationDocument(title: string, slideName = 'Slide 1'): PresentationDocument { +export function createBlankPresentationProject(title: string, slideName = 'Slide 1'): PresentationProject { const slide = createBlankPresentationSlide(slideName) return { schemaVersion: 1, version: 1, - revision: 1, id: createPresentationId('presentation'), theme: { ...DEFAULT_PRESENTATION_MASTER, @@ -699,17 +677,6 @@ export function createBlankPresentationDocument(title: string, slideName = 'Slid } } -export function createInitialPresentationWorkspace(): PresentationWorkspace { - const document = createInitialPresentationDocument() - return { - activeDocumentId: document.id, - documents: [document], - } -} - -const fallbackPresentationWorkspace = createInitialPresentationWorkspace() -const fallbackPresentationDocument = fallbackPresentationWorkspace.documents[0]! -const presentationWorkspacesBySessionAtom = atom>(new Map()) const expandedPresentationSessionsAtom = atom>(new Set()) /** Dedicated PowerPoint renderers pin their exact Session independently of main navigation. */ export const powerPointSessionIdOverrideAtom = atom(null) @@ -717,52 +684,6 @@ export const presentationSessionIdAtom = atom((get) => ( get(powerPointSessionIdOverrideAtom) ?? get(viewedSessionIdAtom) )) -/** Explicit Session ownership for commands that can outlive a navigation change. */ -export const presentationWorkspaceFamily = atomFamily((sessionId: string) => atom( - (get) => get(presentationWorkspacesBySessionAtom).get(sessionId) ?? fallbackPresentationWorkspace, - (get, set, update: SessionStateUpdate) => { - const current = get(presentationWorkspacesBySessionAtom).get(sessionId) ?? fallbackPresentationWorkspace - const next = typeof update === 'function' ? update(current) : update - const workspaces = new Map(get(presentationWorkspacesBySessionAtom)) - workspaces.set(sessionId, next) - set(presentationWorkspacesBySessionAtom, workspaces) - }, -)) - -/** Every open presentation tab owned by the viewed Session. */ -export const currentPresentationWorkspaceAtom = atom( - (get) => { - const sessionId = get(presentationSessionIdAtom) - return sessionId ? get(presentationWorkspaceFamily(sessionId)) : fallbackPresentationWorkspace - }, - (get, set, update: SessionStateUpdate) => { - const sessionId = get(presentationSessionIdAtom) - if (sessionId) set(presentationWorkspaceFamily(sessionId), update) - }, -) - -/** The active presentation tab's editable document. */ -export const currentPresentationDocumentAtom = atom( - (get) => { - const workspace = get(currentPresentationWorkspaceAtom) - return workspace.documents.find((document) => document.id === workspace.activeDocumentId) - ?? workspace.documents[0] - ?? fallbackPresentationDocument - }, - (get, set, update: SessionStateUpdate) => { - const workspace = get(currentPresentationWorkspaceAtom) - const current = get(currentPresentationDocumentAtom) - const next = typeof update === 'function' ? update(current) : update - const hasActiveDocument = workspace.documents.some((document) => document.id === current.id) - set(currentPresentationWorkspaceAtom, { - activeDocumentId: next.id, - documents: hasActiveDocument - ? workspace.documents.map((document) => document.id === current.id ? next : document) - : [...workspace.documents, next], - }) - }, -) - /** Whether the viewed Session's presentation owns the work area. */ export const presentationExpandedAtom = atom( (get) => { @@ -784,14 +705,7 @@ export const presentationExpandedAtom = atom( /** Drop presentation state when its owning Session is deleted. */ export const purgePresentationSessionAtom = atom(null, (get, set, sessionId: string) => { - presentationWorkspaceFamily.remove(sessionId) presentationPaneViewFamily.remove(sessionId) - const workspaces = get(presentationWorkspacesBySessionAtom) - if (workspaces.has(sessionId)) { - const nextWorkspaces = new Map(workspaces) - nextWorkspaces.delete(sessionId) - set(presentationWorkspacesBySessionAtom, nextWorkspaces) - } const expandedSessions = get(expandedPresentationSessionsAtom) if (expandedSessions.has(sessionId)) { const nextExpandedSessions = new Set(expandedSessions) diff --git a/desktop/apps/electron/src/renderer/components/amphi/__tests__/MessageBubble.test.tsx b/desktop/apps/electron/src/renderer/components/amphi/__tests__/MessageBubble.test.tsx index a4f417c6..e237085d 100644 --- a/desktop/apps/electron/src/renderer/components/amphi/__tests__/MessageBubble.test.tsx +++ b/desktop/apps/electron/src/renderer/components/amphi/__tests__/MessageBubble.test.tsx @@ -505,13 +505,13 @@ describe('Pipeline', () => { content: '', toolCalls: [{ toolUseId: 'powerpoint-update', - name: 'edit_ppt_page', + name: 'ppt_edit_page', input: { page_id: 'page-1', ref: 'title', replacement: 'Updated' }, }], blocks: [{ type: 'tool', toolUseId: 'powerpoint-update', - name: 'edit_ppt_page', + name: 'ppt_edit_page', input: { page_id: 'page-1', ref: 'title', replacement: 'Updated' }, }], startedAt: Date.now(), diff --git a/desktop/apps/electron/src/renderer/components/app/ExcelWorkbenchPanel.tsx b/desktop/apps/electron/src/renderer/components/app/ExcelWorkbenchPanel.tsx index 08998b16..bbd1250a 100644 --- a/desktop/apps/electron/src/renderer/components/app/ExcelWorkbenchPanel.tsx +++ b/desktop/apps/electron/src/renderer/components/app/ExcelWorkbenchPanel.tsx @@ -29,7 +29,7 @@ const excelSurfacePolicy: NativeOfficeSurfacePolicy = { onError: (error) => rlog.warn('[excel-host] native surface sync failed', error), } -/** Renderer chrome around one Session-owned native Excel WebContentsView. */ +/** Main-window viewport for one Session-owned native Excel WebContentsView. */ export function ExcelWorkbenchPanel({ active = true }: { active?: boolean }) { const { t, i18n } = useTranslation() const sessionId = useAtomValue(viewedSessionIdAtom) @@ -122,29 +122,32 @@ export function ExcelWorkbenchPanel({ active = true }: { active?: boolean }) { if (hostSession?.crashed) status = t('excel.hostCrashed') else if (error) status = t('excel.hostFailed') else if (hostSession?.ready) status = t('excel.hostReady') + const showShellHeader = !nativeVisible || (hostSession.documentCount ?? 0) > 0 return (
- - { - void window.api.excelHost.closeSession(sessionId).catch((error) => { - rlog.warn('[excel-host] panel close failed', error) - }) - }} - onToggleExpanded={() => setExpanded((value) => !value)} - testIdPrefix="excel" - /> - + {showShellHeader ? ( + + { + void window.api.excelHost.closeSession(sessionId).catch((error) => { + rlog.warn('[excel-host] panel close failed', error) + }) + }} + onToggleExpanded={() => setExpanded((value) => !value)} + testIdPrefix="excel" + /> + + ) : null}
{!nativeVisible ? ( diff --git a/desktop/apps/electron/src/renderer/components/app/OfficeLaunchEmptyState.tsx b/desktop/apps/electron/src/renderer/components/app/OfficeLaunchEmptyState.tsx index 18e720ae..b93dfef4 100644 --- a/desktop/apps/electron/src/renderer/components/app/OfficeLaunchEmptyState.tsx +++ b/desktop/apps/electron/src/renderer/components/app/OfficeLaunchEmptyState.tsx @@ -3,31 +3,81 @@ import { useTranslation } from 'react-i18next' import { Icons } from '@/components/amphi/Icons' import { OfficeAppHeader } from './OfficeWorkbenchChrome' -export function OfficeLaunchEmptyState({ kind, onCreate, onOpen }: { kind: 'excel' | 'presentation'; onCreate: () => Promise; onOpen?: () => void }) { +type OfficeLaunchKind = 'excel' | 'presentation' | 'word' +type LaunchOperation = 'create' | 'open' + +const launchConfig = { + excel: { + title: 'Excel', + prefix: 'excel', + icon: Icons.spreadsheet, + iconClassName: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400', + titleKey: 'excel.emptyTitle', + descriptionKey: 'excel.emptyDescription', + createLabelKey: 'excel.newWorkbook', + createTestId: 'excel-create-workbook', + }, + presentation: { + title: 'PPT', + prefix: 'powerpoint', + icon: Icons.presentation, + iconClassName: 'bg-orange-500/10 text-orange-600 dark:text-orange-400', + titleKey: 'session.presentation.launchTitle', + descriptionKey: 'session.presentation.launchDetail', + createLabelKey: 'session.presentation.launchButton.create', + createTestId: 'powerpoint-create-session', + }, + word: { + title: 'Word', + prefix: 'word', + icon: Icons.wordDocument, + iconClassName: 'bg-blue-500/10 text-blue-600 dark:text-blue-400', + titleKey: 'word.emptyTitle', + descriptionKey: 'word.emptyDescription', + createLabelKey: 'word.newDocument', + createTestId: 'word-create-document', + }, +} as const + +export function OfficeLaunchEmptyState({ kind, onCreate, onOpen }: { + kind: OfficeLaunchKind + onCreate: () => unknown | Promise + onOpen: () => unknown | Promise +}) { const { t } = useTranslation() - const [creating, setCreating] = useState(false) - const [failed, setFailed] = useState(false) - const presentation = kind === 'presentation' - const title = presentation ? 'PPT' : 'Excel' - const icon = presentation ? Icons.presentation(20) : Icons.spreadsheet(20) - const prefix = presentation ? 'powerpoint' : 'excel' - const createLabel = presentation ? 'session.presentation.launchButton.create' : 'excel.newWorkbook' - return
- + const [pending, setPending] = useState(null) + const [failed, setFailed] = useState(null) + const config = launchConfig[kind] + const run = (operation: LaunchOperation, action: () => unknown | Promise) => { + if (pending) return + setPending(operation) + setFailed(null) + void Promise.resolve().then(action).catch(() => setFailed(operation)).finally(() => setPending(null)) + } + return
+
-
{icon}
-
{t(presentation ? 'session.presentation.launchTitle' : 'excel.emptyTitle')}
-
{t(presentation ? 'session.presentation.launchDetail' : 'excel.emptyDescription')}
+
{config.icon(20)}
+
{t(config.titleKey)}
+
{t(config.descriptionKey)}
- - {onOpen ? : null} + +
- {failed ?
{t('office.createFailed')}
: null} + {failed ?
{t(failed === 'create' ? 'office.createFailed' : 'office.openFailed')}
: null}
diff --git a/desktop/apps/electron/src/renderer/components/app/PresentationRibbon.tsx b/desktop/apps/electron/src/renderer/components/app/PresentationRibbon.tsx index 25001e82..203cb382 100644 --- a/desktop/apps/electron/src/renderer/components/app/PresentationRibbon.tsx +++ b/desktop/apps/electron/src/renderer/components/app/PresentationRibbon.tsx @@ -973,7 +973,7 @@ function InsertControls({ onAddShape, onAddSlide, onAddText }: { const { t } = useTranslation() return (
- + onAddText('body')} testId="presentation-add-text" />
diff --git a/desktop/apps/electron/src/renderer/components/app/PresentationSlidePreview.tsx b/desktop/apps/electron/src/renderer/components/app/PresentationSlidePreview.tsx index 27f6c54b..786e6930 100644 --- a/desktop/apps/electron/src/renderer/components/app/PresentationSlidePreview.tsx +++ b/desktop/apps/electron/src/renderer/components/app/PresentationSlidePreview.tsx @@ -233,6 +233,7 @@ export function PresentationSlidePreview({ aria-hidden={interactive ? undefined : 'true'} ref={previewRef} data-testid="presentation-slide-preview" + data-presentation-page-id={slide.id} > void onExpandedChange?: (expanded: boolean) => void - onSave?: (documentId: string, saveAs: boolean) => Promise - saveError?: string | null } interface SlideshowTransitionRun { @@ -222,73 +220,8 @@ interface SlideshowTransitionView extends SlideshowTransitionRun { transition: PresentationTransition } -export const PRESENTATION_HISTORY_MAX_ENTRIES = 50 -export const PRESENTATION_HISTORY_MAX_BYTES = 192 * 1024 * 1024 - -export interface PresentationHistoryEntry { - document: PresentationDocument - estimatedBytes: number -} - -/** Estimate retained JS heap without serializing large embedded data URLs. */ -export function estimatePresentationDocumentBytes(document: PresentationDocument): number { - const seen = new Set() - let bytes = 0 - - const visit = (value: unknown) => { - if (value === null || value === undefined) { - bytes += 4 - return - } - if (typeof value === 'string') { - // UTF-16 is deliberately conservative; data URLs are ASCII but can still be - // promoted internally, and the budget should remain safe across runtimes. - bytes += value.length * 2 - return - } - if (typeof value === 'number' || typeof value === 'boolean') { - bytes += 8 - return - } - if (typeof value !== 'object' || seen.has(value)) return - seen.add(value) - bytes += Array.isArray(value) ? 24 : 32 - if (Array.isArray(value)) { - for (const item of value) visit(item) - return - } - for (const [key, item] of Object.entries(value)) { - bytes += key.length * 2 - visit(item) - } - } - - visit(document) - return bytes -} - -function cloneDocument(document: PresentationDocument): PresentationDocument { - // structuredClone would duplicate every Base64 payload for every undo step. - // Strip the immutable payloads while cloning the mutable model, then reattach - // the original strings by index so snapshots cannot mutate one another. - const payloads = document.assets.map((asset) => asset.source.dataUrl) - const payloadFreeDocument: PresentationDocument = { - ...document, - assets: document.assets.map((asset) => ({ ...asset, source: { ...asset.source, dataUrl: '' } })), - } - const cloned = structuredClone(payloadFreeDocument) - cloned.assets.forEach((asset, index) => { asset.source.dataUrl = payloads[index] ?? '' }) - return cloned -} - -export function createPresentationHistoryEntry(document: PresentationDocument, maxBytes = PRESENTATION_HISTORY_MAX_BYTES): PresentationHistoryEntry | null { - const estimatedBytes = estimatePresentationDocumentBytes(document) - if (estimatedBytes > maxBytes) return null - return { document: cloneDocument(document), estimatedBytes } -} - export function canAppendPresentationFileElement( - document: PresentationDocument, + document: PresentationProject, element: PresentationImageElement | PresentationMediaElement, asset: PresentationAsset, maxBytes = PRESENTATION_HISTORY_MAX_BYTES, @@ -302,7 +235,7 @@ export function canAppendPresentationFileElement( ? { ...item, elements: [...item.elements, element] } : item)), } - return estimatePresentationDocumentBytes(nextDocument) <= maxBytes + return estimatePresentationProjectBytes(nextDocument) <= maxBytes } export function resolvePresentationNumberFieldValue(draft: string, min: number | undefined, fallback: number): number { @@ -311,32 +244,6 @@ export function resolvePresentationNumberFieldValue(draft: string, min: number | return Math.round(min === undefined ? parsed : Math.max(min, parsed)) } -/** Keep the newest contiguous history segment within both entry and byte limits. */ -export function trimPresentationHistoryEntries(entries: readonly PresentationHistoryEntry[], maxEntries = PRESENTATION_HISTORY_MAX_ENTRIES, maxBytes = PRESENTATION_HISTORY_MAX_BYTES): PresentationHistoryEntry[] { - const kept: PresentationHistoryEntry[] = [] - let retainedBytes = 0 - for (let index = entries.length - 1; index >= 0 && kept.length < Math.max(0, maxEntries); index -= 1) { - const entry = entries[index]! - if (entry.estimatedBytes > maxBytes - retainedBytes) break - kept.unshift(entry) - retainedBytes += entry.estimatedBytes - } - return kept -} - -function trimPresentationHistoryPair(past: PresentationHistoryEntry[], future: PresentationHistoryEntry[]): void { - let entryCount = past.length + future.length - let retainedBytes = [...past, ...future].reduce((sum, entry) => sum + entry.estimatedBytes, 0) - while (entryCount > PRESENTATION_HISTORY_MAX_ENTRIES || retainedBytes > PRESENTATION_HISTORY_MAX_BYTES) { - // Prefer discarding the oldest undo state. Once none remain, discard the - // farthest redo state (future[0]); the nearest redo lives at the end. - const removed = past.length > 0 ? past.shift() : future.shift() - if (!removed) break - entryCount -= 1 - retainedBytes -= removed.estimatedBytes - } -} - export function isPresentationRotationLocked(element: PresentationElement): boolean { return !supportsPresentationElementRotation(element) } @@ -1841,25 +1748,18 @@ function createFooterFabricObjects(fabric: FabricModule, theme: PresentationMast } /** A focused PowerPoint-style editor embedded in the Session workbench. */ -export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, workspaceRuntime, onSave, saveError }: PresentationWorkbenchPanelProps) { +export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, presentationStore }: PresentationWorkbenchPanelProps) { const { t } = useTranslation() - const sessionId = useAtomValue(presentationSessionIdAtom) - const agentChange = useAtomValue(presentationAgentChangeAtom) - const workspace = useAtomValue(currentPresentationWorkspaceAtom) - const document = useAtomValue(currentPresentationDocumentAtom) - const store = useStore() - const presentationRuntime = useMemo(() => { - if (workspaceRuntime) return workspaceRuntime - const workspaceAtom = presentationWorkspaceFamily(sessionId ?? '') - return createPresentationWorkspaceRuntime({ - sessionId: sessionId ?? '', - read: () => store.get(workspaceAtom), - write: (next) => store.set(workspaceAtom, next), - }) - }, [sessionId, store, workspaceRuntime]) - useEffect(() => store.sub(presentationWorkspaceFamily(sessionId ?? ''), () => { - presentationRuntime.runtime.publish() - }), [presentationRuntime, sessionId, store]) + const sessionId = presentationStore.sessionId + const presentationSnapshot = useSyncExternalStore( + presentationStore.subscribe, + presentationStore.getSnapshot, + presentationStore.getSnapshot, + ) + const agentChange = presentationSnapshot.agentChange + const document = presentationSnapshot.project! + const documentMetadata = presentationSnapshot.projectMetadata[document.id]! + const documentRevision = documentMetadata.revision const pageSize = getPresentationPageSize(document) const [expanded, setExpanded] = useAtom(presentationExpandedAtom) const setRightCollapsed = useSetAtom(setRightPanelCollapsedAtom) @@ -1867,6 +1767,10 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const showToast = useSetAtom(showToastAtom) const [selectedElementId, setSelectedElementId] = useState(null) const [canvasGeneration, setCanvasGeneration] = useState(0) + const [canvasRenderState, setCanvasRenderState] = useState<{ + key: string | null + status: 'error' | 'loading' | 'ready' + }>({ key: null, status: 'loading' }) const [canvasScale, setCanvasScale] = useState(0.4) const [compact, setCompact] = useState(true) const [ribbonCollapsed, setRibbonCollapsed] = useState(false) @@ -1887,7 +1791,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const [slideshowTransition, setSlideshowTransition] = useState(null) const [animationPreviewRun, setAnimationPreviewRun] = useState(null) const [transitionPreviewRun, setTransitionPreviewRun] = useState(null) - const [historyStatus, setHistoryStatus] = useState({ canUndo: false, canRedo: false }) + const historyStatus = { canUndo: presentationSnapshot.canUndo, canRedo: presentationSnapshot.canRedo } const [insertDialog, setInsertDialog] = useState(null) const [masterDialogOpen, setMasterDialogOpen] = useState(false) const rootRef = useRef(null) @@ -1901,8 +1805,8 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const mediaRuntimeRef = useRef(null) const objectIdsRef = useRef(new WeakMap()) const documentRef = useRef(document) - const editorBindingRef = useRef | null>(null) - const nativeCommitRef = useRef<(next: PresentationDocument) => void>(() => undefined) + const editorBindingRef = useRef | null>(null) + const nativeCommitRef = useRef<(next: PresentationProject) => void>(() => undefined) const flushNativeEditRef = useRef<(() => void) | null>(null) const pendingCanvasEditRef = useRef<(() => void) | null>(null) const pageSizeRef = useRef(pageSize) @@ -1917,8 +1821,6 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, }) const suppressCanvasSelectionRef = useRef(false) const canvasSelectionFrameRef = useRef(null) - const pastRef = useRef([]) - const futureRef = useRef([]) const animationRunIdRef = useRef(0) const transitionRunIdRef = useRef(0) const consumedAgentChangeIdRef = useRef(0) @@ -1931,6 +1833,12 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const currentSlide = document.slides.pages.find((slide) => slide.id === document.slides.selectedPageId) ?? document.slides.pages[0] + const currentCanvasRenderKey = currentSlide + ? JSON.stringify([document.id, documentRevision, currentSlide.id, canvasGeneration, agentChange?.changeId ?? 0]) + : null + const currentCanvasRenderStatus = canvasRenderState.key === currentCanvasRenderKey + ? canvasRenderState.status + : 'loading' const currentSlideBackground = currentSlide ? presentationSlideBackground(document.theme, currentSlide) : document.theme.background @@ -1945,30 +1853,17 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, : [] const selectedText = selectedElement && isPresentationTextElement(selectedElement) ? selectedElement : null - const commitDocument = useCallback((next: PresentationDocument, recordHistory = true) => { + const commitDocument = useCallback((next: PresentationProject, recordHistory = true) => { const current = documentRef.current - let versionedNext: PresentationDocument + let versionedNext: PresentationProject try { - versionedNext = presentationRuntime.commitDocument(current, next) + versionedNext = presentationStore.commitProject(current, next, true, recordHistory) } catch (error) { showToast(error instanceof Error ? error.message : String(error)) return } - if (recordHistory) { - const entry = createPresentationHistoryEntry(current) - // An oversized state is an undo barrier. Keeping older entries would make - // Undo skip the latest change and restore an unrelated document state. - pastRef.current = entry - ? trimPresentationHistoryEntries([...pastRef.current, entry]) - : [] - futureRef.current = [] - } documentRef.current = versionedNext - setHistoryStatus({ - canUndo: pastRef.current.length > 0, - canRedo: futureRef.current.length > 0, - }) - }, [presentationRuntime, showToast]) + }, [presentationStore, showToast]) const replaceCurrentSlide = useCallback((nextSlide: PresentationSlide) => { const current = documentRef.current @@ -2170,8 +2065,6 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, }, [syncFabricObject, syncFabricObjects]) useEffect(() => { - pastRef.current = [] - futureRef.current = [] isolatedElementIdRef.current = null selectedElementIdRef.current = null const timer = window.setTimeout(() => { @@ -2181,7 +2074,6 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, setTransitionPreviewRun(null) setInsertDialog(null) setSelectedElementId(null) - setHistoryStatus({ canUndo: false, canRedo: false }) }, 0) return () => window.clearTimeout(timer) }, [document.id, sessionId]) @@ -2303,10 +2195,10 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, useEffect(() => { if (!active || !canvasElementRef.current) return - const binding = createOfficeEditorBinding({ + const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: sessionId ?? '', documentId: documentRef.current.id, onChange: (next, identity) => { - if (identity.documentId !== presentationRuntime.runtime.getSnapshot().activeDocumentId) return + if (identity.documentId !== presentationStore.runtime.getSnapshot().activeDocumentId) return nativeCommitRef.current(next) }, }) @@ -2474,7 +2366,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, setInsertDialog({ kind: element.type, elementId: element.id }) }) const driver = createPresentationEditorDriver({ - readSnapshot: () => store.get(presentationWorkspaceFamily(sessionId ?? '')).documents + readSnapshot: () => presentationStore.getSnapshot().projects .find((item) => item.id === binding.capture().identity.documentId) ?? null, readEditingObject: () => canvas.getActiveObject() as (FabricObject & PresentationEditingObject) | null, flushPendingEdit: () => { @@ -2509,7 +2401,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, }) if (!binding.attach(driver)) return flushNativeEditRef.current = () => { void driver.flush(binding.capture()) } - unregisterEditor = presentationRuntime.bindEditor(binding) + unregisterEditor = presentationStore.bindEditor(binding) setCanvasGeneration((value) => value + 1) }) return () => { @@ -2517,7 +2409,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, binding.dispose() if (editorBindingRef.current === binding) editorBindingRef.current = null } - }, [activateFabricElement, active, presentationRuntime, sessionId, store]) + }, [activateFabricElement, active, presentationStore, sessionId]) useEffect(() => { const canvas = canvasRef.current @@ -2526,6 +2418,19 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, if (!active || !canvas || !fabric || !mediaRuntime || !currentSlide) return const lease = editorBindingRef.current?.capture() let cancelled = false + const renderKey = JSON.stringify([document.id, documentRevision, currentSlide.id, canvasGeneration, agentChange?.changeId ?? 0]) + let pendingElements = currentSlide.elements.length + let renderFailed = false + const finishElement = () => { + pendingElements -= 1 + if (!cancelled && !renderFailed && pendingElements === 0) { + setCanvasRenderState({ key: renderKey, status: 'ready' }) + } + } + const failRender = () => { + renderFailed = true + if (!cancelled) setCanvasRenderState({ key: renderKey, status: 'error' }) + } const revealFrameIds = new Set() const visibleAgentChange = agentChange && agentChange.slideId === currentSlide.id @@ -2543,7 +2448,10 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, revealFrameIds.add(frameId) } const animateAgentObject = (object: FabricObject, element: PresentationElement, index: number) => { - if (!visibleAgentChange || reducedMotion || !revealedElementIds.has(element.id)) return + if (!visibleAgentChange || reducedMotion || !revealedElementIds.has(element.id)) { + finishElement() + return + } const delayMs = Math.min(240, index * 32) const targetOpacity = element.opacity ?? 1 if ( @@ -2569,7 +2477,11 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, object.setCoords() canvas.requestRenderAll() if (progress < 1) scheduleRevealFrame(tick) - else object.set({ text: fullText }) + else { + object.set({ text: fullText }) + canvas.requestRenderAll() + finishElement() + } } scheduleRevealFrame(tick) return @@ -2588,7 +2500,11 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, object.set({ opacity: targetOpacity * eased }) canvas.requestRenderAll() if (progress < 1) scheduleRevealFrame(tick) - else object.set({ opacity: targetOpacity }) + else { + object.set({ opacity: targetOpacity }) + canvas.requestRenderAll() + finishElement() + } } scheduleRevealFrame(tick) } @@ -2608,6 +2524,11 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const slideNumber = documentRef.current.slides.pages.findIndex((slide) => slide.id === currentSlide.id) + 1 createFooterFabricObjects(fabric, document.theme, currentSlide, Math.max(1, slideNumber), pageSize).forEach((object) => canvas.add(object)) canvas.requestRenderAll() + if (pendingElements === 0) { + scheduleRevealFrame(() => { + if (!cancelled) setCanvasRenderState({ key: renderKey, status: 'ready' }) + }) + } currentSlide.elements.forEach((element, index) => { const source = isPresentationImageElement(element) || isPresentationMediaElement(element) @@ -2621,7 +2542,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, }) : () => undefined, source, ).then((object) => { - if (cancelled || !lease?.isCurrent() || canvasRef.current !== canvas) return + if (cancelled || (lease && !lease.isCurrent()) || canvasRef.current !== canvas) return let hoverCursor = 'move' if (isPresentationMediaElement(element)) hoverCursor = 'default' else if (element.hyperlink && supportsPresentationElementHyperlink(element)) hoverCursor = 'pointer' @@ -2655,6 +2576,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, canvas.requestRenderAll() }).catch((error: unknown) => { if (cancelled || canvasRef.current !== canvas) return + failRender() rlog.warn('[presentation] canvas element render failed', { elementId: element.id, elementType: element.type, @@ -2668,27 +2590,17 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, for (const frameId of revealFrameIds) window.cancelAnimationFrame(frameId) if (mediaRuntimeRef.current === mediaRuntime) mediaRuntime.reset() } - }, [activateFabricElement, active, agentChange, canvasGeneration, currentSlide, currentSlideBackground, document.theme, pageSize]) + }, [activateFabricElement, active, agentChange, canvasGeneration, currentSlide, currentSlideBackground, document.id, documentRevision, document.theme, pageSize]) const undo = useCallback(() => { - const previous = pastRef.current.pop() - if (!previous) return - const current = createPresentationHistoryEntry(documentRef.current) - if (current) futureRef.current.push(current) - else futureRef.current = [] - trimPresentationHistoryPair(pastRef.current, futureRef.current) - commitDocument(previous.document, false) - }, [commitDocument]) + const previous = presentationStore.undo() + if (previous) documentRef.current = previous + }, [presentationStore]) const redo = useCallback(() => { - const next = futureRef.current.pop() - if (!next) return - const current = createPresentationHistoryEntry(documentRef.current) - if (current) pastRef.current.push(current) - else pastRef.current = [] - trimPresentationHistoryPair(pastRef.current, futureRef.current) - commitDocument(next.document, false) - }, [commitDocument]) + const next = presentationStore.redo() + if (next) documentRef.current = next + }, [presentationStore]) const deleteSelectedElement = useCallback(() => { const elementId = selectedElementIdRef.current @@ -2804,7 +2716,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, if (current.slides.selectedPageId === slideId) return const selected = { ...current, slides: selectPresentationPage(current.slides, slideId) } try { - documentRef.current = presentationRuntime.commitDocument(current, selected, false) + documentRef.current = presentationStore.commitProject(current, selected, false, false) } catch (error) { showToast(error instanceof Error ? error.message : String(error)) } @@ -2812,12 +2724,10 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const [saving, setSaving] = useState(false) const savePresentation = useCallback((saveAs: boolean) => { - if (!onSave) return setSaving(true) - void onSave(document.id, saveAs).catch((error) => showToast(String(error))).finally(() => setSaving(false)) - }, [document.id, onSave, showToast]) + void presentationStore.save(document.id, saveAs).catch((error) => showToast(String(error))).finally(() => setSaving(false)) + }, [document.id, presentationStore, showToast]) useEffect(() => { - if (!onSave) return const key = (event: KeyboardEvent) => { if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 's') return event.preventDefault() @@ -2825,33 +2735,28 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, } window.addEventListener('keydown', key) return () => window.removeEventListener('keydown', key) - }, [onSave, savePresentation]) + }, [savePresentation]) - const selectPresentationDocument = (documentId: string) => { - void presentationRuntime.activateDocument(documentId).then((result) => { - if (!result.ok) showToast(result.error.message) - }) + const selectPresentationProject = (documentId: string) => { + void presentationStore.selectProject(documentId).catch((error) => showToast(error instanceof Error ? error.message : String(error))) } - const createPresentationDocument = () => { - void presentationRuntime.createDocument().then((result) => { - if (!result.ok) showToast(result.error.message) - }) + const createPresentationProject = () => { + void presentationStore.createProject().catch((error) => showToast(error instanceof Error ? error.message : String(error))) } - const closePresentationDocument = (documentId: string) => { - void presentationRuntime.closeDocument(documentId).then((result) => { - if (!result.ok) showToast(result.error.message) - else if (result.value.closeSurface) { + const closePresentationProject = (documentId: string) => { + void presentationStore.closeProject(documentId).then((result) => { + if (result.closeSurface) { setExpanded(false) if (onClose) onClose() else setRightCollapsed(true) } - }) + }).catch((error) => showToast(error instanceof Error ? error.message : String(error))) } const closePresentationPanel = () => { - void presentationRuntime.flushEditor().then(() => { + void presentationStore.flushEditor().then(() => { setExpanded(false) if (onClose) onClose() else setRightCollapsed(true) @@ -3318,7 +3223,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const changePageSize = (preset: PresentationPageSizePreset) => { const current = documentRef.current - commitDocument(resizePresentationDocument(current, preset)) + commitDocument(resizePresentationProject(current, preset)) } const applyCurrentTransitionToAll = () => { @@ -3492,7 +3397,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, const previewWidth = compact ? 78 : 126 const sessionTarget = sessionId ? sessionId.slice(0, 8).toUpperCase() : '—' - const documentFileName = (item: PresentationDocument) => { + const documentFileName = (item: PresentationProject) => { const title = item.title.trim() || t('session.presentation.untitled') return title.toLowerCase().endsWith('.pptx') ? title : `${title}.pptx` } @@ -3590,21 +3495,22 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, : undefined} - activeId={workspace.activeDocumentId} + actions={} + activeId={presentationSnapshot.activeProjectId} icon={} label={t('session.presentation.documentTabs')} newIcon={} newLabel={t('session.presentation.newPresentation')} - onClose={closePresentationDocument} - onCreate={createPresentationDocument} - onSelect={selectPresentationDocument} - tabs={workspace.documents.map((item) => { - const fileName = item.source?.path.split(/[\\/]/).at(-1) || documentFileName(item) + onClose={closePresentationProject} + onCreate={createPresentationProject} + onSelect={selectPresentationProject} + tabs={presentationSnapshot.projects.map((item) => { + const metadata = presentationSnapshot.projectMetadata[item.id]! + const fileName = metadata.source?.path.split(/[\\/]/).at(-1) || documentFileName(item) return { id: item.id, label: fileName, - dirtyLabel: isPresentationDirty(item) ? t('office.unsaved') : undefined, + dirtyLabel: isPresentationProjectDirty(metadata) ? t('office.unsaved') : undefined, closeLabel: t('session.presentation.closeDocument', { name: fileName }), } })} @@ -3612,7 +3518,7 @@ export function PresentationWorkbenchPanel({ active, onClose, onExpandedChange, tooltipOptions={{ appearance: 'presentation', delayMs: 0 }} /> - {document.sourceProtected ?
{t('office.importedCopyNotice')}
: null} + {documentMetadata.sourceProtected ?
{t('office.importedCopyNotice')}
: null}
diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/EmbeddedPowerPointPanel.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/EmbeddedPowerPointPanel.test.tsx index b2186955..d68861a5 100644 --- a/desktop/apps/electron/src/renderer/components/app/__tests__/EmbeddedPowerPointPanel.test.tsx +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/EmbeddedPowerPointPanel.test.tsx @@ -76,6 +76,7 @@ function powerPointApi(calls: string[]): ElectronAPI['powerpoint'] { setVisible: async (visible) => { calls.push(`setVisible:${visible}`) }, requestClose: async () => undefined, setExpanded: async () => undefined, + reportState: async () => undefined, openFile: async (_sessionId, absPath) => ({ documentId: 'document-1', fileName: absPath.split('/').at(-1) ?? '', @@ -93,6 +94,7 @@ function sessionInfo(sessionId: string): EmbeddedPowerPointSessionInfo { webContentsId: 42, loading: false, crashed: false, + documentCount: null, } } diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/OfficeLaunchEmptyState.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/OfficeLaunchEmptyState.test.tsx new file mode 100644 index 00000000..0e9be0a1 --- /dev/null +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/OfficeLaunchEmptyState.test.tsx @@ -0,0 +1,63 @@ +import { afterAll, afterEach, describe, expect, it, mock } from 'bun:test' +import { GlobalRegistrator } from '@happy-dom/global-registrator' + +GlobalRegistrator.register() +;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const { act } = await import('react') +const { createRoot } = await import('react-dom/client') +const { OfficeLaunchEmptyState } = await import('../OfficeLaunchEmptyState') + +afterEach(() => document.body.replaceChildren()) +afterAll(async () => { await GlobalRegistrator.unregister() }) + +describe('OfficeLaunchEmptyState', () => { + it('uses one layout and the same create/open controls for PPT, Word, and Excel', async () => { + const kinds = [ + ['presentation', 'powerpoint'], + ['word', 'word'], + ['excel', 'excel'], + ] as const + const buttonClasses: string[][] = [] + for (const [kind, prefix] of kinds) { + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + await act(async () => root.render( + undefined} onOpen={() => undefined} />, + )) + const state = host.querySelector(`[data-testid="${prefix}-launch-empty-state"]`) + const buttons = [...host.querySelectorAll('button')] + expect(state).not.toBeNull() + expect(buttons).toHaveLength(2) + expect(host.querySelector(`[data-testid="${prefix}-open-file"]`)).not.toBeNull() + buttonClasses.push(buttons.map((button) => button.className)) + await act(async () => root.unmount()) + host.remove() + } + expect(buttonClasses[1]).toEqual(buttonClasses[0]) + expect(buttonClasses[2]).toEqual(buttonClasses[0]) + }) + + it('serializes launch actions and reports an open failure without creating a document', async () => { + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + const create = mock(() => undefined) + let rejectOpen!: (error: Error) => void + const open = mock(() => new Promise((_resolve, reject) => { rejectOpen = reject })) + try { + await act(async () => root.render()) + await act(async () => host.querySelector('[data-testid="word-open-file"]')!.click()) + expect(open).toHaveBeenCalledTimes(1) + expect([...host.querySelectorAll('button')].every((button) => button.disabled)).toBe(true) + await act(async () => rejectOpen(new Error('Import failed'))) + expect(host.querySelector('[role="alert"]')).not.toBeNull() + expect(create).not.toHaveBeenCalled() + expect([...host.querySelectorAll('button')].every((button) => !button.disabled)).toBe(true) + } finally { + await act(async () => root.unmount()) + host.remove() + } + }) +}) diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationChartDisplay.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationChartDisplay.test.tsx index e65a1076..2baeb2e6 100644 --- a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationChartDisplay.test.tsx +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationChartDisplay.test.tsx @@ -2,39 +2,40 @@ import { afterAll, afterEach, beforeEach, describe, expect, it } from 'bun:test' import { GlobalRegistrator } from '@happy-dom/global-registrator' import { DOMParser } from '@xmldom/xmldom' import JSZip from 'jszip' -import { presentationSlideBackground, replacePresentationPages, type PresentationChartElement, type PresentationDocument } from '@/atoms/presentation' +import { presentationSlideBackground, type PresentationChartElement, type PresentationProject } from '@/atoms/presentation' GlobalRegistrator.register() const { renderToStaticMarkup } = await import('react-dom/server') const fabric = await import('fabric') -const { createBlankPresentationDocument } = await import('@/atoms/presentation') +const { createBlankPresentationProject } = await import('@/atoms/presentation') const { createPresentationChartElement, createPresentationTableElement } = await import('@/lib/presentationInsert') const { createPresentationPptx } = await import('@/lib/presentationPptx') const { importPresentationPptx } = await import('@/lib/presentationPptxImport') const { applyPresentationDesign } = await import('@/lib/presentationDesign') -const { compilePresentationSlideMarkdown, decompilePresentationSlideMarkdown } = await import('@/lib/presentationMarkdown') +const { editPresentationPage } = await import('@/presentation/agentCommands') const { PresentationSlidePreview } = await import('../PresentationSlidePreview') const { createPresentationFabricObject } = await import('../PresentationWorkbenchPanel') const parse = (xml: string) => new DOMParser().parseFromString(xml, 'text/xml') const chartNs = 'http://schemas.openxmlformats.org/drawingml/2006/chart' -function documentFor(element: PresentationDocument['slides']['pages'][number]['elements'][number]) { - const model = createBlankPresentationDocument('Chart fidelity') +function documentFor(element: PresentationProject['slides']['pages'][number]['elements'][number]) { + const model = createBlankPresentationProject('Chart fidelity') model.slides.pages[0]!.elements = [element] return model } -function markup(model: PresentationDocument) { +function markup(model: PresentationProject) { const host = document.createElement('div') host.innerHTML = renderToStaticMarkup() return host } -function agentEdit(model: PresentationDocument): PresentationDocument { - return { - ...model, - slides: replacePresentationPages(model.slides, [compilePresentationSlideMarkdown(decompilePresentationSlideMarkdown(model.slides.pages[0]!), { document: model }).slide]), - } +function agentEdit(model: PresentationProject): PresentationProject { + const page = model.slides.pages[0]! + const element = page.elements[0]! + return editPresentationPage(model, page.id, [{ + type: 'patch', id: element.id, element_type: element.type, patch: { x: element.x }, + }]).project } afterAll(() => GlobalRegistrator.unregister()) diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationInsertIntegration.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationInsertIntegration.test.tsx index 17bfabac..1d3b0530 100644 --- a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationInsertIntegration.test.tsx +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationInsertIntegration.test.tsx @@ -9,21 +9,34 @@ const { act } = await import('react') const { createRoot } = await import('react-dom/client') const { Simulate } = await import('react-dom/test-utils') const { createStore, Provider } = await import('jotai') -const { createBlankPresentationDocument, currentPresentationDocumentAtom, selectPresentationPage } = await import('@/atoms/presentation') +const { createBlankPresentationProject, selectPresentationPage } = await import('@/atoms/presentation') const { activeSessionIdAtom } = await import('@/atoms/sessions') const { settingsAtom } = await import('@/atoms/settings') const { toastAtom } = await import('@/atoms/toast') const { i18n } = await import('@/lib/i18n') const { createPresentationMediaElement } = await import('@/lib/presentationInsert') const { createPresentationAsset, presentationElementSource } = await import('@/presentation/project') +const { estimatePresentationProjectBytes } = await import('@/presentation/history') const { createPresentationTestDocument } = await import('@/test-fixtures/presentation') +const { createPresentationTestStore, readPresentationTestProject, replacePresentationTestProject } = await import('@/test-fixtures/presentation-store') const { canAppendPresentationFileElement, - estimatePresentationDocumentBytes, PresentationWorkbenchPanel, } = await import('../PresentationWorkbenchPanel') const mountedRoots = new Set() +const presentationStores = new Set>>() +const presentationStoreByJotaiStore = new WeakMap>>() + +function presentationStoreOf(store: object) { + const presentationStore = presentationStoreByJotaiStore.get(store) + if (!presentationStore) throw new Error('Missing presentation test Store') + return presentationStore +} + +function projectOf(store: object) { + return readPresentationTestProject(presentationStoreOf(store)) +} beforeEach(async () => { await i18n.changeLanguage('zh') @@ -34,6 +47,8 @@ afterEach(async () => { for (const root of mountedRoots) root.unmount() mountedRoots.clear() }) + for (const store of presentationStores) store.dispose() + presentationStores.clear() document.body.replaceChildren() }) @@ -45,8 +60,11 @@ async function mountPanel() { const store = createStore() const settings = store.get(settingsAtom) store.set(settingsAtom, { ...settings, ui: { ...settings.ui, lastNav: 'home' } }) - store.set(activeSessionIdAtom, `presentation-insert-${Math.random()}`) - store.set(currentPresentationDocumentAtom, createPresentationTestDocument()) + const sessionId = `presentation-insert-${Math.random()}` + store.set(activeSessionIdAtom, sessionId) + const presentationStore = await createPresentationTestStore(sessionId, createPresentationTestDocument()) + presentationStores.add(presentationStore) + presentationStoreByJotaiStore.set(store, presentationStore) const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) @@ -54,7 +72,7 @@ async function mountPanel() { await act(async () => { root.render( - + , ) await new Promise((resolve) => setTimeout(resolve, 20)) @@ -98,7 +116,7 @@ describe('presentation Insert tab integration', () => { await act(async () => host.querySelector('[data-testid="presentation-insert-table"]')!.click()) await submitOpenDialog() - let presentation = store.get(currentPresentationDocumentAtom) + let presentation = projectOf(store) let slide = presentation.slides.pages.find((item) => item.id === presentation.slides.selectedPageId)! const table = slide.elements.at(-1) expect(table?.type).toBe('table') @@ -107,7 +125,7 @@ describe('presentation Insert tab integration', () => { await act(async () => host.querySelector('[data-testid="presentation-insert-chart"]')!.click()) await submitOpenDialog() - presentation = store.get(currentPresentationDocumentAtom) + presentation = projectOf(store) slide = presentation.slides.pages.find((item) => item.id === presentation.slides.selectedPageId)! const chart = slide.elements.at(-1) expect(chart?.type).toBe('chart') @@ -122,7 +140,7 @@ describe('presentation Insert tab integration', () => { await setInputValue(document.querySelector('[data-testid="presentation-insert-link-url"]')!, 'https://example.com/docs') await setInputValue(document.querySelector('[data-testid="presentation-insert-link-label"]')!, 'Documentation') await submitOpenDialog() - presentation = store.get(currentPresentationDocumentAtom) + presentation = projectOf(store) slide = presentation.slides.pages.find((item) => item.id === presentation.slides.selectedPageId)! const link = slide.elements.at(-1) expect(link?.type).toBe('text') @@ -134,7 +152,7 @@ describe('presentation Insert tab integration', () => { await act(async () => host.querySelector('[data-testid="presentation-insert-footer"]')!.click()) await setInputValue(document.querySelector('[data-testid="presentation-insert-footer-text"]')!, 'Confidential') await submitOpenDialog() - presentation = store.get(currentPresentationDocumentAtom) + presentation = projectOf(store) expect(presentation.theme.footer).toEqual({ text: 'Confidential', showDate: false, showSlideNumber: true }) expect(presentation.slides.pages.every((item) => item.footer === undefined)).toBe(true) expect(host.querySelector('[data-testid="presentation-slide-preview"]')?.textContent).toContain('Confidential') @@ -195,7 +213,7 @@ describe('presentation Insert tab integration', () => { else Reflect.deleteProperty(URL, 'revokeObjectURL') } - const presentation = store.get(currentPresentationDocumentAtom) + const presentation = projectOf(store) const slide = presentation.slides.pages.find((item) => item.id === presentation.slides.selectedPageId)! const inserted = slide.elements.slice(-3) expect(inserted.map((element) => element.type)).toEqual(['image', 'audio', 'video']) @@ -231,7 +249,7 @@ describe('presentation Insert tab integration', () => { await new Promise((resolve) => setTimeout(resolve, 20)) }) - const presentation = store.get(currentPresentationDocumentAtom) + const presentation = projectOf(store) expect(presentation.slides.pages.every((slide) => slide.elements.every((element) => element.type !== 'audio'))).toBe(true) expect(store.get(toastAtom)?.message).toBe('无法读取所选文件,或不支持该文件格式。') @@ -242,7 +260,7 @@ describe('presentation Insert tab integration', () => { }) it('prevents embedded files from making the document exceed the undo-safe budget', () => { - const documentModel = createBlankPresentationDocument('Media budget') + const documentModel = createBlankPresentationProject('Media budget') const source = { dataUrl: `data:video/mp4;base64,${'A'.repeat(400)}`, fileName: 'large.mp4', @@ -254,7 +272,7 @@ describe('presentation Insert tab integration', () => { const secondAsset = createPresentationAsset('video', source, second.sourceAssetId) documentModel.assets.push(firstAsset) documentModel.slides.pages[0]!.elements.push(first) - const currentBytes = estimatePresentationDocumentBytes(documentModel) + const currentBytes = estimatePresentationProjectBytes(documentModel) expect(canAppendPresentationFileElement(documentModel, second, secondAsset, currentBytes + 100)).toBe(false) expect(canAppendPresentationFileElement(documentModel, second, secondAsset, currentBytes + 10_000)).toBe(true) @@ -262,7 +280,7 @@ describe('presentation Insert tab integration', () => { it('cancels an asynchronous file insertion when its target slide changes', async () => { const { host, root, store } = await mountPanel() - const initial = store.get(currentPresentationDocumentAtom) + const initial = projectOf(store) const targetSlide = initial.slides.pages[0]! const otherSlide = initial.slides.pages[1]! expect(initial.slides.selectedPageId).toBe(targetSlide.id) @@ -284,7 +302,7 @@ describe('presentation Insert tab integration', () => { expect(pendingRead.current).not.toBeUndefined() await act(async () => { - store.set(currentPresentationDocumentAtom, { ...initial, slides: selectPresentationPage(initial.slides, otherSlide.id) }) + replacePresentationTestProject(presentationStoreOf(store), { ...initial, slides: selectPresentationPage(initial.slides, otherSlide.id) }) await Promise.resolve() }) const read = pendingRead.current @@ -294,7 +312,7 @@ describe('presentation Insert tab integration', () => { await new Promise((resolve) => setTimeout(resolve, 20)) }) - const current = store.get(currentPresentationDocumentAtom) + const current = projectOf(store) expect(current.slides.selectedPageId).toBe(otherSlide.id) expect(current.slides.pages.every((slide) => slide.elements.every((element) => element.type !== 'audio'))).toBe(true) expect(store.get(toastAtom)?.message).toBe('已取消') @@ -309,7 +327,7 @@ describe('presentation Insert tab integration', () => { it('follows an internal slide link during slide show playback', async () => { const { host, root, store } = await mountPanel() - const presentation = store.get(currentPresentationDocumentAtom) + const presentation = projectOf(store) const targetSlide = presentation.slides.pages[1]! await act(async () => host.querySelector('[data-testid="presentation-insert-link"]')!.click()) diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationInsertRuntime.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationInsertRuntime.test.tsx index ef5180f1..7dc07f55 100644 --- a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationInsertRuntime.test.tsx +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationInsertRuntime.test.tsx @@ -11,7 +11,7 @@ const { createRoot } = await import('react-dom/client') const { renderToStaticMarkup } = await import('react-dom/server') const { Simulate } = await import('react-dom/test-utils') const fabric = await import('fabric') -const { createBlankPresentationDocument } = await import('@/atoms/presentation') +const { createBlankPresentationProject } = await import('@/atoms/presentation') const { createPresentationImageElement, createPresentationMediaElement, @@ -19,7 +19,6 @@ const { createPresentationChartElement, } = await import('@/lib/presentationInsert') const { - createPresentationHistoryEntry, createPresentationImageFabricClipPath, createPresentationMediaFabricObject, createPresentationMediaRuntime, @@ -27,13 +26,12 @@ const { createPresentationTextFabricObject, createPresentationFabricObject, getPresentationTextFabricFramePatch, - estimatePresentationDocumentBytes, isPresentationRotationLocked, PresentationNumberField, resolvePresentationNumberFieldValue, resolvePresentationSlideshowKeyAction, - trimPresentationHistoryEntries, } = await import('../PresentationWorkbenchPanel') +const { createPresentationHistoryEntry, estimatePresentationProjectBytes, trimPresentationHistoryEntries } = await import('@/presentation/history') const { getPresentationPieSlices, getPresentationChartRange, @@ -43,7 +41,7 @@ const { const { importPresentationPptx } = await import('@/lib/presentationPptxImport') const { createPresentationPptx } = await import('@/lib/presentationPptx') -const { compilePresentationSlideMarkdown, decompilePresentationSlideMarkdown } = await import('@/lib/presentationMarkdown') +const { editPresentationPage } = await import('@/presentation/agentCommands') const { createPresentationAsset } = await import('@/presentation/project') const mountedRoots = new Set() @@ -72,7 +70,7 @@ describe('presentation Insert runtime safeguards', () => { it.each([[0.2, 0.3], [2e-300, 3e-300], [2e300, 3e300]].map(values => [values] as const))('normalizes fractional pie data consistently in preview and Fabric: %j', async (values) => { const element = { ...createPresentationChartElement('pie'), width: 800, height: 400, title: undefined, showLegend: false, categories: ['A', 'B'], series: [{ name: 'Total', values }], colors: ['#FF6600', '#00AA88'] } - const model = createBlankPresentationDocument('Proportions') + const model = createBlankPresentationProject('Proportions') model.slides.pages[0]!.elements = [element] const host = document.createElement('div') host.innerHTML = renderToStaticMarkup() @@ -93,7 +91,7 @@ describe('presentation Insert runtime safeguards', () => { it.each(['transparent', '#FFFFFF', '#152945'])('leaves a real hole in single-value doughnuts over %s', async (fill) => { const element = { ...createPresentationChartElement('doughnut'), width: 800, height: 400, title: undefined, showLegend: false, categories: ['A', 'B', 'C'], series: [{ name: 'Total', values: [0, 50, 0] }], colors: ['#FF6600', '#00AA88', '#2266EE'], chartAreaFill: fill, plotAreaFill: fill } - const model = createBlankPresentationDocument('Open ring') + const model = createBlankPresentationProject('Open ring') model.slides.pages[0]!.elements = [element] const host = document.createElement('div') host.innerHTML = renderToStaticMarkup() @@ -120,7 +118,7 @@ describe('presentation Insert runtime safeguards', () => { it.each(['line', 'lineArrow', 'lineDoubleArrow', 'elbowConnector', 'elbowArrow', 'curvedConnector', 'curvedArrow'] as const)('preserves the existing %s path, transform and editability across repeated exports', async (type) => { for (const transform of [{ rotation: 0 }, { rotation: 37, flipHorizontal: true }, { rotation: 90, flipVertical: true }]) { - let model = createBlankPresentationDocument('Connector fidelity') + let model = createBlankPresentationProject('Connector fidelity') const element = { id: 'connector', type, x: 100, y: 150, width: 700, height: 300, fill: 'transparent', borderColor: '#111111', borderWidth: 6, ...transform } model.slides.pages[0]!.elements = [element] const original = await createPresentationFabricObject(fabric, element, () => undefined) @@ -128,7 +126,11 @@ describe('presentation Insert runtime safeguards', () => { const originalPath = original.getObjects().find(object => object instanceof fabric.Path)! for (let round = 0; round < 2; round++) { model = await importPresentationPptx(await createPresentationPptx(model)) - model.slides.pages = [compilePresentationSlideMarkdown(decompilePresentationSlideMarkdown(model.slides.pages[0]!), { document: model }).slide] + const page = model.slides.pages[0]! + const connector = page.elements[0]! + model = editPresentationPage(model, page.id, [{ + type: 'patch', id: connector.id, element_type: connector.type, patch: { x: connector.x }, + }]).project const reopened = model.slides.pages[0]!.elements[0]! expect(reopened.type).toBe(type) const current = await createPresentationFabricObject(fabric, reopened, () => undefined) @@ -231,7 +233,7 @@ describe('presentation Insert runtime safeguards', () => { value: () => ({ font: '', textBaseline: 'alphabetic', measureText: (value: string) => ({ width: value.length * 12 }) }), }) try { - const model = createBlankPresentationDocument('Blank paragraphs') + const model = createBlankPresentationProject('Blank paragraphs') const element: PresentationTextElement = { id: 'blank', type: 'text', text: '\nBefore\n\n\nAfter\n', x: 0, y: 0, width: 600, height: 600, rotation: 0, fontSize: 32, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', wordWrap, lineHeight: 1, paragraphs: [{ start: 0, end: 0, style: {}, endStyle: { fontSize: 64 } }, { start: 1, end: 7, style: {} }, @@ -280,7 +282,7 @@ describe('presentation Insert runtime safeguards', () => { return 0 } }) try { - const model = createBlankPresentationDocument('Short fixed spacing') + const model = createBlankPresentationProject('Short fixed spacing') const element: PresentationTextElement = { id: 'fixed', type: 'text', text: 'Small\nLARGE\nSmall', x: 0, y: 0, width: 600, height: 620, rotation: 0, fontSize: 24, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', lineSpacing: 32, textRuns: [{ start: 6, end: 11, style: { fontSize: 120 } }] } @@ -317,7 +319,7 @@ describe('presentation Insert runtime safeguards', () => { value: () => ({ font: '', textBaseline: 'alphabetic', measureText: (value: string) => ({ width: value.length * 24 }) }), }) try { - const model = createBlankPresentationDocument('Vertical list') + const model = createBlankPresentationProject('Vertical list') const element: PresentationTextElement = { id: 'vertical', type: 'text', text: '背 景\n甲乙', x: 40, y: 40, width: 600, height: 600, rotation: 0, fontSize: 40, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', textDirection, paragraphs: [{ start: 0, end: 3, style: { listStyle: 'bullet', listBulletChar: '◆', listMarkerFontFamily: 'Georgia' } }, @@ -360,7 +362,7 @@ describe('presentation Insert runtime safeguards', () => { return 0 } }) try { - const model = createBlankPresentationDocument('Fixed spacing') + const model = createBlankPresentationProject('Fixed spacing') model.slides.pages[0]!.elements = [{ id: 'fixed', type: 'text', text: 'Small LARGE', x: 0, y: 0, width: 600, height: 96, rotation: 0, fontSize: 24, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', lineSpacing: 48, textRuns: [{ start: 6, end: 11, style: { fontSize: 80 } }] }] @@ -406,7 +408,7 @@ describe('presentation Insert runtime safeguards', () => { value: () => ({ font: '', textBaseline: 'alphabetic', measureText: (value: string) => ({ width: value.length * 12 }) }), }) try { - const model = createBlankPresentationDocument('Line height') + const model = createBlankPresentationProject('Line height') const element = { id: 'line-height', type: 'text' as const, text: 'Heading', x: 40, y: 40, width: 600, height: 64, rotation: 0, fontSize: 40, fontFamily: 'Arial', fontWeight: 400 as const, color: '#111111', align: 'left' as const, lineHeight, wordWrap: true } @@ -946,53 +948,53 @@ describe('presentation Insert runtime safeguards', () => { }) it('keeps ordinary history at 50 entries and trims embedded payloads by byte budget', () => { - const documentModel = createBlankPresentationDocument('History') - const plainBytes = estimatePresentationDocumentBytes(documentModel) + const documentModel = createBlankPresentationProject('History') + const plainBytes = estimatePresentationProjectBytes(documentModel) const source = fileSource('video/mp4', 'large.mp4', 'A'.repeat(2_000)) const media = createPresentationMediaElement('video', source) documentModel.assets.push(assetFor(media, source)) documentModel.slides.pages[0]!.elements.push(media) - const mediaBytes = estimatePresentationDocumentBytes(documentModel) + const mediaBytes = estimatePresentationProjectBytes(documentModel) expect(mediaBytes).toBeGreaterThan(plainBytes + 3_900) const entry = createPresentationHistoryEntry(documentModel, mediaBytes) expect(entry).not.toBeNull() - expect(entry!.document).not.toBe(documentModel) - expect(entry!.document.assets[0]!.source.dataUrl).toBe(documentModel.assets[0]!.source.dataUrl) + expect(entry!.project).not.toBe(documentModel) + expect(entry!.project.assets[0]!.source.dataUrl).toBe(documentModel.assets[0]!.source.dataUrl) expect(createPresentationHistoryEntry(documentModel, mediaBytes - 1)).toBeNull() const ordinaryEntries = Array.from({ length: 60 }, (_, index) => ({ - document: { ...documentModel, id: `document-${index}` }, + project: { ...documentModel, id: `document-${index}` }, estimatedBytes: 1, })) const entryLimited = trimPresentationHistoryEntries(ordinaryEntries, 50, 1_000) expect(entryLimited).toHaveLength(50) - expect(entryLimited[0]?.document.id).toBe('document-10') - expect(entryLimited.at(-1)?.document.id).toBe('document-59') + expect(entryLimited[0]?.project.id).toBe('document-10') + expect(entryLimited.at(-1)?.project.id).toBe('document-59') const byteLimited = trimPresentationHistoryEntries( ordinaryEntries.slice(0, 4).map((item) => ({ ...item, estimatedBytes: 40 })), 50, 100, ) - expect(byteLimited.map((item) => item.document.id)).toEqual(['document-2', 'document-3']) + expect(byteLimited.map((item) => item.project.id)).toEqual(['document-2', 'document-3']) }) it('preserves shared media sources across history clones', () => { - const document = createBlankPresentationDocument('Shared media') + const document = createBlankPresentationProject('Shared media') const source = fileSource('video/mp4', 'large.mp4', 'A'.repeat(10_000)) const media = createPresentationMediaElement('video', source) document.assets.push(assetFor(media, source)) document.slides.pages[0]!.elements = [media, { ...media, id: 'duplicated-media' }] - const estimatedBefore = estimatePresentationDocumentBytes(document) + const estimatedBefore = estimatePresentationProjectBytes(document) const entry = createPresentationHistoryEntry(document) expect(entry).not.toBeNull() - const [first, second] = entry!.document.slides.pages[0]!.elements + const [first, second] = entry!.project.slides.pages[0]!.elements expect(first?.type).toBe('video') expect(second?.type).toBe('video') if (first?.type === 'video' && second?.type === 'video') expect(first.sourceAssetId).toBe(second.sourceAssetId) - expect(entry!.document.assets).toHaveLength(1) - expect(estimatePresentationDocumentBytes(entry!.document)).toBe(estimatedBefore) + expect(entry!.project.assets).toHaveLength(1) + expect(estimatePresentationProjectBytes(entry!.project)).toBe(estimatedBefore) }) it('leaves media navigation keys to native controls while preserving slideshow shortcuts', () => { @@ -1019,7 +1021,7 @@ describe('presentation Insert runtime safeguards', () => { const audio = { ...createPresentationMediaElement('audio', audioSource), autoplay: true, muted: false } const video = { ...createPresentationMediaElement('video', videoSource), autoplay: true, muted: false } const assets = [assetFor(audio, audioSource), assetFor(video, videoSource)] - const slide = { ...createBlankPresentationDocument('Media').slides.pages[0]!, elements: [audio, video] } + const slide = { ...createBlankPresentationProject('Media').slides.pages[0]!, elements: [audio, video] } const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) @@ -1075,7 +1077,7 @@ describe('presentation Insert runtime safeguards', () => { it('ignores an obsolete slide-show audio play failure after playback restarts', async () => { const source = fileSource('audio/mpeg', 'restart-slideshow.mp3') const audio = createPresentationMediaElement('audio', source) - const slide = { ...createBlankPresentationDocument('Audio controls').slides.pages[0]!, elements: [audio] } + const slide = { ...createBlankPresentationProject('Audio controls').slides.pages[0]!, elements: [audio] } const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) @@ -1141,7 +1143,7 @@ describe('presentation Insert runtime safeguards', () => { const audio = { ...createPresentationMediaElement('audio', audioSource), autoplay: true } const video = { ...createPresentationMediaElement('video', videoSource), autoplay: true } const assets = [assetFor(audio, audioSource), assetFor(video, videoSource)] - const slide = { ...createBlankPresentationDocument('Strict media').slides.pages[0]!, elements: [audio, video] } + const slide = { ...createBlankPresentationProject('Strict media').slides.pages[0]!, elements: [audio, video] } const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) @@ -1186,7 +1188,7 @@ describe('presentation Insert runtime safeguards', () => { const initialVideoSource = fileSource('video/mp4', 'first.mp4', 'BBBB') const initialAudio = createPresentationMediaElement('audio', initialAudioSource) const initialVideo = createPresentationMediaElement('video', initialVideoSource) - const baseSlide = createBlankPresentationDocument('Media source replacement').slides.pages[0]! + const baseSlide = createBlankPresentationProject('Media source replacement').slides.pages[0]! const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) @@ -1235,7 +1237,7 @@ describe('presentation Insert runtime safeguards', () => { ...createPresentationMediaElement('audio', audioSource), hyperlink: { type: 'url' as const, url: 'https://example.com/unsupported-media-link' }, } - const slide = { ...createBlankPresentationDocument('Links').slides.pages[0]!, elements: [linkedImage, audio] } + const slide = { ...createBlankPresentationProject('Links').slides.pages[0]!, elements: [linkedImage, audio] } const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) @@ -1323,7 +1325,7 @@ describe('presentation Insert runtime safeguards', () => { expect(isPresentationRotationLocked(chart)).toBe(true) expect(isPresentationRotationLocked(image)).toBe(false) - const slide = { ...createBlankPresentationDocument('Rotation').slides.pages[0]!, elements: [media, table, chart, image] } + const slide = { ...createBlankPresentationProject('Rotation').slides.pages[0]!, elements: [media, table, chart, image] } const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) @@ -1338,7 +1340,7 @@ describe('presentation Insert runtime safeguards', () => { }) it('renders centered PowerPoint text at point-correct CSS size inside the full text box width', async () => { - const documentModel = createBlankPresentationDocument('Centered text') + const documentModel = createBlankPresentationProject('Centered text') const slide = documentModel.slides.pages[0]! slide.elements = [{ id: 'centered-title', @@ -1378,7 +1380,7 @@ describe('presentation Insert runtime safeguards', () => { }) it('renders East Asian vertical text in height-bound right-to-left columns', async () => { - const documentModel = createBlankPresentationDocument('Vertical poem') + const documentModel = createBlankPresentationProject('Vertical poem') const slide = documentModel.slides.pages[0]! slide.elements = [{ id: 'vertical-poem', @@ -1508,7 +1510,7 @@ describe('presentation Insert runtime safeguards', () => { x: element.x, y: element.y, width: element.width, height: element.height, rotation: 0, }) const mixedElement = { ...element, id: 'vertical-mixed', text: '目录 Contents' } - const model = createBlankPresentationDocument('Mixed vertical text') + const model = createBlankPresentationProject('Mixed vertical text') model.slides.pages[0]!.elements = [mixedElement] const host = document.createElement('div') host.innerHTML = renderToStaticMarkup() @@ -1543,7 +1545,7 @@ describe('presentation Insert runtime safeguards', () => { expect(clipPath).toBeInstanceOf(fabric.Ellipse) expect(clipPath).toMatchObject({ rx: element.width / 2, ry: element.height / 2 }) - const documentModel = createBlankPresentationDocument('Picture-filled ellipse') + const documentModel = createBlankPresentationProject('Picture-filled ellipse') documentModel.assets.push(assetFor(element, source)) documentModel.slides.pages[0]!.elements = [element] const host = document.createElement('div') @@ -1578,7 +1580,7 @@ describe('presentation Insert runtime safeguards', () => { showLegend: false, title: undefined, } - const slide = { ...createBlankPresentationDocument('Negative chart').slides.pages[0]!, elements: [chart] } + const slide = { ...createBlankPresentationProject('Negative chart').slides.pages[0]!, elements: [chart] } await act(async () => { root.render() }) @@ -1614,7 +1616,7 @@ describe('presentation Insert runtime safeguards', () => { it('uses a minimum logical chart viewport while retaining a legacy small frame', async () => { const chart = { ...createPresentationChartElement('column'), width: 8, height: 8 } - const slide = { ...createBlankPresentationDocument('Small chart').slides.pages[0]!, elements: [chart] } + const slide = { ...createBlankPresentationProject('Small chart').slides.pages[0]!, elements: [chart] } const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationSlideshowPlayback.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationSlideshowPlayback.test.tsx index 73cbb2d0..b80db38e 100644 --- a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationSlideshowPlayback.test.tsx +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationSlideshowPlayback.test.tsx @@ -1,20 +1,21 @@ import { afterAll, afterEach, beforeEach, describe, expect, it } from 'bun:test' import { GlobalRegistrator } from '@happy-dom/global-registrator' import type { Root } from 'react-dom/client' -import type { PresentationDocument, PresentationElement, PresentationFileSource, PresentationMediaElement, PresentationTextElement } from '@/atoms/presentation' +import type { PresentationProject, PresentationElement, PresentationFileSource, PresentationMediaElement, PresentationTextElement } from '@/atoms/presentation' GlobalRegistrator.register() ;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true const { act } = await import('react') const { createRoot } = await import('react-dom/client') const { createStore, Provider } = await import('jotai') -const { createBlankPresentationDocument, createBlankPresentationSlide, currentPresentationDocumentAtom, powerPointSessionIdOverrideAtom } = await import('@/atoms/presentation') +const { createBlankPresentationProject, createBlankPresentationSlide, powerPointSessionIdOverrideAtom } = await import('@/atoms/presentation') const { activeSessionIdAtom } = await import('@/atoms/sessions') const { settingsAtom } = await import('@/atoms/settings') const { installApiStub } = await import('@/lib/apiStub') const { i18n } = await import('@/lib/i18n') const { createPresentationMediaElement } = await import('@/lib/presentationInsert') const { createPresentationAsset } = await import('@/presentation/project') +const { createPresentationTestStore } = await import('@/test-fixtures/presentation-store') const { PresentationWorkbenchPanel } = await import('../PresentationWorkbenchPanel') const { PresentationAnimationPlayer } = await import('../PresentationAnimationPlayer') @@ -24,11 +25,12 @@ let plays: HTMLMediaElement[] let pauses: HTMLMediaElement[] let animations: Array<{ node: Element; options?: KeyframeAnimationOptions; frames: Keyframe[]; finish: () => void }> let roots: Root[] +let presentationStores: Awaited>[] beforeEach(async () => { await i18n.changeLanguage('zh') installApiStub() - plays = []; pauses = []; animations = []; roots = [] + plays = []; pauses = []; animations = []; roots = []; presentationStores = [] const playing = new WeakSet() Object.defineProperties(HTMLMediaElement.prototype, { paused: { configurable: true, get() { return !playing.has(this) } }, @@ -45,6 +47,7 @@ beforeEach(async () => { afterEach(async () => { await act(async () => roots.forEach(root => root.unmount())) + for (const store of presentationStores) store.dispose() for (const [key, descriptor] of descriptors) { if (descriptor) Object.defineProperty(HTMLMediaElement.prototype, key, descriptor) else Reflect.deleteProperty(HTMLMediaElement.prototype, key) @@ -60,22 +63,23 @@ function bullet(id: string, overrides: Partial = {}): P fontSize: 32, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', animation: 'appear', ...overrides } } -function attachMedia(model: PresentationDocument, media: PresentationMediaElement, source: PresentationFileSource): void { +function attachMedia(model: PresentationProject, media: PresentationMediaElement, source: PresentationFileSource): void { model.assets.push(createPresentationAsset(media.type, source, media.sourceAssetId)) } -async function mount(model: PresentationDocument) { +async function mount(model: PresentationProject) { const store = createStore() const settings = store.get(settingsAtom) store.set(settingsAtom, { ...settings, ui: { ...settings.ui, lastNav: 'home' } }) store.set(activeSessionIdAtom, 'slideshow-playback') store.set(powerPointSessionIdOverrideAtom, 'slideshow-playback') - store.set(currentPresentationDocumentAtom, model) + const presentationStore = await createPresentationTestStore('slideshow-playback', model) + presentationStores.push(presentationStore) const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) roots.push(root) - await act(async () => root.render()) + await act(async () => root.render()) await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)) }) await click(host, 'session.presentation.playFromCurrent') expect(host.textContent).toContain(model.title) @@ -94,7 +98,7 @@ async function finishStep() { describe('slideshow playback interactions', () => { it.each(['fillColor', 'textColor', 'zoom'] as const)('holds %s through later steps and the outgoing transition, then resets on revisit', async effect => { - const model = createBlankPresentationDocument('Emphasis lifecycle') + const model = createBlankPresentationProject('Emphasis lifecycle') const originalShape = { id: 'emphasis', type: 'rect' as const, x: 320, y: 200, width: 320, height: 160, rotation: 0, fill: '#CC2222', borderColor: '#CC2222', borderWidth: 0 } const element: PresentationElement = { ...(effect === 'textColor' ? bullet('Emphasis', { color: '#CC2222', textRuns: [{ start: 0, end: 8, style: { color: '#FF8800', fontSize: 21 } }] }) : originalShape), @@ -139,7 +143,7 @@ describe('slideshow playback interactions', () => { }) it.each(['zoom', 'textColor'] as const)('keeps %s hyperlinks usable and carries the held state into a linked transition', async effect => { - const model = createBlankPresentationDocument('Emphasis link') + const model = createBlankPresentationProject('Emphasis link') const target = createBlankPresentationSlide('Linked') target.transition = { effect: 'fade', durationMs: 800 } model.slides.pages.push(target) @@ -170,7 +174,7 @@ describe('slideshow playback interactions', () => { for (const type of ['audio', 'video'] as const) it.each([false, true])(`preserves ${type} with autoplay=%s through two unrelated animations and stops it on exit`, async autoplay => { const source = { dataUrl: type === 'audio' ? 'data:audio/wav;base64,UklGRg==' : 'data:video/mp4;base64,AAAAHGZ0eXBpc29t', fileName: 'Narration', mimeType: type === 'audio' ? 'audio/wav' : 'video/mp4' } const media = { ...createPresentationMediaElement(type, source), autoplay } - const model = createBlankPresentationDocument('Media lifecycle') + const model = createBlankPresentationProject('Media lifecycle') attachMedia(model, media, source) model.slides.pages[0]!.elements = [bullet('First'), media, bullet('Second')] model.slides.pages.push(createBlankPresentationSlide('Next')) @@ -200,7 +204,7 @@ describe('slideshow playback interactions', () => { it('plays and pauses from SVG and path hit targets without advancing the slide', async () => { const source = { dataUrl: 'data:audio/wav;base64,UklGRg==', fileName: 'Narration', mimeType: 'audio/wav' } const media = { ...createPresentationMediaElement('audio', source), autoplay: false } - const model = createBlankPresentationDocument('Audio controls') + const model = createBlankPresentationProject('Audio controls') attachMedia(model, media, source) model.slides.pages[0]!.elements = [media, bullet('Pending')] const host = await mount(model) @@ -221,7 +225,7 @@ describe('slideshow playback interactions', () => { }) it.each(['withPrevious', 'afterPrevious'] as const)('starts an initial %s animation once while retaining click steps', async animationStart => { - const model = createBlankPresentationDocument('Automatic intro') + const model = createBlankPresentationProject('Automatic intro') model.slides.pages[0]!.elements = [bullet('Automatic', { animationStart, animationDelay: 80 }), bullet('Manual')] const host = await mount(model) const slideshow = host.querySelector('[data-testid="presentation-slideshow"]')! @@ -240,7 +244,7 @@ describe('slideshow playback interactions', () => { }) it('waits for the incoming transition and replays automatic content on revisiting the slide', async () => { - const model = createBlankPresentationDocument('Transition and auto intro') + const model = createBlankPresentationProject('Transition and auto intro') const incoming = createBlankPresentationSlide('Incoming') incoming.transition = { effect: 'fade', durationMs: 800 } incoming.elements = [bullet('Automatic', { animationStart: 'afterPrevious' })] @@ -261,7 +265,7 @@ describe('slideshow playback interactions', () => { }) it('keeps explicit element-click triggers manual even with an automatic start setting', async () => { - const model = createBlankPresentationDocument('Element trigger') + const model = createBlankPresentationProject('Element trigger') model.slides.pages[0]!.elements = [bullet('Triggered', { animationStart: 'withPrevious', animationTrigger: 'elementClick' })] const host = await mount(model) expect(animations).toHaveLength(0) @@ -270,7 +274,7 @@ describe('slideshow playback interactions', () => { }) it('keeps ribbon animation previews silent', async () => { - const model = createBlankPresentationDocument('Silent preview') + const model = createBlankPresentationProject('Silent preview') const source = { dataUrl: 'data:audio/wav;base64,UklGRg==', fileName: 'Narration', mimeType: 'audio/wav' } const media = { ...createPresentationMediaElement('audio', source), autoplay: true } attachMedia(model, media, source) diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationStoreWorkbench.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationStoreWorkbench.test.tsx new file mode 100644 index 00000000..b8ae7433 --- /dev/null +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationStoreWorkbench.test.tsx @@ -0,0 +1,67 @@ +import { afterAll, afterEach, expect, it } from 'bun:test' +import { GlobalRegistrator } from '@happy-dom/global-registrator' +import type { OfficeFilesAPI } from '../../../../shared/office-files' + +GlobalRegistrator.register() +;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const { act } = await import('react') +const { createRoot } = await import('react-dom/client') +const { createStore, Provider } = await import('jotai') +const { powerPointSessionIdOverrideAtom } = await import('@/atoms/presentation') +const { settingsAtom } = await import('@/atoms/settings') +const { PresentationStore } = await import('@/presentation/store') +const { createPresentationTestDocument } = await import('@/test-fixtures/presentation') +const { PresentationWorkbenchPanel } = await import('../PresentationWorkbenchPanel') + +afterEach(() => { document.body.replaceChildren() }) +afterAll(async () => { await GlobalRegistrator.unregister() }) + +it('renders and edits the project owned by PresentationStore', async () => { + const project = createPresentationTestDocument() + let recovery: string | null = JSON.stringify({ + schemaVersion: 1, + activeProjectId: project.id, + projects: [project], + projectMetadata: { [project.id]: { revision: 1 } }, + }) + const files: OfficeFilesAPI = { + inspect: async (_kind, path) => ({ path, mtimeMs: 1 }), + save: async () => ({ ok: true, fileName: 'Project.pptx', source: { path: '/Project.pptx', mtimeMs: 2 } }), + confirmClose: async () => 'cancel', + getRecovery: async () => recovery, + setRecovery: async (_kind, _sessionId, value) => { recovery = value }, + } + const presentationStore = new PresentationStore('presentation-store-workbench', { + encode: async () => new Uint8Array(), + files, + importPptx: async () => { throw new Error('not used') }, + managedFiles: false, + }) + await presentationStore.restore() + const jotaiStore = createStore() + jotaiStore.set(powerPointSessionIdOverrideAtom, presentationStore.sessionId) + const settings = jotaiStore.get(settingsAtom) + jotaiStore.set(settingsAtom, { ...settings, ui: { ...settings.ui, lastNav: 'home' } }) + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + + try { + await act(async () => { + root.render() + }) + const initialPageCount = project.slides.pages.length + await act(async () => host.querySelector('[data-testid="presentation-compact-insert"]')!.click()) + await act(async () => document.querySelector('[data-testid="presentation-add-slide"]')!.click()) + expect(presentationStore.getSnapshot().project?.slides.pages).toHaveLength(initialPageCount + 1) + expect(presentationStore.getSnapshot().canUndo).toBe(true) + + const current = presentationStore.getSnapshot().project! + await act(async () => { presentationStore.commitProject(current, { ...current, title: 'Store-owned title' }) }) + expect(host.textContent).toContain('Store-owned title') + } finally { + await act(async () => root.unmount()) + presentationStore.dispose() + } +}) diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationWorkbenchPanel.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationWorkbenchPanel.test.tsx index 153be79b..86fe109d 100644 --- a/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationWorkbenchPanel.test.tsx +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/PresentationWorkbenchPanel.test.tsx @@ -8,17 +8,30 @@ const { act } = await import('react') const { createRoot } = await import('react-dom/client') const { Simulate } = await import('react-dom/test-utils') const { createStore, Provider } = await import('jotai') -const { currentPresentationDocumentAtom, currentPresentationWorkspaceAtom, presentationExpandedAtom, replacePresentationPages } = await import('@/atoms/presentation') +const { presentationExpandedAtom, replacePresentationPages } = await import('@/atoms/presentation') const { activeSessionIdAtom } = await import('@/atoms/sessions') const { settingsAtom } = await import('@/atoms/settings') const { i18n } = await import('@/lib/i18n') const { presentationTextStyleAt } = await import('@/lib/presentationText') const { installApiStub } = await import('@/lib/apiStub') const { createPresentationTestDocument } = await import('@/test-fixtures/presentation') +const { createPresentationTestStore, readPresentationTestProject, replacePresentationTestProject } = await import('@/test-fixtures/presentation-store') const { PresentationWorkbenchPanel } = await import('../PresentationWorkbenchPanel') const originalElementAnimateDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'animate') let transitionAnimationCalls: Keyframe[][] = [] +const presentationStores = new Set>>() +const presentationStoreByJotaiStore = new WeakMap>>() + +function presentationStoreOf(store: object) { + const presentationStore = presentationStoreByJotaiStore.get(store) + if (!presentationStore) throw new Error('Missing presentation test Store') + return presentationStore +} + +function projectOf(store: object) { + return readPresentationTestProject(presentationStoreOf(store)) +} function installTransitionAnimationMock() { Object.defineProperty(Element.prototype, 'animate', { @@ -45,6 +58,8 @@ beforeEach(async () => { }) afterEach(() => { + for (const store of presentationStores) store.dispose() + presentationStores.clear() if (originalElementAnimateDescriptor) Object.defineProperty(Element.prototype, 'animate', originalElementAnimateDescriptor) else Reflect.deleteProperty(Element.prototype, 'animate') document.body.replaceChildren() @@ -59,14 +74,19 @@ async function mountPanel(withTestContent = true, onClose?: () => void, onExpand const settings = store.get(settingsAtom) store.set(settingsAtom, { ...settings, ui: { ...settings.ui, lastNav: 'home' } }) store.set(activeSessionIdAtom, 'presentation-session') - if (withTestContent) store.set(currentPresentationDocumentAtom, createPresentationTestDocument()) + const presentationStore = await createPresentationTestStore( + 'presentation-session', + withTestContent ? createPresentationTestDocument() : undefined, + ) + presentationStores.add(presentationStore) + presentationStoreByJotaiStore.set(store, presentationStore) const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) await act(async () => { root.render( - + , ) }) @@ -81,14 +101,14 @@ describe('PresentationWorkbenchPanel', () => { it('applies a theme as a global default without erasing page background overrides', async () => { const { host, root, store } = await mountPanel() try { - const initial = store.get(currentPresentationDocumentAtom) + const initial = projectOf(store) expect(initial.slides.pages[0]!.background).toBeUndefined() expect(initial.slides.pages[1]!.background).toBe('#F7F6F2') await act(async () => host.querySelector('[data-testid="presentation-tab-design"]')!.click()) await act(async () => host.querySelector('[aria-label="深夜"]')!.click()) - const themed = store.get(currentPresentationDocumentAtom) + const themed = projectOf(store) expect(themed.theme.background).toBe('#17182B') expect(themed.slides.pages[0]!.background).toBeUndefined() expect(themed.slides.pages[1]!.background).toBe('#F7F6F2') @@ -100,7 +120,7 @@ describe('PresentationWorkbenchPanel', () => { expect(inheritBackground.disabled).toBe(false) await act(async () => inheritBackground.click()) - const inherited = store.get(currentPresentationDocumentAtom) + const inherited = projectOf(store) expect(inherited.slides.pages[1]!.background).toBeUndefined() expect(Object.hasOwn(inherited.slides.pages[1]!, 'background')).toBe(false) expect(inherited.theme.background).toBe('#17182B') @@ -112,11 +132,11 @@ describe('PresentationWorkbenchPanel', () => { it('restores the current slide footer to theme inheritance', async () => { const { host, root, store } = await mountPanel() try { - const current = store.get(currentPresentationDocumentAtom) + const current = projectOf(store) const pages = current.slides.pages.map((slide, index) => index === 0 ? { ...slide, footer: { text: 'Page override', showDate: true, showSlideNumber: false } } : slide) - await act(async () => store.set(currentPresentationDocumentAtom, { + await act(async () => replacePresentationTestProject(presentationStoreOf(store), { ...current, theme: { ...current.theme, footer: { text: 'Theme footer', showDate: false, showSlideNumber: true } }, slides: replacePresentationPages(current.slides, pages), @@ -127,7 +147,7 @@ describe('PresentationWorkbenchPanel', () => { await act(async () => document.querySelector('[data-testid="presentation-insert-footer-use-theme"]')!.click()) await act(async () => document.querySelector('button[type="submit"]')!.click()) - const restored = store.get(currentPresentationDocumentAtom) + const restored = projectOf(store) expect(restored.slides.pages[0]!.footer).toBeUndefined() expect(Object.hasOwn(restored.slides.pages[0]!, 'footer')).toBe(false) expect(restored.theme.footer.text).toBe('Theme footer') @@ -139,17 +159,17 @@ describe('PresentationWorkbenchPanel', () => { it('scales inline text styles and insets when the ribbon changes the slide ratio', async () => { const { host, root, store } = await mountPanel() try { - const current = store.get(currentPresentationDocumentAtom) + const current = projectOf(store) const text = { id: 'ratio-text', type: 'text' as const, text: '标题 English', x: 100, y: 100, width: 400, height: 200, rotation: 0, fontSize: 40, fontFamily: 'Arial', fontWeight: 700 as const, color: '#111111', align: 'left' as const, textRuns: [{ start: 3, end: 10, style: { fontSize: 20, color: '#0088CC' } }], lineSpacing: 48, textInsets: { left: 8, top: 4, right: 8, bottom: 4 }, } - await act(async () => store.set(currentPresentationDocumentAtom, { ...current, slides: replacePresentationPages(current.slides, current.slides.pages.map(slide => ({ ...slide, elements: [text] }))) })) + await act(async () => replacePresentationTestProject(presentationStoreOf(store), { ...current, slides: replacePresentationPages(current.slides, current.slides.pages.map(slide => ({ ...slide, elements: [text] }))) })) await act(async () => host.querySelector('[data-testid="presentation-tab-design"]')!.click()) await act(async () => host.querySelector('[data-testid="presentation-slide-ratio"]')!.click()) await act(async () => document.querySelector('[data-testid="presentation-slide-ratio-standard"]')!.click()) - const resized = store.get(currentPresentationDocumentAtom) + const resized = projectOf(store) expect(resized.pageSize.width).toBe(960) const element = resized.slides.pages[0]!.elements[0]! expect(element).toMatchObject({ width: 300, fontSize: 30, lineSpacing: 36, textInsets: { left: 6, right: 6, top: 3, bottom: 3 } }) @@ -160,23 +180,24 @@ describe('PresentationWorkbenchPanel', () => { it('selects a slide without advancing the document revision', async () => { const { host, root, store } = await mountPanel() - const initial = store.get(currentPresentationDocumentAtom) + const initial = projectOf(store) + const initialRevision = presentationStoreOf(store).getSnapshot().projectMetadata[initial.id]!.revision const target = initial.slides.pages[1]! const preview = host.querySelectorAll('[data-testid="presentation-slide-preview"]')[1]! const button = preview.closest('button')! await act(async () => button.click()) - const selected = store.get(currentPresentationDocumentAtom) + const selected = projectOf(store) expect(selected.slides.selectedPageId).toBe(target.id) - expect(selected.revision).toBe(initial.revision) + expect(presentationStoreOf(store).getSnapshot().projectMetadata[selected.id]!.revision).toBe(initialRevision) await act(async () => root.unmount()) }) it('opens directly into one presentation with three ordinary text boxes', async () => { const { host, root, store } = await mountPanel(false) - const presentation = store.get(currentPresentationDocumentAtom) + const presentation = projectOf(store) expect(presentation.title).toBe('') expect(presentation.slides.pages).toHaveLength(1) @@ -207,7 +228,7 @@ describe('PresentationWorkbenchPanel', () => { await act(async () => close.click()) expect(closeCalls).toBe(1) - expect(store.get(currentPresentationWorkspaceAtom).documents).toHaveLength(1) + expect(presentationStoreOf(store).getSnapshot().projects).toHaveLength(1) await act(async () => root.unmount()) }) @@ -216,7 +237,7 @@ describe('PresentationWorkbenchPanel', () => { let closeCalls = 0 const expansionChanges: boolean[] = [] const { host, root, store } = await mountPanel(false, () => { closeCalls += 1 }, (expanded) => { expansionChanges.push(expanded) }) - const workspace = store.get(currentPresentationWorkspaceAtom) + const projects = presentationStoreOf(store).getSnapshot().projects try { const toggle = host.querySelector('[data-testid="presentation-toggle-expanded"]')! await act(async () => toggle.click()) @@ -232,7 +253,7 @@ describe('PresentationWorkbenchPanel', () => { await act(async () => host.querySelector('[data-testid="presentation-close-panel"]')!.click()) expect(closeCalls).toBe(1) expect(store.get(presentationExpandedAtom)).toBe(false) - expect(store.get(currentPresentationWorkspaceAtom)).toBe(workspace) + expect(presentationStoreOf(store).getSnapshot().projects).toBe(projects) } finally { await act(async () => root.unmount()) } @@ -287,7 +308,7 @@ describe('PresentationWorkbenchPanel', () => { verticalAlign.click() }) - const presentation = store.get(currentPresentationDocumentAtom) + const presentation = projectOf(store) const slide = presentation.slides.pages.find((item) => item.id === presentation.slides.selectedPageId)! const element = slide.elements.at(-1) expect(element?.type).toBe('text') @@ -317,15 +338,15 @@ describe('PresentationWorkbenchPanel', () => { }) await act(async () => host.querySelector('[data-testid="presentation-add-comment"]')!.click()) - let slide = store.get(currentPresentationDocumentAtom).slides.pages[0]! + let slide = projectOf(store).slides.pages[0]! expect(slide.comments?.[0]?.text).toBe('Tighten this claim') const comment = host.querySelector('[data-presentation-comment-id]')! const actions = comment.querySelectorAll('button') await act(async () => actions[0]!.click()) - slide = store.get(currentPresentationDocumentAtom).slides.pages[0]! + slide = projectOf(store).slides.pages[0]! expect(slide.comments?.[0]?.resolved).toBe(true) await act(async () => actions[1]!.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.comments).toEqual([]) + expect(projectOf(store).slides.pages[0]?.comments).toEqual([]) await act(async () => root.unmount()) }) @@ -363,7 +384,7 @@ describe('PresentationWorkbenchPanel', () => { ?.call(notes, 'Remember the customer story.') notes.dispatchEvent(new view.Event('input', { bubbles: true })) }) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.notes).toBe('Remember the customer story.') + expect(projectOf(store).slides.pages[0]?.notes).toBe('Remember the customer story.') const transitions = host.querySelector('[data-testid="presentation-tab-transitions"]')! await act(async () => transitions.click()) @@ -382,7 +403,7 @@ describe('PresentationWorkbenchPanel', () => { const fadeTransition = host.querySelector('[data-testid="presentation-transition-fade"]')! const animationCountBeforeSelection = transitionAnimationCalls.length await act(async () => fadeTransition.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition).toEqual({ + expect(projectOf(store).slides.pages[0]?.transition).toEqual({ effect: 'fade', durationMs: 1_000, }) @@ -398,7 +419,7 @@ describe('PresentationWorkbenchPanel', () => { Simulate.change(duration) }) expect(duration.value).toBe('') - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition?.durationMs).toBe(1_000) + expect(projectOf(store).slides.pages[0]?.transition?.durationMs).toBe(1_000) await act(async () => { Simulate.blur(duration) duration.blur() @@ -410,7 +431,7 @@ describe('PresentationWorkbenchPanel', () => { const view = duration.ownerDocument.defaultView! Object.getOwnPropertyDescriptor(view.HTMLInputElement.prototype, 'value')?.set?.call(duration, '') Simulate.change(duration) - store.set(currentPresentationDocumentAtom, (current) => ({ + replacePresentationTestProject(presentationStoreOf(store), (current) => ({ ...current, slides: replacePresentationPages(current.slides, current.slides.pages.map((slide) => slide.id === current.slides.selectedPageId ? { ...slide, transition: { ...slide.transition, durationMs: 1_800 } } @@ -423,7 +444,7 @@ describe('PresentationWorkbenchPanel', () => { Simulate.blur(duration) }) expect(duration.ownerDocument.activeElement).not.toBe(duration) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition?.durationMs).toBe(1_800) + expect(projectOf(store).slides.pages[0]?.transition?.durationMs).toBe(1_800) expect(duration.value).toBe('1.8') await act(async () => { @@ -432,7 +453,7 @@ describe('PresentationWorkbenchPanel', () => { Object.getOwnPropertyDescriptor(view.HTMLInputElement.prototype, 'value')?.set?.call(duration, '0.01') Simulate.change(duration) }) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition?.durationMs).toBe(100) + expect(projectOf(store).slides.pages[0]?.transition?.durationMs).toBe(100) await act(async () => { Simulate.blur(duration) duration.blur() @@ -445,7 +466,7 @@ describe('PresentationWorkbenchPanel', () => { Object.getOwnPropertyDescriptor(view.HTMLInputElement.prototype, 'value')?.set?.call(duration, '30') Simulate.change(duration) }) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition?.durationMs).toBe(20_000) + expect(projectOf(store).slides.pages[0]?.transition?.durationMs).toBe(20_000) await act(async () => { Simulate.blur(duration) duration.blur() @@ -458,7 +479,7 @@ describe('PresentationWorkbenchPanel', () => { Object.getOwnPropertyDescriptor(view.HTMLInputElement.prototype, 'value')?.set?.call(duration, '1.2') Simulate.change(duration) }) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition?.durationMs).toBe(1_200) + expect(projectOf(store).slides.pages[0]?.transition?.durationMs).toBe(1_200) await act(async () => { Simulate.blur(duration) duration.blur() @@ -469,11 +490,11 @@ describe('PresentationWorkbenchPanel', () => { await act(async () => options.click()) const throughBlack = document.querySelector('[data-testid="presentation-transition-through-black"]')! await act(async () => throughBlack.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition?.throughBlack).toBe(true) + expect(projectOf(store).slides.pages[0]?.transition?.throughBlack).toBe(true) const applyToAll = host.querySelector('[data-testid="presentation-transition-apply-all"]')! await act(async () => applyToAll.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages.every((slide) => ( + expect(projectOf(store).slides.pages.every((slide) => ( slide.transition?.effect === 'fade' && slide.transition.durationMs === 1_200 && slide.transition.throughBlack === true @@ -485,7 +506,7 @@ describe('PresentationWorkbenchPanel', () => { expect(document.querySelector('[data-testid="presentation-transition-gallery-reveal"]')).not.toBeNull() const cube = document.querySelector('[data-testid="presentation-transition-gallery-cube"]')! await act(async () => cube.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition).toEqual({ + expect(projectOf(store).slides.pages[0]?.transition).toEqual({ effect: 'cube', durationMs: 1_200, direction: 'left', @@ -500,7 +521,7 @@ describe('PresentationWorkbenchPanel', () => { await act(async () => options.click()) const fromTop = document.querySelector('[data-testid="presentation-transition-direction-up"]')! await act(async () => fromTop.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.transition?.direction).toBe('up') + expect(projectOf(store).slides.pages[0]?.transition?.direction).toBe('up') const home = host.querySelector('[data-testid="presentation-tab-home"]')! await act(async () => home.click()) @@ -513,7 +534,7 @@ describe('PresentationWorkbenchPanel', () => { const fadeAnimation = host.querySelector('[data-testid="presentation-animation-fade"]')! await act(async () => fadeAnimation.click()) - const presentation = store.get(currentPresentationDocumentAtom) + const presentation = projectOf(store) const selectedSlide = presentation.slides.pages.find((slide) => slide.id === presentation.slides.selectedPageId)! expect(selectedSlide.elements.at(-1)?.animation).toBe('fade') expect(host.querySelector('[data-testid="presentation-animation-player"]')).not.toBeNull() @@ -524,14 +545,14 @@ describe('PresentationWorkbenchPanel', () => { expect(checkerboard.disabled).toBe(false) expect(dissolve.disabled).toBe(false) await act(async () => checkerboard.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.elements.at(-1)?.animation).toBe('checkerboard') + expect(projectOf(store).slides.pages[0]?.elements.at(-1)?.animation).toBe('checkerboard') expect(host.querySelectorAll('[data-animation-part*="-checker-"]')).toHaveLength(48) const textColor = host.querySelector('[data-testid="presentation-animation-textColor"]')! await act(async () => textColor.click()) const purpleTextAnimation = document.querySelector('button[aria-label="文字颜色 #8B7CFF"]')! await act(async () => purpleTextAnimation.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.elements.at(-1)).toMatchObject({ + expect(projectOf(store).slides.pages[0]?.elements.at(-1)).toMatchObject({ animation: 'textColor', animationColor: '#8B7CFF', }) @@ -548,7 +569,7 @@ describe('PresentationWorkbenchPanel', () => { const trigger = host.querySelector('[data-testid="presentation-animation-trigger"]')! await act(async () => trigger.click()) await act(async () => document.querySelector('[data-testid="presentation-animation-option-elementClick"]')!.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.elements.at(-1)).toMatchObject({ + expect(projectOf(store).slides.pages[0]?.elements.at(-1)).toMatchObject({ animationDelay: 1_300, animationStart: 'withPrevious', animationTrigger: 'elementClick', @@ -556,7 +577,7 @@ describe('PresentationWorkbenchPanel', () => { const applyAnimationToAll = host.querySelector('[data-testid="presentation-animation-apply-all"]')! await act(async () => applyAnimationToAll.click()) - expect(store.get(currentPresentationDocumentAtom).slides.pages[0]?.elements.every((element) => ( + expect(projectOf(store).slides.pages[0]?.elements.every((element) => ( element.animation === 'textColor' && element.animationDelay === 1_300 && element.animationStart === 'withPrevious' @@ -586,14 +607,14 @@ describe('PresentationWorkbenchPanel', () => { it('applies and previews one animation for an entire grouped card', async () => { const { host, root, store } = await mountPanel() - const initial = store.get(currentPresentationDocumentAtom) + const initial = projectOf(store) const overview = initial.slides.pages[1]! const cardGroupId = overview.elements.find((element) => element.groupId)?.groupId if (!cardGroupId) throw new Error('Expected a grouped test card') const cardElements = overview.elements.filter((element) => element.groupId === cardGroupId) await act(async () => { - store.set(currentPresentationDocumentAtom, { + replacePresentationTestProject(presentationStoreOf(store), { ...initial, slides: replacePresentationPages(initial.slides, initial.slides.pages.map((slide) => slide.id === overview.id ? { ...slide, elements: cardElements } @@ -607,7 +628,7 @@ describe('PresentationWorkbenchPanel', () => { expect(host.querySelector('[data-testid="presentation-animation-textColor"]')?.disabled).toBe(false) await act(async () => host.querySelector('[data-testid="presentation-animation-fade"]')!.click()) - const current = store.get(currentPresentationDocumentAtom) + const current = projectOf(store) const currentSlide = current.slides.pages.find((slide) => slide.id === overview.id)! expect(currentSlide.elements[0]?.animation).toBe('fade') expect(currentSlide.elements.slice(1).every((element) => element.animation === undefined)).toBe(true) @@ -623,11 +644,11 @@ describe('PresentationWorkbenchPanel', () => { it('advances slide-click animations before moving to the next slide in slideshow mode', async () => { const { host, root, store } = await mountPanel() - const current = store.get(currentPresentationDocumentAtom) + const current = projectOf(store) const firstSlide = current.slides.pages[0]! const animatedElement = firstSlide.elements.find((element) => element.type === 'text')! await act(async () => { - store.set(currentPresentationDocumentAtom, { + replacePresentationTestProject(presentationStoreOf(store), { ...current, slides: replacePresentationPages(current.slides, current.slides.pages.map((slide) => slide.id === firstSlide.id ? { @@ -685,11 +706,11 @@ describe('PresentationWorkbenchPanel', () => { it('runs an element-click animation from its target area in slideshow mode', async () => { const { host, root, store } = await mountPanel() - const current = store.get(currentPresentationDocumentAtom) + const current = projectOf(store) const firstSlide = current.slides.pages[0]! const animatedElement = firstSlide.elements.find((element) => element.type === 'text')! await act(async () => { - store.set(currentPresentationDocumentAtom, { + replacePresentationTestProject(presentationStoreOf(store), { ...current, slides: replacePresentationPages(current.slides, current.slides.pages.map((slide) => slide.id === firstSlide.id ? { @@ -738,7 +759,7 @@ describe('PresentationWorkbenchPanel', () => { if (!host.querySelector('[data-testid="presentation-format-painter"]')?.disabled) break await act(async () => new Promise((resolve) => setTimeout(resolve, 10))) } - const sourceDocument = store.get(currentPresentationDocumentAtom) + const sourceDocument = projectOf(store) const source = sourceDocument.slides.pages.find((slide) => slide.id === sourceDocument.slides.selectedPageId)!.elements.at(-1) expect(source).toMatchObject({ type: 'text', fontWeight: 700 }) const formatPainter = host.querySelector('[data-testid="presentation-format-painter"]')! @@ -748,14 +769,14 @@ describe('PresentationWorkbenchPanel', () => { await addTextThroughMenu() for (let attempt = 0; attempt < 10; attempt += 1) { - const current = store.get(currentPresentationDocumentAtom) + const current = projectOf(store) const selectedSlide = current.slides.pages.find((item) => item.id === current.slides.selectedPageId)! const target = selectedSlide.elements.at(-1) if (target?.type === 'text' && target.fontWeight === 700) break await act(async () => new Promise((resolve) => setTimeout(resolve, 10))) } - let presentation = store.get(currentPresentationDocumentAtom) + let presentation = projectOf(store) let slide = presentation.slides.pages.find((item) => item.id === presentation.slides.selectedPageId)! const painted = slide.elements.at(-1) expect(painted?.type).toBe('text') @@ -763,7 +784,7 @@ describe('PresentationWorkbenchPanel', () => { const clearFormat = host.querySelector('[data-testid="presentation-clear-format"]')! await act(async () => clearFormat.click()) - presentation = store.get(currentPresentationDocumentAtom) + presentation = projectOf(store) slide = presentation.slides.pages.find((item) => item.id === presentation.slides.selectedPageId)! const cleared = slide.elements.at(-1) expect(cleared?.type).toBe('text') @@ -799,23 +820,23 @@ describe('PresentationWorkbenchPanel', () => { expect(documentHeader.contains(closePanel)).toBe(false) expect(appHeader.contains(expandPanel)).toBe(true) expect(appHeader.contains(closePanel)).toBe(true) - expect(store.get(currentPresentationWorkspaceAtom).documents).toHaveLength(1) + expect(presentationStoreOf(store).getSnapshot().projects).toHaveLength(1) - const firstDocumentId = store.get(currentPresentationDocumentAtom).id + const firstDocumentId = projectOf(store).id await act(async () => newDocument.click()) - expect(store.get(currentPresentationWorkspaceAtom).documents).toHaveLength(2) - expect(store.get(currentPresentationDocumentAtom).id).not.toBe(firstDocumentId) - expect(store.get(currentPresentationDocumentAtom).slides.pages).toHaveLength(1) + expect(presentationStoreOf(store).getSnapshot().projects).toHaveLength(2) + expect(projectOf(store).id).not.toBe(firstDocumentId) + expect(projectOf(store).slides.pages).toHaveLength(1) expect(host.querySelectorAll('[data-testid="presentation-document-tab"]')).toHaveLength(2) const tabs = host.querySelectorAll('[data-testid="presentation-document-tab"]') await act(async () => tabs[0]!.click()) - expect(store.get(currentPresentationDocumentAtom).id).toBe(firstDocumentId) + expect(projectOf(store).id).toBe(firstDocumentId) const closeButtons = host.querySelectorAll('[data-testid="presentation-close-document"]') await act(async () => closeButtons[0]!.click()) - expect(store.get(currentPresentationWorkspaceAtom).documents).toHaveLength(1) - expect(store.get(currentPresentationDocumentAtom).id).not.toBe(firstDocumentId) + expect(presentationStoreOf(store).getSnapshot().projects).toHaveLength(1) + expect(projectOf(store).id).not.toBe(firstDocumentId) await act(async () => root.unmount()) }) @@ -842,7 +863,7 @@ describe('PresentationWorkbenchPanel', () => { }) expect(document.querySelector('[role="tooltip"]')?.textContent).toBe('心形') await act(async () => heart.click()) - const presentation = store.get(currentPresentationDocumentAtom) + const presentation = projectOf(store) const slide = presentation.slides.pages.find((item) => item.id === presentation.slides.selectedPageId)! const inserted = slide.elements.at(-1) expect(inserted?.type).toBe('heart') diff --git a/desktop/apps/electron/src/renderer/components/app/__tests__/SessionResourcePanel.test.tsx b/desktop/apps/electron/src/renderer/components/app/__tests__/SessionResourcePanel.test.tsx index 4c83338b..2ccc973c 100644 --- a/desktop/apps/electron/src/renderer/components/app/__tests__/SessionResourcePanel.test.tsx +++ b/desktop/apps/electron/src/renderer/components/app/__tests__/SessionResourcePanel.test.tsx @@ -62,6 +62,7 @@ const excelHostApi: ElectronAPI['excelHost'] = { ready: true, crashed: false, dirty: false, + documentCount: 0, } }, openWorkbook: async (sessionId, _config, request) => { @@ -212,7 +213,7 @@ function startPowerPointTool( store: ReturnType, sessionId: string, toolUseId: string, - toolName = 'edit_ppt_page', + toolName = 'ppt_edit_page', ): void { startBrowserTool(store, sessionId, toolUseId, toolName, { page_id: 'page-1', @@ -513,7 +514,7 @@ describe('SessionResourcePanel', () => { store.set(activeSessionIdAtom, sessionId) store.set(setSessionWorkbenchSurfaceAtom, SessionWorkbenchSurface.Excel) store.set(excelHostSnapshotAtom, { - sessions: [{ sessionId, targetId: 'excel-debug-target', webContentsId: 50, ready: true, crashed: false, dirty: false }], + sessions: [{ sessionId, targetId: 'excel-debug-target', webContentsId: 50, ready: true, crashed: false, dirty: false, documentCount: 1 }], }) const roundsExtension: SessionWorkbenchExtension = { ...toolExtension, @@ -683,7 +684,7 @@ describe('SessionResourcePanel', () => { } }) - it('shows PPT as active without a background marker until a presentation is created', async () => { + it('distinguishes an empty PPT target from a created presentation', async () => { const store = createStore() const sessionId = 'session-ppt-lifecycle' store.set(activeSessionIdAtom, sessionId) @@ -707,6 +708,25 @@ describe('SessionResourcePanel', () => { webContentsId: 42, loading: false, crashed: false, + documentCount: 0, + }], + }) + }) + + expect(presentation.querySelector( + '[data-testid="session-workbench-presentation-status-indicator"]', + )).toBeNull() + expect(presentation.getAttribute('aria-label')).toBe('PPT') + + await act(async () => { + store.set(setEmbeddedPowerPointSnapshotAtom, { + sessions: [{ + sessionId, + targetId: 'ppt-target', + webContentsId: 42, + loading: false, + crashed: false, + documentCount: 1, }], }) }) @@ -723,6 +743,22 @@ describe('SessionResourcePanel', () => { '[data-testid="session-workbench-presentation-status-indicator"]', )?.dataset.state).toBe('background-open') + await act(async () => { + store.set(setEmbeddedPowerPointSnapshotAtom, { + sessions: [{ + sessionId, + targetId: 'ppt-target', + webContentsId: 42, + loading: false, + crashed: false, + documentCount: 0, + }], + }) + }) + expect(presentation.querySelector( + '[data-testid="session-workbench-presentation-status-indicator"]', + )).toBeNull() + await act(async () => presentation.click()) await act(async () => { store.set(setEmbeddedPowerPointSnapshotAtom, { sessions: [] }) @@ -752,6 +788,7 @@ describe('SessionResourcePanel', () => { webContentsId: 43, loading: false, crashed: false, + documentCount: null, }], }) await Promise.resolve() @@ -774,10 +811,11 @@ describe('SessionResourcePanel', () => { sessions: [{ sessionId, targetId: 'existing-ppt-target', - webContentsId: 44, - loading: false, - crashed: false, - }], + webContentsId: 44, + loading: false, + crashed: false, + documentCount: null, + }], }) const { host, root } = await mountPanel(store) @@ -813,6 +851,7 @@ describe('SessionResourcePanel', () => { ready: true, crashed: false, dirty: false, + documentCount: 1, }], }) await Promise.resolve() @@ -829,6 +868,34 @@ describe('SessionResourcePanel', () => { await act(async () => root.unmount()) }) + it('lets the native Excel launch surface own the only header while the workspace is empty', async () => { + const store = createStore() + const sessionId = 'session-excel-empty' + store.set(activeSessionIdAtom, sessionId) + store.set(setSessionWorkbenchSurfaceAtom, SessionWorkbenchSurface.Excel) + const { host, root } = await mountPanel(store) + + await act(async () => { + store.set(excelHostSnapshotAtom, { sessions: [{ + sessionId, + targetId: 'excel-target-empty', + webContentsId: 50, + ready: true, + crashed: false, + dirty: false, + documentCount: 0, + }] }) + await Promise.resolve() + }) + + expect(host.querySelector('[data-testid="excel-native-canvas"]')).not.toBeNull() + expect(host.querySelector('[data-testid="excel-app-header"]')).toBeNull() + expect(host.querySelector('[data-testid="excel-toggle-expanded"]')).toBeNull() + expect(host.querySelector('[data-testid="session-workbench-excel-status-indicator"]')).toBeNull() + + await act(async () => root.unmount()) + }) + it('opens a routed workbook in Excel and replaces only the target startup workbook', async () => { const store = createStore() const sessionId = 'session-routed-workbook' @@ -864,7 +931,7 @@ describe('SessionResourcePanel', () => { store.set(activeSessionIdAtom, sessionId) store.set(setSessionWorkbenchSurfaceAtom, SessionWorkbenchSurface.Excel) store.set(setExcelHostSnapshotAtom, { sessions: [{ - sessionId, targetId: 'excel-retained', webContentsId: 50, ready: true, crashed: false, dirty: true, + sessionId, targetId: 'excel-retained', webContentsId: 50, ready: true, crashed: false, dirty: true, documentCount: 1, }] }) store.set(excelExpandedAtom, true) const { host, root } = await mountPanel(store) @@ -888,7 +955,7 @@ describe('SessionResourcePanel', () => { it('closes Excel from its header without recreating its target on dirty-state updates', async () => { const store = createStore() const sessionId = 'session-excel-panel-close' - const session = { sessionId, targetId: 'excel-panel', webContentsId: 50, ready: true, crashed: false, dirty: false } + const session = { sessionId, targetId: 'excel-panel', webContentsId: 50, ready: true, crashed: false, dirty: false, documentCount: 1 } store.set(activeSessionIdAtom, sessionId) store.set(setSessionWorkbenchSurfaceAtom, SessionWorkbenchSurface.Excel) store.set(setExcelHostSnapshotAtom, { sessions: [session] }) @@ -919,6 +986,7 @@ describe('SessionResourcePanel', () => { ready: true, crashed: false, dirty: false, + documentCount: 1, }], }) const { host, root } = await mountPanel(store) @@ -2194,6 +2262,7 @@ describe('SessionResourcePanel', () => { ready: true, crashed: false, dirty: false, + documentCount: 1, }], }) const { host, root } = await mountPanel(store) diff --git a/desktop/apps/electron/src/renderer/components/word/SessionWordEditor.tsx b/desktop/apps/electron/src/renderer/components/word/SessionWordEditor.tsx index 27814d54..8f814d42 100644 --- a/desktop/apps/electron/src/renderer/components/word/SessionWordEditor.tsx +++ b/desktop/apps/electron/src/renderer/components/word/SessionWordEditor.tsx @@ -17,7 +17,7 @@ import { type WordWorkspacePersister, } from '@/lib/wordPersistence' import { Icons } from '@/components/amphi/Icons' -import { WordLaunchEmptyState } from './WordLaunchEmptyState' +import { OfficeLaunchEmptyState } from '@/components/app/OfficeLaunchEmptyState' import { OfficeAppHeader } from '@/components/app/OfficeWorkbenchChrome' import { rlog } from '@/lib/logger' import { loadOfficeRecovery } from '@/lib/office/officePersistence' @@ -70,6 +70,7 @@ export interface SessionWordEditorProps { onDocumentCountChange?: (sessionId: string, count: number) => void onOpenFileError?: (name: string, cause: unknown) => void onOpenFileRequestHandled?: (requestId: string, error?: string) => void + onOpenDocument?: () => unknown | Promise onFlushHandlerChange?: (flush: WordWorkspaceFlush | null) => void onStateChange?: (state: { documentCount: number; persistenceStatus: WordPersistenceStatus }) => void onToggleExpanded?: () => void @@ -87,6 +88,7 @@ export function SessionWordEditor({ onDocumentCountChange = noop, onOpenFileError = noop, onOpenFileRequestHandled = noop, + onOpenDocument = noop, onFlushHandlerChange = noop, onStateChange = noop, onToggleExpanded = noop, @@ -104,6 +106,7 @@ export function SessionWordEditor({ onDocumentCountChange={onDocumentCountChange} onOpenFileError={onOpenFileError} onOpenFileRequestHandled={onOpenFileRequestHandled} + onOpenDocument={onOpenDocument} onFlushHandlerChange={onFlushHandlerChange} onStateChange={onStateChange} onToggleExpanded={onToggleExpanded} @@ -122,6 +125,7 @@ function SessionWordEditorInstance({ onDocumentCountChange, onOpenFileError, onOpenFileRequestHandled, + onOpenDocument, onFlushHandlerChange, onStateChange, onToggleExpanded, @@ -353,6 +357,7 @@ function SessionWordEditorInstance({ }).catch((error) => rlog.warn('[word] close failed', error)) } : undefined} onSaveRequested={flushWorkspace} + onOpenDocument={onOpenDocument} onEditorFlushHandlerChange={setEditorFlush} onToggleExpanded={onToggleExpanded} persistenceStatus={persistenceStatus} @@ -362,10 +367,11 @@ function SessionWordEditorInstance({ /> } -function WordSessionSurface({ expanded, onClose, onEditorFlushHandlerChange, onSaveRequested, onToggleExpanded, openingFileName, persistenceStatus, showExpandControl, store }: { +function WordSessionSurface({ expanded, onClose, onEditorFlushHandlerChange, onOpenDocument, onSaveRequested, onToggleExpanded, openingFileName, persistenceStatus, showExpandControl, store }: { expanded: boolean onClose?: () => void onEditorFlushHandlerChange: (flush: WordWorkspaceFlush | null) => void + onOpenDocument: () => unknown | Promise onSaveRequested: () => Promise onToggleExpanded: () => void openingFileName: string | null @@ -377,7 +383,7 @@ function WordSessionSurface({ expanded, onClose, onEditorFlushHandlerChange, onS if (workspace.documents.length === 0) { return openingFileName ? - : { void store.dispatch({ type: 'document.create' }) }} /> + : store.dispatch({ type: 'document.create' })} onOpen={onOpenDocument} /> } return ( diff --git a/desktop/apps/electron/src/renderer/components/word/WordLaunchEmptyState.tsx b/desktop/apps/electron/src/renderer/components/word/WordLaunchEmptyState.tsx deleted file mode 100644 index 0ee58169..00000000 --- a/desktop/apps/electron/src/renderer/components/word/WordLaunchEmptyState.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { useTranslation } from 'react-i18next' -import { Icons } from '@/components/amphi/Icons' -import { OfficeAppHeader } from '@/components/app/OfficeWorkbenchChrome' - -/** Shared launch screen before a Session has an explicitly opened Word document. */ -export function WordLaunchEmptyState({ creating = false, failed = false, onCreate }: { - creating?: boolean - failed?: boolean - onCreate: () => void -}) { - const { t } = useTranslation() - return ( -
- -
-
-
- {Icons.wordDocument(20)} -
-
{t('word.emptyTitle')}
-
{t('word.emptyDescription')}
- - {failed ?
{t('word.hostFailed')}
: null} -
-
-
- ) -} diff --git a/desktop/apps/electron/src/renderer/components/word/__tests__/SessionWordEditor.test.tsx b/desktop/apps/electron/src/renderer/components/word/__tests__/SessionWordEditor.test.tsx index b3b5c16c..aa41ff1c 100644 --- a/desktop/apps/electron/src/renderer/components/word/__tests__/SessionWordEditor.test.tsx +++ b/desktop/apps/electron/src/renderer/components/word/__tests__/SessionWordEditor.test.tsx @@ -10,6 +10,7 @@ GlobalRegistrator.register() const { act } = await import('react') const { createRoot } = await import('react-dom/client') +const { i18n } = await import('@/lib/i18n') const { installApiStub } = await import('@/lib/apiStub') installApiStub() const { SessionWordEditor } = await import('../SessionWordEditor') @@ -118,16 +119,20 @@ describe('SessionWordEditor', () => { const host = document.createElement('div') document.body.appendChild(host) const root = createRoot(host) + const onOpenDocument = mock(async () => undefined) await act(async () => { - root.render() + root.render() await new Promise((resolve) => setTimeout(resolve, 0)) }) expect(host.querySelector('[data-testid="word-launch-empty-state"]')).not.toBeNull() + expect(host.querySelector('[data-testid="word-open-file"]')).not.toBeNull() expect(await window.__bridgicWord?.dispatch({ type: 'workspace.get' })).toMatchObject({ ok: true, state: { documents: [] }, }) + await act(async () => host.querySelector('[data-testid="word-open-file"]')!.click()) + expect(onOpenDocument).toHaveBeenCalledTimes(1) await act(async () => { host.querySelector('[data-testid="word-create-document"]')?.click() @@ -284,7 +289,7 @@ describe('SessionWordEditor', () => { await waitForElement(host, '[data-testid="word-document-header"] [role="alert"]') const before = attempts const writes = save.mock.calls.length - const retry = Array.from(host.querySelectorAll('button')).find((button) => button.textContent === '重试')! + const retry = Array.from(host.querySelectorAll('button')).find((button) => button.textContent === i18n.t('word.retry'))! expect(retry).toBeDefined() // A still-failing retry must remain visibly failed. await act(async () => { retry.click(); await new Promise((resolve) => setTimeout(resolve, 10)) }) diff --git a/desktop/apps/electron/src/renderer/excel/ExcelHostApp.tsx b/desktop/apps/electron/src/renderer/excel/ExcelHostApp.tsx index 5be98483..6284dfa1 100644 --- a/desktop/apps/electron/src/renderer/excel/ExcelHostApp.tsx +++ b/desktop/apps/electron/src/renderer/excel/ExcelHostApp.tsx @@ -265,7 +265,10 @@ export function ExcelHostApp() { useEffect(() => { const hasUnsaved = tabs.some((tab) => tab.dirty) - if (recoveryLoaded) void api.setDirty(hasUnsaved).catch((cause) => setError(errorMessage(cause))) + if (recoveryLoaded) { + void api.reportState({ documentCount: tabs.length, dirty: hasUnsaved }) + .catch((cause) => setError(errorMessage(cause))) + } }, [api, recoveryLoaded, tabs]) useEffect(() => { @@ -369,18 +372,16 @@ export function ExcelHostApp() { ) }, [config, copy.saveConflict, flushActiveEditor, updateTab, workspace]) - const addBlankTab = () => { - void executeWorkspaceOperation('document.create', null, async (context) => { - await flushActiveEditor(context.assertCurrent) - await persistRef.current(context) - setFormulaDialog(null) - setInsertDialog(null) - const tab = newWorkbookTab(config, nextWorkbookOrdinal.current) - nextWorkbookOrdinal.current += 1 - workspace.replace([...workspace.getState().tabs, tab], tab.tabId) - setError(null) - }) - } + const addBlankTab = () => executeWorkspaceOperation('document.create', null, async (context) => { + await flushActiveEditor(context.assertCurrent) + await persistRef.current(context) + setFormulaDialog(null) + setInsertDialog(null) + const tab = newWorkbookTab(config, nextWorkbookOrdinal.current) + nextWorkbookOrdinal.current += 1 + workspace.replace([...workspace.getState().tabs, tab], tab.tabId) + setError(null) + }) const openWorkbook = () => executeWorkspaceOperation('document.open', null, async (context) => { setFormulaDialog(null) @@ -710,7 +711,7 @@ export function ExcelHostApp() { }, [runEditorOperation]) if (!activeTab && recoveryLoaded && !recoveryFailure && !error && busy === null && pendingWorkbookOpenTickets.length === 0) { - return { addBlankTab() }} onOpen={() => void openWorkbook()} /> + return } return ( diff --git a/desktop/apps/electron/src/renderer/excel/__tests__/UniverSheetEditor.test.tsx b/desktop/apps/electron/src/renderer/excel/__tests__/UniverSheetEditor.test.tsx index 94622115..5b7e3dca 100644 --- a/desktop/apps/electron/src/renderer/excel/__tests__/UniverSheetEditor.test.tsx +++ b/desktop/apps/electron/src/renderer/excel/__tests__/UniverSheetEditor.test.tsx @@ -1,7 +1,7 @@ import { afterAll, afterEach, describe, expect, it, mock, spyOn } from 'bun:test' import { GlobalRegistrator } from '@happy-dom/global-registrator' import { DrawingTypeEnum, LocaleType, type IWorkbookData } from '@univerjs/core' -import type { ExcelHostConfig, ExcelHostPreloadAPI, ExcelWorkbookOpenTicket } from '../../../shared/types' +import type { ExcelHostConfig, ExcelHostPreloadAPI, ExcelHostRendererState, ExcelWorkbookOpenTicket } from '../../../shared/types' import type { ExcelUniverAdapter, SheetEditorHandle } from '../excelUniverAdapter' GlobalRegistrator.register({ url: 'http://localhost/' }) @@ -58,6 +58,7 @@ async function mountHost(initialWorkbook: 'empty' | 'blank', recovery: string | window.history.replaceState(null, '', `http://localhost/excel.html?sessionId=session&initialWorkbook=${initialWorkbook}`) let deliver!: (ticket: ExcelWorkbookOpenTicket) => void const reads: string[] = [] + const stateReports: ExcelHostRendererState[] = [] let checkpoint: string | null = recovery const api: ExcelHostPreloadAPI = { open: async () => ({ canceled: true }), @@ -71,7 +72,7 @@ async function mountHost(initialWorkbook: 'empty' | 'blank', recovery: string | save: async () => ({ ok: false, reason: 'canceled' }), saveAs: async () => ({ ok: false, reason: 'canceled' }), requestClose: async () => undefined, - setDirty: async () => undefined, + reportState: async (state) => { stateReports.push(state) }, getRecoveryState: async () => recovery, setRecoveryState: async (value) => { checkpoint = value }, onConfigChanged: () => () => undefined, @@ -83,7 +84,7 @@ async function mountHost(initialWorkbook: 'empty' | 'blank', recovery: string | const root = createRoot(host) await act(async () => root.render()) return { - api, host, reads, + api, host, reads, stateReports, recovery: () => checkpoint === null ? null : JSON.parse(checkpoint) as { tabs: Array<{ tabId: string; documentId: string | null; snapshot: IWorkbookData; mtimeMs: number | null; dirty: boolean }>; activeTabId: string }, open: async (requestId: string) => { await act(async () => deliver({ requestId, replaceInitialBlank: true })) }, close: async () => { @@ -96,6 +97,18 @@ async function mountHost(initialWorkbook: 'empty' | 'blank', recovery: string | } describe('Excel routed workbook imports', () => { + it('reports the authoritative empty and populated workbook inventory to the shell', async () => { + const app = await mountHost('empty') + try { + await waitFor(() => app.stateReports.at(-1)?.documentCount === 0) + await act(async () => app.host.querySelector('[data-testid="excel-create-workbook"]')!.click()) + await waitFor(() => app.stateReports.at(-1)?.documentCount === 1) + expect(app.stateReports.at(-1)).toEqual({ documentCount: 1, dirty: true }) + } finally { + await app.close() + } + }) + it('loads without a blank workbook, imports repeated requests once and reactivates edited tabs by file identity', async () => { let finish!: (snapshot: IWorkbookData) => void const importing = spyOn(workbookImport, 'importExcelWorkbook') diff --git a/desktop/apps/electron/src/renderer/excel/main.tsx b/desktop/apps/electron/src/renderer/excel/main.tsx index 9373f0fe..0ec6b642 100644 --- a/desktop/apps/electron/src/renderer/excel/main.tsx +++ b/desktop/apps/electron/src/renderer/excel/main.tsx @@ -11,7 +11,7 @@ if (!window.excelHostApi) { save: async () => canceled, saveAs: async () => canceled, requestClose: async () => undefined, - setDirty: async () => undefined, + reportState: async () => undefined, getRecoveryState: async () => null, setRecoveryState: async () => undefined, onConfigChanged: () => () => undefined, diff --git a/desktop/apps/electron/src/renderer/hooks/__tests__/useEmbeddedPowerPointBridge.test.tsx b/desktop/apps/electron/src/renderer/hooks/__tests__/useEmbeddedPowerPointBridge.test.tsx index 30f40600..ebd4cf24 100644 --- a/desktop/apps/electron/src/renderer/hooks/__tests__/useEmbeddedPowerPointBridge.test.tsx +++ b/desktop/apps/electron/src/renderer/hooks/__tests__/useEmbeddedPowerPointBridge.test.tsx @@ -32,6 +32,7 @@ function snapshot(sessionId: string): EmbeddedPowerPointSnapshot { webContentsId: 9, loading: false, crashed: false, + documentCount: null, }], } } diff --git a/desktop/apps/electron/src/renderer/index.css b/desktop/apps/electron/src/renderer/index.css index adbccb13..fa329847 100644 --- a/desktop/apps/electron/src/renderer/index.css +++ b/desktop/apps/electron/src/renderer/index.css @@ -380,6 +380,7 @@ html[data-platform="win32"] .auto-hide-scrollbar::-webkit-scrollbar-button { html, body, #root, + #excel-root, #word-root { height: 100%; margin: 0; diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/officeSurfaceStatus.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/officeSurfaceStatus.test.ts index 78caa8ff..0573a19b 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/officeSurfaceStatus.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/officeSurfaceStatus.test.ts @@ -15,9 +15,11 @@ const input = { } const ppt = { sessionId: 'session-a', targetId: 'ppt-a', webContentsId: 1, loading: false, crashed: false, + documentCount: null, } const excel = { sessionId: 'session-a', targetId: 'excel-a', webContentsId: 2, ready: true, crashed: false, dirty: false, + documentCount: null, } const word = { @@ -56,13 +58,24 @@ describe('Office shell status compatibility contract', () => { expect(hasOfficeBackgroundContent(crashed)).toBe(true) }) - it('retains native background markers without fabricating PPT or Excel document counts', () => { + it('does not treat an empty or pending PPT or Excel target as background content', () => { const statuses = projectOfficeSurfaceStatuses({ ...input, powerPointSession: ppt, excelSession: excel }) - for (const kind of ['presentation', 'excel'] as const) { - expect(hasOfficeBackgroundContent(statuses[kind])).toBe(true) - expect(statuses[kind].documentCount).toBeNull() - expect(statuses[kind].runtimeState).toBe('ready') - } + expect(statuses.presentation.documentInventory).toBe('pending') + expect(statuses.presentation.documentCount).toBeNull() + expect(hasOfficeBackgroundContent(statuses.presentation)).toBe(false) + const empty = projectOfficeSurfaceStatuses({ ...input, powerPointSession: { ...ppt, documentCount: 0 } }).presentation + expect(empty.documentInventory).toBe('ready') + expect(hasOfficeBackgroundContent(empty)).toBe(false) + const populated = projectOfficeSurfaceStatuses({ ...input, powerPointSession: { ...ppt, documentCount: 1 } }).presentation + expect(hasOfficeBackgroundContent(populated)).toBe(true) + + expect(hasOfficeBackgroundContent(statuses.excel)).toBe(false) + expect(statuses.excel.documentCount).toBeNull() + expect(statuses.excel.documentInventory).toBe('pending') + const emptyExcel = projectOfficeSurfaceStatuses({ ...input, excelSession: { ...excel, documentCount: 0 } }).excel + expect(hasOfficeBackgroundContent(emptyExcel)).toBe(false) + const populatedExcel = projectOfficeSurfaceStatuses({ ...input, excelSession: { ...excel, documentCount: 1 } }).excel + expect(hasOfficeBackgroundContent(populatedExcel)).toBe(true) }) it('rejects native inventories owned by a different Session', () => { @@ -93,8 +106,8 @@ describe('Office shell status compatibility contract', () => { it('keeps failed native targets discoverable and gives crash state priority over loading', () => { const statuses = projectOfficeSurfaceStatuses({ ...input, - powerPointSession: { ...ppt, loading: true, crashed: true }, - excelSession: { ...excel, crashed: true }, + powerPointSession: { ...ppt, loading: true, crashed: true, documentCount: 1 }, + excelSession: { ...excel, crashed: true, documentCount: 1 }, }) for (const kind of ['presentation', 'excel'] as const) { expect(statuses[kind].runtimeState).toBe('crashed') diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/powerPointProtocol.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/powerPointProtocol.test.ts index 7a56ef71..99eb68f9 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/powerPointProtocol.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/powerPointProtocol.test.ts @@ -1,467 +1,266 @@ import { describe, expect, it } from 'bun:test' import { - createBlankPresentationDocument, + createBlankPresentationProject, createBlankPresentationSlide, - presentationSlideBackground, - presentationSlideFooter, - type PresentationWorkspace, } from '@/atoms/presentation' import { createPresentationAsset } from '@/presentation/project' -import { executePowerPointRequest } from '../powerPointProtocol' -import { presentationTextStyleAt } from '../presentationText' +import { executePowerPointRequest, type PowerPointProjectCollection } from '../powerPointProtocol' -function workspace(): PresentationWorkspace { - const document = createBlankPresentationDocument('Quarterly review') - return { activeDocumentId: document.id, documents: [document] } +function workspace(): PowerPointProjectCollection { + const document = createBlankPresentationProject('Quarterly review') + return { activeProjectId: document.id, projects: [document] } } -describe('PowerPoint renderer protocol', () => { - it('invalidates cached media revisions for payload changes and rejects stale edits', async () => { - const initial = workspace() - const document = initial.documents[0]! - const slide = document.slides.pages[0]! - const source = { dataUrl: 'data:image/png;base64,YQ==', fileName: 'image.png', mimeType: 'image/png' } - const asset = createPresentationAsset('image', source) - document.assets = [asset] - slide.elements = [{ id: 'image', type: 'image', sourceAssetId: asset.id, altText: '', fit: 'contain', x: 0, y: 0, width: 20, height: 20, rotation: 0 }] - const revision = async () => { - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - return (read.result as { page: { revision: string } }).page.revision - } - const first = await revision() - expect(await revision()).toBe(first) - asset.source.dataUrl = 'data:image/png;base64,Yg==' - const second = await revision() - expect(second).not.toBe(first) - expect(await revision()).toBe(second) - await expect(executePowerPointRequest(initial, { method: 'remove_ppt_element', params: { page_id: slide.id, ref: 'image', expected_revision: first } })).rejects.toThrow('changed after it was read') - expect(slide.elements).toHaveLength(1) - asset.source.dataUrl = 'data:image/png;base64,YQ==' - expect(await revision()).toBe(first) - slide.elements[0]!.x = 10 - expect(await revision()).not.toBe(first) - }) - - it('respects explicit Agent run sizes alongside base formatting and retains numbering through later edits', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - slide.elements = [{ id: 'rich', type: 'text', text: '标题 English', x: 20, y: 20, width: 600, height: 120, rotation: 0, - fontSize: 40, fontFamily: 'Arial', fontWeight: 700, color: '#111111', align: 'left', - textRuns: [{ start: 3, end: 10, style: { fontSize: 20, fontWeight: 400, color: '#0088CC' } }], - }] - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - const page = (read.result as { page: { markdown: string; revision: string } }).page - const runs = JSON.stringify([{ start: 3, end: 10, style: { fontSize: 40, fontWeight: 400, color: '#0088CC', opacity: 0.25 } }]).replaceAll('"', '"') - const paragraphs = JSON.stringify([{ start: 0, end: 10, style: { listStyle: 'number', listStartAt: 9, listNumberFormat: 'romanUcPeriod' } }]).replaceAll('"', '"') - const replacement = page.markdown.match(//)![0] - .replace('fontSize="40"', 'fontSize="80"').replace(/textRuns="[^"]*"/, `textRuns="${runs}" paragraphs="${paragraphs}"`) - const result = await executePowerPointRequest(initial, { method: 'edit_ppt_page', params: { - page_id: slide.id, ref: 'rich', expected_revision: page.revision, replacement, - } }) - const text = result.workspace?.documents[0]?.slides.pages[0]?.elements[0] - if (text?.type !== 'text') throw new Error(JSON.stringify(result.result)) - expect(presentationTextStyleAt(text, 3)).toMatchObject({ fontSize: 40, fontWeight: 400, color: '#0088CC' }) - expect(text.paragraphs?.[0]?.style.listStartAt).toBe(9) - expect(text.paragraphs?.[0]?.style.listNumberFormat).toBe('romanUcPeriod') - expect(presentationTextStyleAt(text, 3).opacity).toBe(0.25) - const updated = await executePowerPointRequest(result.workspace!, { method: 'get_ppt_page', params: { page_id: slide.id } }) - expect((updated.result as { page: { markdown: string } }).page.markdown).toContain('listStartAt":9') - }) - it('keeps middle run and paragraph formatting when the Agent changes several separated words', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - slide.elements = [{ - id: 'rich', type: 'text', text: '标题 English 结尾\n正文', x: 20, y: 20, width: 500, height: 200, rotation: 0, - fontSize: 40, fontFamily: 'Arial', fontWeight: 700, color: '#111111', align: 'left', lineSpacing: 48, - textRuns: [{ start: 3, end: 10, style: { fontSize: 20, fontWeight: 400, color: '#0088CC' } }], - paragraphs: [{ start: 0, end: 13, style: { align: 'center', lineSpacing: 48 } }, - { start: 14, end: 16, style: { align: 'right', lineSpacing: 28, spaceBefore: 12 } }], - }] - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - const page = (read.result as { page: { markdown: string; revision: string } }).page - expect(page.markdown).toContain('paragraphs=') - for (const omitAttributes of [false, true]) { - let replacement = page.markdown.match(//)![0].replace('标题', '新标题').replace('结尾', '新结尾').replace('正文', '新正文') - if (omitAttributes) replacement = replacement.replace(/ (textRuns|paragraphs)="[^"]*"/g, '') - const edited = await executePowerPointRequest(initial, { method: 'edit_ppt_page', params: { - page_id: slide.id, ref: 'rich', expected_revision: page.revision, replacement, - } }) - const text = edited.workspace?.documents[0]?.slides.pages[0]?.elements[0] - if (text?.type !== 'text') throw new Error(JSON.stringify(edited.result)) - expect(presentationTextStyleAt(text, 4)).toMatchObject({ fontSize: 20, fontWeight: 400, color: '#0088CC' }) - expect(text.paragraphs).toEqual([ - { start: 0, end: 15, style: expect.objectContaining({ align: 'center', lineSpacing: 48 }) }, - { start: 16, end: 19, style: expect.objectContaining({ align: 'right', lineSpacing: 28, spaceBefore: 12 }) }, - ]) - } - }) - - it('retains authored blank-line size when the Agent edits the surrounding text', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - slide.elements = [{ id: 'blank-lines', type: 'text', text: 'Before\n\nAfter', x: 0, y: 0, width: 600, height: 400, rotation: 0, - fontSize: 32, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', - paragraphs: [{ start: 0, end: 6, style: {} }, { start: 7, end: 7, style: {}, endStyle: { fontSize: 128 } }, { start: 8, end: 13, style: {} }], - }] - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - const page = (read.result as { page: { markdown: string; revision: string } }).page - for (const omitAttributes of [false, true]) { - let replacement = page.markdown.match(//)![0].replace('Before', 'New Before').replace('After', 'New After') - if (omitAttributes) replacement = replacement.replace(/ paragraphs="[^"]*"/g, '') - const edited = await executePowerPointRequest(initial, { method: 'edit_ppt_page', params: { page_id: slide.id, ref: 'blank-lines', expected_revision: page.revision, replacement } }) - expect(edited.workspace?.documents[0]?.slides.pages[0]?.elements[0]).toMatchObject({ text: 'New Before\n\nNew After', - paragraphs: [{ start: 0, end: 10 }, { start: 11, end: 11, endStyle: { fontSize: 128 } }, { start: 12, end: 21 }], - }) - } - }) - - it('rejects malformed paragraph partitions and styles without mutating the document', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - for (const paragraphs of [[], [{ start: 1, end: 4, style: {} }], [{ start: 0, end: 99, style: {} }], - [{ start: 0, end: 4, style: { lineSpacing: -1 } }], [{ start: 0, end: 4, style: { align: 'invalid' } }], - [{ start: 0, end: 1, style: {} }, { start: 2, end: 4, style: {} }], - ...[null, { fontSize: -1 }, { opacity: 2 }, { fontFamily: 12 }].map(endStyle => [{ start: 0, end: 4, style: {}, endStyle }]), - ...[0, -1, 1.5, 32768, '5'].map(listStartAt => [{ start: 0, end: 4, style: { listStartAt } }])]) { - const serialized = JSON.stringify(paragraphs).replaceAll('"', '"') - const result = await executePowerPointRequest(initial, { method: 'insert_ppt_element', params: { - page_id: slide.id, expected_revision: (read.result as { page: { revision: string } }).page.revision, - element: `Text`, - } }) - expect(result.result).toMatchObject({ status: 'invalid' }) - expect(result.workspace).toBeUndefined() - } - expect(slide.elements).toEqual([]) - }) - - it('preserves rich text through agent moves, source edits and explicit frame formatting', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - slide.elements = [{ - id: 'rich-text', type: 'text', text: '标题 English', x: 20, y: 100, width: 400, height: 100, rotation: 0, - fontSize: 40, fontFamily: 'Arial', fontWeight: 700, color: '#111111', align: 'left', lineSpacing: 48, - textRuns: [{ start: 3, end: 10, style: { fontSize: 20, fontWeight: 400, color: '#0088CC' } }], - }] - const readPage = async (state: PresentationWorkspace) => { - const read = await executePowerPointRequest(state, { method: 'get_ppt_page', params: { page_id: slide.id } }) - return (read.result as { page: { markdown: string; revision: string } }).page - } - const change = async (state: PresentationWorkspace, transform: (markdown: string) => string) => { - const page = await readPage(state) - const element = page.markdown.match(//)![0] - const result = await executePowerPointRequest(state, { method: 'edit_ppt_page', params: { - page_id: slide.id, ref: 'rich-text', expected_revision: page.revision, replacement: transform(element), - } }) - expect(result.workspace).toBeDefined() - return result.workspace! - } - expect((await readPage(initial)).markdown).toContain('textRuns=') - const moved = await change(initial, markdown => markdown.replace('x="20"', 'x="35"')) - const movedText = moved.documents[0]!.slides.pages[0]!.elements[0]! - expect(movedText).toMatchObject({ x: 35, lineSpacing: 48 }) - if (movedText.type !== 'text') throw new Error('Expected text') - expect(presentationTextStyleAt(movedText, 3)).toMatchObject({ fontSize: 20, color: '#0088CC', fontWeight: 400 }) - const edited = await change(moved, markdown => markdown.replace('标题 English', '新标题 English')) - const editedText = edited.documents[0]!.slides.pages[0]!.elements[0]! - if (editedText.type !== 'text') throw new Error('Expected text') - expect(presentationTextStyleAt(editedText, 4)).toMatchObject({ fontSize: 20, color: '#0088CC', fontWeight: 400 }) - const colored = await change(edited, markdown => markdown.replace('color="#111111"', 'color="#FF0000"')) - const coloredText = colored.documents[0]!.slides.pages[0]!.elements[0]! - if (coloredText.type !== 'text') throw new Error('Expected text') - expect(presentationTextStyleAt(coloredText, 4)).toMatchObject({ fontSize: 20, color: '#FF0000' }) - expect(slide.elements[0]).toMatchObject({ text: '标题 English', x: 20 }) - }) +async function readDeck(state: PowerPointProjectCollection) { + const document = state.projects[0]! + return executePowerPointRequest(state, { method: 'read_deck', params: { document_id: document.id, include_theme: true } }) +} - it('rejects invalid inline style ranges without changing the document', async () => { - const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! - const read = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: slide.id } }) - for (const textRuns of [ - [{ start: 0, end: 99, style: { fontSize: 20 } }], - [{ start: 0, end: 1, style: { fontSize: -1 } }], - [{ start: 0, end: 1, style: { unexpected: true } }], - ]) { - const serialized = JSON.stringify(textRuns).replaceAll('"', '"') - const result = await executePowerPointRequest(initial, { method: 'insert_ppt_element', params: { - page_id: slide.id, expected_revision: (read.result as { page: { revision: string } }).page.revision, - element: `Text`, - } }) - expect(result.result).toMatchObject({ status: 'invalid' }) - expect(result.workspace).toBeUndefined() - } - expect(slide.elements).toEqual([]) - }) +async function readPage(state: PowerPointProjectCollection, pageId: string, format = 'compact') { + const document = state.projects[0]! + return executePowerPointRequest(state, { method: 'read_page', params: { document_id: document.id, page_id: pageId, format } }) +} - it('opens a new target with metadata and one blank page summary', async () => { +describe('PowerPoint renderer protocol', () => { + it('opens a new target and reuses the exact Session document', async () => { const opened = await executePowerPointRequest(workspace(), { - method: 'view_ppt', - params: { target: '/workspace/roadmap.pptx', file_name: 'roadmap.pptx' }, + method: 'open', params: { target: '/workspace/roadmap.pptx', file_name: 'roadmap.pptx' }, }) - expect(opened.target).toBe('/workspace/roadmap.pptx') - expect(opened.persist).toBeTrue() expect(opened.result).toMatchObject({ - identity: { document_id: expect.any(String), file_name: 'roadmap.pptx' }, - meta: { total_pages: 1, current_position: 1 }, - pages: [{ index: 0, has_content: false }], + revision: expect.any(String), + deck: { id: expect.any(String), file_name: 'roadmap.pptx', total_pages: 1, pages: [{ index: 0, has_content: false }] }, reused: false, }) - - const reopened = await executePowerPointRequest(opened.workspace!, { - method: 'view_ppt', - params: { target: '/workspace/roadmap.pptx', file_name: 'roadmap.pptx' }, - }, { currentTarget: opened.target!, fileName: 'roadmap.pptx' }) - expect(reopened.workspace).toBeUndefined() + const reopened = await executePowerPointRequest(opened.projects!, { + method: 'open', params: { target: '/workspace/roadmap.pptx', file_name: 'roadmap.pptx' }, + }, { currentTarget: opened.target! }) + expect(reopened.projects).toBeUndefined() expect(reopened.result).toMatchObject({ reused: true }) }) - it('reads refs and atomically inserts one native element', async () => { - const initial = workspace() - const slideId = initial.documents[0]!.slides.selectedPageId - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', - params: { page_id: slideId }, - }) - const revision = (read.result as { page: { revision: string } }).page.revision - expect((read.result as { page: { refs: string[] } }).page.refs).toEqual([]) - const applied = await executePowerPointRequest(initial, { - method: 'insert_ppt_element', - params: { - page_id: slideId, - expected_revision: revision, - element: 'Revenue grew 24%', - assets: {}, - }, - }) - - const document = applied.workspace!.documents[0]! - expect(document.slides.pages[0]!.elements[0]).toMatchObject({ - type: 'text', - text: 'Revenue grew 24%', - }) - expect(document.revision).toBe(initial.documents[0]!.revision + 1) - expect(document.slides.selectedPageId).toBe(slideId) - expect(applied.agentChange).toEqual({ - elementIds: [expect.any(String)], - kind: 'content', - slideId, - }) - const result = applied.result as { element_ref: string; page: { markdown: string; refs: string[] } } - expect(result.page.refs).toEqual([result.element_ref]) - expect(result.page.markdown).toContain(`ref="${result.element_ref}"`) - expect(initial.documents[0]!.slides.pages[0]!.elements).toEqual([]) + it('reports the requested document file name independently of the active tab', async () => { + const first = createBlankPresentationProject('First') + const second = createBlankPresentationProject('Second') + const initial = { activeProjectId: second.id, projects: [first, second] } + const result = await executePowerPointRequest(initial, { + method: 'read_deck', params: { document_id: first.id }, + }, { currentTarget: '/workspace/second.pptx', fileNameOf: (projectId) => projectId === first.id ? 'first.pptx' : 'second.pptx' }) + expect(result.result).toMatchObject({ deck: { id: first.id, file_name: 'first.pptx' } }) + expect(result.projects?.activeProjectId).toBe(first.id) }) - it('edits one referenced element without replacing its identity or siblings', async () => { + it('offers compact Markdown and an exact structured model without using Markdown for edits', async () => { const initial = workspace() - const slideId = initial.documents[0]!.slides.selectedPageId - initial.documents[0]!.slides.pages[0]!.elements = [ - { - id: 'stable', type: 'text', text: 'Same', x: 20, y: 20, width: 200, height: 60, - rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, color: '#111111', align: 'left', - }, - { - id: 'changed', type: 'text', text: 'Before', x: 20, y: 100, width: 200, height: 60, - rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, color: '#111111', align: 'left', - }, - ] - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', params: { page_id: slideId }, - }) - const revision = (read.result as { page: { revision: string } }).page.revision - const applied = await executePowerPointRequest(initial, { - method: 'edit_ppt_page', - params: { - page_id: slideId, - expected_revision: revision, - ref: 'changed', - replacement: 'After', - assets: {}, - }, - }) - - expect(applied.agentChange?.elementIds).toEqual(['changed']) - expect(applied.workspace!.documents[0]!.slides.pages[0]!.elements).toEqual([ - initial.documents[0]!.slides.pages[0]!.elements[0], - expect.objectContaining({ id: 'changed', text: 'After' }), - ]) + const slide = initial.projects[0]!.slides.pages[0]! + slide.elements = [{ + id: 'title', type: 'text', text: 'Before', x: 37, y: 91, width: 620, height: 110, rotation: 4, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', + }] + slide.comments = [{ id: 'review', author: 'Reviewer', createdAt: new Date(0).toISOString(), resolved: false, text: 'Tighten this', elementId: 'title' }] + const compact = await readPage(initial, slide.id) + expect((compact.result as { page: { markdown: string } }).page.markdown).toContain('') + const model = await readPage(initial, slide.id, 'model') + expect(model.result).toMatchObject({ page: { model: { + comments: [{ id: 'review', text: 'Tighten this', elementId: 'title' }], + elements: [{ id: 'title', x: 37, fontSize: 44 }], + } } }) }) - it('removes one referenced element and rejects an invented ref', async () => { + it('patches native elements while preserving every omitted property', async () => { const initial = workspace() - const slide = initial.documents[0]!.slides.pages[0]! + const document = initial.projects[0]! + const slide = document.slides.pages[0]! slide.elements = [{ - id: 'obsolete', type: 'text', text: 'Remove me', x: 20, y: 20, width: 200, height: 60, - rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, color: '#111111', align: 'left', + id: 'title', type: 'text', text: 'Before', x: 37, y: 91, width: 620, height: 110, rotation: 4, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', + textInsets: { left: 5, top: 6, right: 7, bottom: 8 }, }] - slide.comments = [{ - id: 'comment', author: 'Reviewer', createdAt: new Date(0).toISOString(), resolved: false, - text: 'Keep this review note', elementId: 'obsolete', - }] - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', params: { page_id: slide.id }, - }) - const revision = (read.result as { page: { revision: string } }).page.revision - const removed = await executePowerPointRequest(initial, { - method: 'remove_ppt_element', - params: { page_id: slide.id, ref: 'obsolete', expected_revision: revision }, + const read = await readPage(initial, slide.id) + const revision = (read.result as { revision: string }).revision + const updated = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, expected_revision: revision, + operations: [{ type: 'patch', id: 'title', element_type: 'text', patch: { text: 'After', x: 55 } }], + } }) + expect(updated.projects!.projects[0]!.slides.pages[0]!.elements[0]).toMatchObject({ + id: 'title', text: 'After', x: 55, y: 91, width: 620, fontSize: 44, + textInsets: { left: 5, top: 6, right: 7, bottom: 8 }, }) - - expect(removed.workspace!.documents[0]!.slides.pages[0]!.elements).toEqual([]) - expect(removed.workspace!.documents[0]!.slides.pages[0]!.comments?.[0]).not.toHaveProperty('elementId') - expect((removed.result as { element_ref: string }).element_ref).toBe('obsolete') - await expect(executePowerPointRequest(initial, { - method: 'remove_ppt_element', - params: { page_id: slide.id, ref: 'invented', expected_revision: revision }, - })).rejects.toThrow('Unknown PowerPoint element ref') }) - it('clears links to a page when the Agent removes that page', async () => { + it('adds, patches, and removes comments atomically', async () => { const initial = workspace() - const document = initial.documents[0]! - const first = document.slides.pages[0]! - const second = createBlankPresentationSlide('Second') - first.elements = [{ - id: 'link', type: 'rect', x: 0, y: 0, width: 10, height: 10, rotation: 0, - fill: '#FFFFFF', borderColor: '#000000', borderWidth: 0, - hyperlink: { type: 'slide', slideId: second.id }, + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + slide.elements = [{ + id: 'title', type: 'text', text: 'Title', x: 37, y: 91, width: 620, height: 110, rotation: 0, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', }] - document.slides = { - pages: [first, second], - slideOrder: [first.id, second.id], - selectedPageId: first.id, - } - const overview = await executePowerPointRequest(initial, { - method: 'view_ppt', params: { target: '/workspace/review.pptx', file_name: 'review.pptx' }, - }, { currentTarget: '/workspace/review.pptx', fileName: 'review.pptx' }) - const page = await executePowerPointRequest(initial, { method: 'get_ppt_page', params: { page_id: second.id } }) - const removed = await executePowerPointRequest(initial, { - method: 'remove_ppt_page', - params: { - page_id: second.id, - expected_revision: (page.result as { page: { revision: string } }).page.revision, - expected_deck_revision: (overview.result as { deck_revision: string }).deck_revision, - }, - }) + slide.comments = [{ id: 'obsolete', author: 'Reviewer', createdAt: new Date(0).toISOString(), resolved: false, text: 'Remove me' }] + const read = await readPage(initial, slide.id) + const updated = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, + page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [ + { type: 'add-comment', comment: { id: 'review', text: 'Tighten this', elementId: 'title' } }, + { type: 'patch-comment', id: 'review', patch: { text: 'Looks good', resolved: true, elementId: null } }, + { type: 'remove-comment', id: 'obsolete' }, + ], + } }) + expect(updated.projects!.projects[0]!.slides.pages[0]!.comments).toEqual([ + expect.objectContaining({ id: 'review', author: 'Agent', resolved: true, text: 'Looks good' }), + ]) + expect(updated.projects!.projects[0]!.slides.pages[0]!.comments![0]).not.toHaveProperty('elementId') + }) - expect(removed.workspace!.documents[0]!.slides.pages).toHaveLength(1) - expect(removed.workspace!.documents[0]!.slides.pages[0]!.elements[0]).not.toHaveProperty('hyperlink') + it('rejects an element patch whose declared type does not match the live element', async () => { + const initial = workspace() + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + slide.elements = [{ + id: 'title', type: 'text', text: 'Title', x: 37, y: 91, width: 620, height: 110, rotation: 0, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', + }] + const read = await readPage(initial, slide.id) + await expect(executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, + page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'patch', id: 'title', element_type: 'image', patch: { altText: 'Nope' } }], + } })).rejects.toThrow('title is text, not image') + await expect(executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, + page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'patch', id: 'title', element_type: 'text', patch: { fill: '#FF0000' } }], + } })).rejects.toThrow('Unsupported patch.patch property: fill') }) - it('updates document-wide design with a private document revision', async () => { + it('applies deck design, insertion, movement, and deletion as one transaction', async () => { const initial = workspace() - const overview = await executePowerPointRequest(initial, { - method: 'view_ppt', - params: { target: '/workspace/review.pptx', file_name: 'review.pptx' }, - }, { currentTarget: '/workspace/review.pptx', fileName: 'review.pptx' }) - const revision = (overview.result as { document_revision: string }).document_revision - const applied = await executePowerPointRequest(initial, { - method: 'update_ppt_design', - params: { - expected_document_revision: revision, - design: { - theme: 'midnight', - page_size: 'standard', - footer: { show_slide_number: true }, - transition: { effect: 'fade', duration_ms: 650, through_black: true }, - }, - }, - }) + const document = initial.projects[0]! + const cover = document.slides.pages[0]! + cover.id = 'cover' + const obsolete = createBlankPresentationSlide('Obsolete') + obsolete.id = 'obsolete' + document.slides = { pages: [cover, obsolete], slideOrder: ['cover', 'obsolete'], selectedPageId: 'cover' } + const read = await readDeck(initial) + const revision = (read.result as { revision: string }).revision + const result = await executePowerPointRequest(initial, { method: 'manage_deck', params: { + document_id: document.id, + expected_revision: revision, + operations: [ + { type: 'set-design', patch: { title: 'Updated deck', theme: 'midnight' } }, + { type: 'insert-page', page: { id: 'evidence', name: 'Evidence' }, after: 'cover' }, + { type: 'remove-page', pageId: 'obsolete' }, + ], + } }) + const next = result.projects!.projects[0]! + expect(next.title).toBe('Updated deck') + expect(next.theme.background).toBe('#17182B') + expect(next.slides.pages.map((page) => page.id)).toEqual(['cover', 'evidence']) + expect(result.result).toMatchObject({ status: 'ready', changed_page_ids: expect.arrayContaining(['cover', 'obsolete', 'evidence']) }) + }) - const document = applied.workspace!.documents[0]! - expect(document.theme).toMatchObject({ - background: '#17182B', - bodyFontFamily: 'Aptos', - footer: { showSlideNumber: true }, - titleFontFamily: 'Aptos Display', - }) - expect(document.pageSize.preset).toBe('standard') - expect(document.slides.pages[0]).toMatchObject({ - transition: { effect: 'fade', durationMs: 650, throughBlack: true }, + it('merges a partial deck transition with the selected page transition', async () => { + const initial = workspace() + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + slide.transition = { effect: 'reveal', durationMs: 750, direction: 'left', throughBlack: true } + const read = await readDeck(initial) + const result = await executePowerPointRequest(initial, { method: 'manage_deck', params: { + document_id: document.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'set-design', patch: { transition: { durationMs: 1250 } } }], + } }) + expect(result.projects!.projects[0]!.slides.pages[0]!.transition).toEqual({ + effect: 'reveal', durationMs: 1250, direction: 'left', throughBlack: true, }) - expect(document.slides.pages[0]).not.toHaveProperty('background') - expect(document.slides.pages[0]).not.toHaveProperty('footer') - expect(presentationSlideBackground(document.theme, document.slides.pages[0]!)).toBe('#17182B') - expect(presentationSlideFooter(document.theme, document.slides.pages[0]!).showSlideNumber).toBe(true) - expect(applied.agentChange).toMatchObject({ kind: 'design', slideId: document.slides.selectedPageId }) - expect(applied.persist).toBeTrue() }) - it('rejects a stale document-wide design change', async () => { + it('does not publish a partial workspace when any operation is invalid', async () => { const initial = workspace() - await expect(executePowerPointRequest(initial, { - method: 'update_ppt_design', - params: { expected_document_revision: 'stale', design: { theme: 'paper' } }, - })).rejects.toEqual(expect.objectContaining({ code: 'document_changed' })) + const original = structuredClone(initial) + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + const read = await readPage(initial, slide.id) + await expect(executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, + page_id: slide.id, + expected_revision: (read.result as { revision: string }).revision, + operations: [ + { type: 'add', element: { id: 'valid', type: 'text', text: 'Valid' } }, + { type: 'add', element: { id: 'broken', type: 'not-a-shape' } }, + ], + } })).rejects.toThrow('Unsupported PowerPoint element type') + expect(initial).toEqual(original) }) - it('rejects a stale page token without publishing a workspace', async () => { + it('rejects stale page and deck revisions before applying commands', async () => { const initial = workspace() - const slideId = initial.documents[0]!.slides.selectedPageId - await expect(executePowerPointRequest(initial, { - method: 'insert_ppt_element', - params: { - page_id: slideId, - expected_revision: 'stale', - element: 'Changed', - }, - })).rejects.toEqual(expect.objectContaining({ code: 'page_changed' })) - expect(initial.documents[0]!.slides.pages[0]!.elements).toEqual([]) + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + await expect(executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, expected_revision: 'stale', + operations: [{ type: 'set-page', patch: { name: 'Nope' } }], + } })).rejects.toEqual(expect.objectContaining({ code: 'page_changed' })) + await expect(executePowerPointRequest(initial, { method: 'manage_deck', params: { + document_id: document.id, expected_revision: 'stale', + operations: [{ type: 'set-design', patch: { title: 'Nope' } }], + } })).rejects.toEqual(expect.objectContaining({ code: 'document_changed' })) }) - it('returns compiler diagnostics without mutating the page', async () => { + it('supports validation without publishing or incrementing a revision', async () => { const initial = workspace() - const slideId = initial.documents[0]!.slides.selectedPageId - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', params: { page_id: slideId }, - }) - const revision = (read.result as { page: { revision: string } }).page.revision - const invalid = await executePowerPointRequest(initial, { - method: 'insert_ppt_element', - params: { - page_id: slideId, - expected_revision: revision, - element: '# Not a Ppt element', - }, - }) - expect(invalid.workspace).toBeUndefined() - expect(invalid.result).toMatchObject({ status: 'invalid' }) - expect(initial.documents[0]!.slides.pages[0]!.elements).toEqual([]) + const document = initial.projects[0]! + const slide = document.slides.pages[0]! + const read = await readPage(initial, slide.id) + const revision = (read.result as { revision: string }).revision + const result = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, expected_revision: revision, + operations: [{ type: 'set-page', patch: { name: 'Validated' } }], validate_only: true, + } }) + expect(result.projects).toBeUndefined() + expect(result.result).toMatchObject({ status: 'validated' }) + expect(document.slides.pages[0]!.name).not.toBe('Validated') }) - it('returns a workspace path for embedded assets without exposing it in Markdown', async () => { + it('clears optional properties and detaches comments through explicit commands', async () => { const initial = workspace() - const document = initial.documents[0]! + const document = initial.projects[0]! const slide = document.slides.pages[0]! + slide.background = '#123456' + slide.elements = [{ id: 'remove', type: 'text', text: 'Remove', x: 20, y: 20, width: 200, height: 60, + rotation: 0, fontSize: 24, fontFamily: 'Aptos', fontWeight: 400, color: '#111111', align: 'left' }] + slide.comments = [{ id: 'comment', author: 'Reviewer', createdAt: new Date(0).toISOString(), resolved: false, text: 'Keep', elementId: 'remove' }] + const read = await readPage(initial, slide.id) + const result = await executePowerPointRequest(initial, { method: 'edit_page', params: { + document_id: document.id, page_id: slide.id, expected_revision: (read.result as { revision: string }).revision, + operations: [{ type: 'set-page', patch: { background: null } }, { type: 'remove', id: 'remove' }], + } }) + const next = result.projects!.projects[0]!.slides.pages[0]! + expect(next.background).toBeUndefined() + expect(next.elements).toEqual([]) + expect(next.comments?.[0]).not.toHaveProperty('elementId') + }) + + it('selects an exact live page for rendering and returns embedded assets safely', async () => { + const initial = workspace() + const document = initial.projects[0]! + const first = document.slides.pages[0]! + const second = createBlankPresentationSlide('Second') + document.slides = { pages: [first, second], slideOrder: [first.id, second.id], selectedPageId: first.id } document.assets = [createPresentationAsset('image', { dataUrl: 'data:image/png;base64,cG5n', fileName: 'hero.png', mimeType: 'image/png', }, 'hero-asset')] - const hero = { - id: 'hero', - type: 'image' as const, - sourceAssetId: 'hero-asset', - altText: 'Hero', - fit: 'cover' as const, - x: 20, - y: 20, - width: 320, - height: 180, - rotation: 0, - } - slide.elements = [hero, { ...hero, id: 'hero-copy', x: 360 }] - - const read = await executePowerPointRequest(initial, { - method: 'get_ppt_page', params: { page_id: slide.id }, - }) - const result = read.result as { assets: Array>; page: { markdown: string } } - expect(result.assets).toHaveLength(1) - expect(result.assets[0]).toMatchObject({ - path: '.ppt-assets/hero-asset-hero.png', - data_url: 'data:image/png;base64,cG5n', - }) - expect(result.page.markdown).toContain('src="@existing/hero"') - expect(result.page.markdown).toContain('src="@existing/hero-copy"') - expect(result.page.markdown).not.toContain('base64') + second.elements = [{ id: 'hero', type: 'image', sourceAssetId: 'hero-asset', altText: 'Hero', fit: 'cover', x: 20, y: 20, width: 320, height: 180, rotation: 0 }] + const rendered = await executePowerPointRequest(initial, { method: 'inspect', params: { document_id: document.id, kind: 'render', page_id: second.id } }) + expect(rendered.result).toMatchObject({ document_revision: 1, page_id: second.id, index: 1, revision: expect.any(String) }) + expect(rendered.projects!.projects[0]!.slides.selectedPageId).toBe(second.id) + const read = await readPage(initial, second.id, 'both') + expect(read.result).toMatchObject({ assets: [{ path: '.ppt-assets/hero-asset-hero.png', data_url: 'data:image/png;base64,cG5n' }] }) + expect(read.result).toMatchObject({ page: { model: { elements: [{ id: 'hero', src: '.ppt-assets/hero-asset-hero.png' }] } } }) + expect(JSON.stringify(read.result)).not.toContain('sourceAssetId') }) }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationDesign.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationDesign.test.ts index bbefca58..cc47bd0d 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationDesign.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationDesign.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'bun:test' import { - createBlankPresentationDocument, + createBlankPresentationProject, createBlankPresentationSlide, presentationSlideBackground, presentationSlideFooter, @@ -10,7 +10,7 @@ import { applyPresentationDesign } from '../presentationDesign' describe('presentation design defaults', () => { it('updates global theme defaults without copying over page overrides', () => { - const document = createBlankPresentationDocument('Theme defaults') + const document = createBlankPresentationProject('Theme defaults') const inherited = document.slides.pages[0]! const overridden = { ...createBlankPresentationSlide('Override'), diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationEditorDriver.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationEditorDriver.test.ts index d2f037d9..1278ca9d 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationEditorDriver.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationEditorDriver.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'bun:test' -import { createBlankPresentationDocument, createBlankPresentationSlide, selectPresentationPage } from '@/atoms/presentation' +import { createBlankPresentationProject, createBlankPresentationSlide, selectPresentationPage } from '@/atoms/presentation' import { createOfficeEditorBinding } from '../office/officeEditorBinding' import { bindPresentationNativeEdit, createPresentationEditorDriver, type PresentationEditingObject } from '../presentationEditorDriver' function setup() { - let document = createBlankPresentationDocument('Native edit') + let document = createBlankPresentationProject('Native edit') let editing: PresentationEditingObject | null = null let pending: (() => void) | null = null let disposed = 0 @@ -41,7 +41,7 @@ describe('PowerPoint native editor driver', () => { const active = { isEditing: true, exitEditing: () => { events.push('text') active.isEditing = false - binding.publishChange({ ...read(), title: 'Committed native text', revision: read().revision + 1 }) + binding.publishChange({ ...read(), title: 'Committed native text' }) } } edit(active) defer(() => { events.push('transform') }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationFileController.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationFileController.test.ts index 06e74975..a78a2338 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationFileController.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationFileController.test.ts @@ -1,14 +1,19 @@ import { describe, expect, it, mock } from 'bun:test' -import { createBlankPresentationDocument, type PresentationWorkspace } from '@/atoms/presentation' +import { createBlankPresentationProject, type PresentationProject } from '@/atoms/presentation' +import type { PresentationCheckpoint } from '@/presentation/checkpoint' import { createPresentationEditorDriver } from '../presentationEditorDriver' import { createOfficeEditorBinding } from '../office/officeEditorBinding' -import { createPresentationFileController } from '../presentationFileController' -import { isPresentationDirty } from '../presentationWorkspaceRuntime' -import type { OfficeFilesAPI } from '../../../shared/office-files' +import { createPresentationFileController, isPresentationProjectDirty } from '../presentationFileController' +import type { OfficeFileSource, OfficeFilesAPI } from '../../../shared/office-files' -function setup(automatic = false, onSaveStatus?: (status: 'saving' | 'saved' | 'error', error?: string) => void) { - const document = { ...createBlankPresentationDocument('Report'), source: { path: '/Report.pptx', mtimeMs: 42 }, savedRevision: 1 } - let workspace: PresentationWorkspace = { activeDocumentId: document.id, documents: [document] } +function setup(managed = false, onExportStatus?: (status: 'saving' | 'saved' | 'error', error?: string) => void) { + const project = createBlankPresentationProject('Report') + let checkpoint: PresentationCheckpoint = { + schemaVersion: 1, + activeProjectId: project.id, + projects: [project], + projectMetadata: { [project.id]: { revision: 1, source: { path: '/Report.pptx', mtimeMs: 42 }, savedRevision: 1 } }, + } let recovery: string | null = null const files: OfficeFilesAPI = { inspect: async (_kind, path) => ({ path, mtimeMs: 42 }), @@ -17,170 +22,230 @@ function setup(automatic = false, onSaveStatus?: (status: 'saving' | 'saved' | ' getRecovery: async () => recovery, setRecovery: async (_kind, _session, value) => { recovery = value }, } - const controller = createPresentationFileController({ automatic, onSaveStatus, sessionId: 'session-a', files, read: () => workspace, write: (value) => { workspace = value; controller.schedule() }, encode: async () => new Uint8Array([1]), flushEditor: async () => undefined, locale: () => 'en' }) - return { controller, files, read: () => workspace, edit: () => { workspace = { ...workspace, documents: [{ ...workspace.documents[0]!, revision: workspace.documents[0]!.revision + 1 }] } } } + const commitExport = (projectId: string, _fileName: string, source: OfficeFileSource, exportedRevision: number) => { + checkpoint = { + ...checkpoint, + projectMetadata: { + ...checkpoint.projectMetadata, + [projectId]: { ...checkpoint.projectMetadata[projectId]!, source, sourceProtected: false, savedRevision: exportedRevision }, + }, + } + } + const controller = createPresentationFileController({ + encode: async () => new Uint8Array([1]), + files, + flushEditor: async () => undefined, + managed, + onExportStatus, + read: () => checkpoint, + commitExport, + sessionId: 'session-a', + }) + return { + controller, + files, + read: () => checkpoint, + readRecovery: () => recovery, + writeRecovery: (value: string | null) => { recovery = value }, + edit: () => { + const metadata = checkpoint.projectMetadata[project.id]! + checkpoint = { + ...checkpoint, + projectMetadata: { ...checkpoint.projectMetadata, [project.id]: { ...metadata, revision: metadata.revision + 1 } }, + } + }, + } } -describe('PowerPoint explicit saving', () => { - it('uses Save as when Save is chosen while closing a protected imported file', async () => { +describe('PowerPoint project persistence and explicit export', () => { + it('requires Save as for a protected imported source and clears protection only after export', async () => { const { controller, files, read, edit } = setup() - await controller.restore() - read().documents[0]!.sourceProtected = true - edit() - files.confirmClose = async () => 'save' - expect(await controller.beforeClose(read().activeDocumentId)).toBe(true) - expect(files.save).toHaveBeenCalledWith(expect.objectContaining({ saveAs: true, preserveSource: true })) - controller.recovery.dispose() - }) + try { + await controller.restore() + read().projectMetadata[read().activeProjectId]!.sourceProtected = true + edit() + await expect(controller.save(read().activeProjectId)).rejects.toThrow() + expect(files.save).not.toHaveBeenCalled() - it('requires a distinct Save as for a converted source and clears protection only after saving', async () => { - const { controller, files, read, edit } = setup() - await controller.restore() - read().documents[0]!.sourceProtected = true - edit() - await expect(controller.save(read().activeDocumentId)).rejects.toThrow() - expect(files.save).not.toHaveBeenCalled() - files.save = mock(async () => ({ ok: false as const, reason: 'source-protected' as const })) - await expect(controller.save(read().activeDocumentId, true)).rejects.toThrow() - expect(read().documents[0]!.sourceProtected).toBe(true) - files.save = mock(async () => ({ ok: true as const, source: { path: '/Copy.pptx', mtimeMs: 43 }, fileName: 'Copy.pptx' })) - expect(await controller.save(read().activeDocumentId, true)).toBe(true) - expect(files.save).toHaveBeenCalledWith(expect.objectContaining({ preserveSource: true })) - expect(read().documents[0]!.sourceProtected).toBe(false) - controller.recovery.dispose() - }) + files.save = mock(async () => ({ ok: false as const, reason: 'source-protected' as const })) + await expect(controller.save(read().activeProjectId, true)).rejects.toThrow() + expect(read().projectMetadata[read().activeProjectId]!.sourceProtected).toBe(true) - it('checkpoints edits without writing the source, then saves only on an explicit request', async () => { - const { controller, files, read, edit } = setup() - await controller.restore() - edit() - controller.schedule() - await controller.flush() - expect(files.save).not.toHaveBeenCalled() - expect(isPresentationDirty(read().documents[0]!)).toBe(true) - expect(await controller.save(read().activeDocumentId)).toBe(true) - expect(files.save).toHaveBeenCalledTimes(1) - expect(isPresentationDirty(read().documents[0]!)).toBe(false) - controller.recovery.dispose() + files.save = mock(async () => ({ ok: true as const, source: { path: '/Copy.pptx', mtimeMs: 43 }, fileName: 'Copy.pptx' })) + expect(await controller.save(read().activeProjectId, true)).toBe(true) + expect(files.save).toHaveBeenCalledWith(expect.objectContaining({ preserveSource: true, saveAs: true })) + expect(read().projectMetadata[read().activeProjectId]!.sourceProtected).toBe(false) + } finally { + controller.recovery.dispose() + } }) - it('does not clear newer edits made during saving', async () => { - const { controller, files, read, edit } = setup() - await controller.restore() - edit() - files.save = async () => { edit(); return { ok: true, source: { path: '/Report.pptx', mtimeMs: 43 }, fileName: 'Report.pptx' } } - expect(await controller.save(read().activeDocumentId)).toBe(false) - expect(isPresentationDirty(read().documents[0]!)).toBe(true) - controller.recovery.dispose() + + it('checkpoints project edits without writing PPTX and exports only on an explicit request', async () => { + const { controller, files, read, readRecovery, edit } = setup() + try { + await controller.restore() + edit() + controller.schedule() + await controller.flush() + + expect(files.save).not.toHaveBeenCalled() + const stored = JSON.parse(readRecovery()!) as PresentationCheckpoint + expect(stored.projectMetadata[read().activeProjectId]!.revision).toBe(read().projectMetadata[read().activeProjectId]!.revision) + expect(isPresentationProjectDirty(read().projectMetadata[read().activeProjectId]!)).toBe(true) + + expect(await controller.save(read().activeProjectId)).toBe(true) + expect(files.save).toHaveBeenCalledTimes(1) + expect(isPresentationProjectDirty(read().projectMetadata[read().activeProjectId]!)).toBe(false) + } finally { + controller.recovery.dispose() + } }) - it('canceled closing keeps the draft and never saves implicitly', async () => { + + it('does not acknowledge edits made while an explicit export is running', async () => { const { controller, files, read, edit } = setup() - await controller.restore() - edit() - expect(await controller.beforeClose(read().activeDocumentId)).toBe(false) - expect(files.save).not.toHaveBeenCalled() - controller.recovery.dispose() + try { + await controller.restore() + edit() + files.save = async () => { + edit() + return { ok: true, source: { path: '/Report.pptx', mtimeMs: 43 }, fileName: 'Report.pptx' } + } + + expect(await controller.save(read().activeProjectId)).toBe(false) + expect(isPresentationProjectDirty(read().projectMetadata[read().activeProjectId]!)).toBe(true) + } finally { + controller.recovery.dispose() + } }) -}) -it('retries a failed PPT recovery write after the source is saved and clears the failure only on success', async () => { - const status = mock(() => undefined) - const { controller, files, read, edit } = setup(true, status) - let fail = true - let checkpoint: string | null = null - files.setRecovery = mock(async (_kind, _session, value) => { - if (fail) throw new Error('Recovery unavailable') - checkpoint = value + it('retries a failed recovery checkpoint without implicitly exporting PPTX', async () => { + const { controller, files, edit } = setup() + let fail = true + files.setRecovery = mock(async () => { + if (fail) throw new Error('Recovery unavailable') + }) + try { + await controller.restore() + edit() + controller.schedule() + await expect(controller.flush()).rejects.toThrow('Recovery unavailable') + expect(files.save).not.toHaveBeenCalled() + + fail = false + await controller.flush() + expect(files.save).not.toHaveBeenCalled() + expect(controller.recovery.getSnapshot().status).toBe('saved') + } finally { + controller.recovery.dispose() + } }) - try { - await controller.restore() - edit() - controller.schedule() - await expect(controller.autoSave.flush()).rejects.toThrow('Recovery unavailable') - expect(isPresentationDirty(read().documents[0]!)).toBe(false) - expect(files.save).toHaveBeenCalledTimes(1) - await expect(controller.save(read().activeDocumentId)).rejects.toThrow('Recovery unavailable') - expect(status).toHaveBeenLastCalledWith('error', 'Recovery unavailable') - fail = false - expect(await controller.save(read().activeDocumentId)).toBe(true) - expect(JSON.parse(checkpoint!)).toEqual(read()) - expect(files.save).toHaveBeenCalledTimes(1) - expect(status).toHaveBeenLastCalledWith('saved') - expect(controller.recovery.getSnapshot().status).toBe('saved') - } finally { controller.autoSave.dispose(); controller.recovery.dispose() } -}) -it('keeps PPT edits made during a clean-file recovery retry pending', async () => { - const status = mock(() => undefined) - const { controller, files, read, edit } = setup(true, status) - try { - await controller.restore() - files.setRecovery = async () => { edit() } - expect(await controller.save(read().activeDocumentId)).toBe(false) - expect(isPresentationDirty(read().documents[0]!)).toBe(true) - expect(files.save).not.toHaveBeenCalled() - expect(status).toHaveBeenLastCalledWith('saving') - } finally { controller.autoSave.dispose(); controller.recovery.dispose() } -}) + it('does not repeat a successful PPTX export when only its recovery checkpoint failed', async () => { + const status = mock(() => undefined) + const { controller, files, read, edit } = setup(false, status) + let fail = true + files.setRecovery = mock(async () => { + if (fail) throw new Error('Recovery unavailable') + }) + try { + await controller.restore() + edit() + await expect(controller.save(read().activeProjectId)).rejects.toThrow('Recovery unavailable') + expect(files.save).toHaveBeenCalledTimes(1) + expect(isPresentationProjectDirty(read().projectMetadata[read().activeProjectId]!)).toBe(false) + expect(status).toHaveBeenLastCalledWith('error', 'Recovery unavailable') + fail = false + expect(await controller.save(read().activeProjectId)).toBe(true) + expect(files.save).toHaveBeenCalledTimes(1) + expect(status).toHaveBeenLastCalledWith('saved') + } finally { + controller.recovery.dispose() + } + }) -it('automatically saves PPT edits and retains a failed write for retry without a discard dialog', async () => { - const { controller, files, read, edit } = setup(true) - await controller.restore() - read().documents[0]!.sourceProtected = true - edit() - controller.schedule() - await controller.autoSave.flush() - expect(files.save).toHaveBeenCalledWith(expect.objectContaining({ managed: true, documentId: read().activeDocumentId })) - expect(isPresentationDirty(read().documents[0]!)).toBe(false) - files.save = async () => { throw new Error('disk full') } - edit() - controller.schedule() - await expect(controller.autoSave.flush()).rejects.toThrow('disk full') - await expect(controller.beforeClose(read().activeDocumentId)).rejects.toThrow('disk full') - expect(isPresentationDirty(read().documents[0]!)).toBe(true) - expect(files.confirmClose).not.toHaveBeenCalled() - files.save = async () => ({ ok: true, fileName: 'Report.pptx', source: { path: '/Report.pptx', mtimeMs: 44 } }) - await controller.autoSave.flush() - expect(isPresentationDirty(read().documents[0]!)).toBe(false) - controller.autoSave.dispose() - controller.recovery.dispose() -}) + it('keeps edits made during a clean-project recovery write pending', async () => { + const status = mock(() => undefined) + const { controller, files, read, edit } = setup(false, status) + try { + await controller.restore() + files.setRecovery = async () => { edit() } + expect(await controller.save(read().activeProjectId)).toBe(false) + expect(isPresentationProjectDirty(read().projectMetadata[read().activeProjectId]!)).toBe(true) + expect(files.save).not.toHaveBeenCalled() + expect(status).toHaveBeenLastCalledWith('saving') + } finally { + controller.recovery.dispose() + } + }) + it('rejects a recovery inventory whose active project is missing', async () => { + const { controller, read, writeRecovery } = setup() + writeRecovery(JSON.stringify({ ...read(), activeProjectId: 'missing-project' })) + try { + await expect(controller.restore()).rejects.toThrow('invalid project inventory') + } finally { + controller.recovery.dispose() + } + }) +}) -it('background PPT saves leave active text and IME input intact, while close commits the final text', async () => { - const document = { ...createBlankPresentationDocument('Report'), source: { path: '/Report.pptx', mtimeMs: 42 }, savedRevision: 0 } - let workspace: PresentationWorkspace = { activeDocumentId: document.id, documents: [document] } +it('explicit PPTX export commits active text but refuses incomplete IME composition', async () => { + let project: PresentationProject = createBlankPresentationProject('Report') + const source = { path: '/Report.pptx', mtimeMs: 42 } + let checkpoint: PresentationCheckpoint = { + schemaVersion: 1, + activeProjectId: project.id, + projects: [project], + projectMetadata: { [project.id]: { revision: 1, source, savedRevision: 0 } }, + } const writes: string[] = [] let exits = 0 const editing = { - isEditing: true, inCompositionMode: true, + isEditing: true, + inCompositionMode: true, exitEditing() { exits++ editing.isEditing = false - workspace = { ...workspace, documents: workspace.documents.map((item) => ({ ...item, revision: item.revision + 1, title: 'Completed text' })) } + project = { ...project, title: 'Completed text' } + const metadata = checkpoint.projectMetadata[project.id]! + checkpoint = { + ...checkpoint, + projects: [project], + projectMetadata: { [project.id]: { ...metadata, revision: metadata.revision + 1 } }, + } }, } - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 's', documentId: document.id }) - binding.attach(createPresentationEditorDriver({ readSnapshot: () => workspace.documents[0]!, readEditingObject: () => editing, flushPendingEdit: () => undefined, dispose: () => undefined })) + const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 's', documentId: project.id }) + binding.attach(createPresentationEditorDriver({ readSnapshot: () => project, readEditingObject: () => editing, flushPendingEdit: () => undefined, dispose: () => undefined })) const controller = createPresentationFileController({ - sessionId: 's', automatic: true, read: () => workspace, write: (next) => { workspace = next }, - flushEditor: binding.flush, encode: async (item) => new TextEncoder().encode(item.title), locale: () => 'en', + sessionId: 's', managed: true, read: () => checkpoint, + commitExport: (projectId, _fileName, nextSource, exportedRevision) => { + checkpoint = { + ...checkpoint, + projectMetadata: { [projectId]: { ...checkpoint.projectMetadata[projectId]!, source: nextSource, savedRevision: exportedRevision } }, + } + }, + flushEditor: binding.flush, encode: async (item) => new TextEncoder().encode(item.title), files: { - inspect: async () => document.source, - save: async (request) => { writes.push(new TextDecoder().decode(request.bytes)); return { ok: true, source: document.source, fileName: 'Report.pptx' } }, + inspect: async () => source, + save: async (request) => { writes.push(new TextDecoder().decode(request.bytes)); return { ok: true, source, fileName: 'Report.pptx' } }, getRecovery: async () => null, setRecovery: async () => undefined, confirmClose: async () => 'cancel', }, }) try { await controller.restore() - await controller.autoSave.flush() - expect(writes).toEqual(['Report']) - expect(editing.isEditing).toBe(true) + await expect(controller.flush()).rejects.toThrow('Finish composing') + await expect(controller.save(project.id)).rejects.toThrow('Finish composing') + expect(writes).toEqual([]) expect(exits).toBe(0) - await expect(controller.beforeClose(document.id)).rejects.toThrow('Finish composing') + editing.inCompositionMode = false - expect(await controller.beforeClose(document.id)).toBe(true) + expect(await controller.save(project.id)).toBe(true) expect(exits).toBe(1) - expect(writes).toEqual(['Report', 'Completed text']) - } finally { controller.autoSave.dispose(); controller.recovery.dispose(); binding.dispose() } + expect(writes).toEqual(['Completed text']) + } finally { + controller.recovery.dispose() + binding.dispose() + } }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationMarkdown.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationMarkdown.test.ts index ab6bff98..52092c85 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationMarkdown.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationMarkdown.test.ts @@ -1,469 +1,74 @@ import { describe, expect, it } from 'bun:test' -import { createBlankPresentationDocument, presentationSlideBackground } from '@/atoms/presentation' -import { - compilePresentationElementMarkdown, - compilePresentationMarkdown, - compilePresentationSlideMarkdown, - decompilePresentationSlideMarkdown, - inspectPresentationMarkdownAssets, -} from '../presentationMarkdown' +import { createBlankPresentationProject } from '@/atoms/presentation' +import { createPresentationAsset } from '@/presentation/project' +import { decompilePresentationSlideMarkdown } from '../presentationMarkdown' -describe('presentation Markdown compiler', () => { - it('inherits document-wide typography and palette for later semantic pages', () => { - const document = createBlankPresentationDocument('Designed deck') - document.theme = { - ...document.theme, - accentColors: ['#CC5500', '#118844'], - background: '#17182B', - bodyFontFamily: 'Arial', - titleFontFamily: 'Georgia', - } - const compiled = compilePresentationSlideMarkdown(`--- -id: designed ---- - -# A designed title - -Supporting evidence - -`, { document }).slide - - expect(compiled.elements[0]).toMatchObject({ color: '#FFFFFF', fontFamily: 'Georgia' }) - expect(compiled.background).toBeUndefined() - expect(presentationSlideBackground(document.theme, compiled)).toBe('#17182B') - expect(compiled.elements[1]).toMatchObject({ color: '#C7C8D8', fontFamily: 'Arial' }) - expect(compiled.elements[2]).toMatchObject({ fill: '#CC5500', borderColor: '#CC5500' }) - }) - - it('uses a page background override when deriving editable text and table colors', () => { - const document = createBlankPresentationDocument('Mixed-background deck') - document.theme = { ...document.theme, background: '#FFFFFF', accentColors: ['#CC5500'] } - const slide = compilePresentationSlideMarkdown(`--- -id: dark-page -background: '#17182B' ---- - -# Visible title - -| Metric | Value | -| --- | ---: | -| ARR | 42 |`, { document }).slide - - expect(slide.elements[0]).toMatchObject({ type: 'text', color: '#FFFFFF' }) - expect(slide.elements[1]).toMatchObject({ - type: 'table', - headerFill: '#CC5500', - bodyFill: '#17182B', - textColor: '#FFFFFF', - }) - - const fragmentSlide = { ...document.slides.pages[0]!, background: '#17182B' } - const fragment = compilePresentationElementMarkdown('Supporting evidence', { - document, - slide: fragmentSlide, - }).element - expect(fragment).toMatchObject({ type: 'text', color: '#C7C8D8' }) - }) - - it('keeps inherited page styling out of canonical slide Markdown', () => { - const document = createBlankPresentationDocument('Inherited page') - document.theme = { - ...document.theme, - background: '#17182B', - footer: { text: 'Global footer', showDate: false, showSlideNumber: true }, - } +describe('PowerPoint compact Markdown projection', () => { + it('keeps stable refs and authored text while omitting routine native layout', () => { + const document = createBlankPresentationProject('Review') const slide = document.slides.pages[0]! + slide.name = 'Executive summary' + slide.elements = [{ + id: 'title', type: 'text', text: 'Revenue\nup 20%', x: 37, y: 91, width: 620, height: 110, rotation: 4, + fontSize: 44, fontFamily: 'Arial', fontWeight: 700, color: '#112233', align: 'center', + }] const markdown = decompilePresentationSlideMarkdown(slide, document) - const roundTripped = compilePresentationSlideMarkdown(markdown, { document }).slide - - expect(markdown).not.toContain('background:') - expect(markdown).not.toContain('footer:') - expect(roundTripped.background).toBeUndefined() - expect(roundTripped.footer).toBeUndefined() - expect(presentationSlideBackground(document.theme, roundTripped)).toBe('#17182B') - }) - - it('uses a deck theme immediately while compiling its first inherited page', () => { - const compiled = compilePresentationMarkdown(`--- -title: Dark deck -theme: - background: '#17182B' - titleFontFamily: Georgia - bodyFontFamily: Arial ---- - -# Visible title - -Visible body`).document - const slide = compiled.slides.pages[0]! - - expect(slide.background).toBeUndefined() - expect(slide.elements[0]).toMatchObject({ color: '#FFFFFF', fontFamily: 'Georgia' }) - expect(slide.elements[1]).toMatchObject({ color: '#C7C8D8', fontFamily: 'Arial' }) - }) - - it('compiles Slidev framing, YAML, Markdown blocks, slots, tables, and notes', () => { - const markdown = `--- -title: Product review -pageSize: wide -id: cover -name: Cover -layout: title ---- - -# Product review {#title} - -One native presentation model. - ---- -id: metrics -name: Metrics -layout: two-cols ---- - -::left:: - -- ARR grew 42% -- NRR reached 118% - -::right:: - -| Quarter | ARR | -| --- | ---: | -| Q3 | 25 | - -` - const compiled = compilePresentationMarkdown(markdown).document - - expect(compiled.title).toBe('Product review') - expect(compiled.slides.pages.map((slide) => slide.id)).toEqual(['cover', 'metrics']) - expect(compiled.slides.pages[0]!.elements[0]).toMatchObject({ id: 'title', type: 'text', text: 'Product review' }) - expect(compiled.slides.pages[1]!.layout).toBe('twoContent') - expect(compiled.slides.pages[1]!.elements.map((element) => element.type)).toEqual(['text', 'table']) - expect(compiled.slides.pages[1]!.elements[0]!.x).toBeLessThan(compiled.pageSize.width / 2) - expect(compiled.slides.pages[1]!.elements[1]!.x).toBeGreaterThan(compiled.pageSize.width / 2) - expect(compiled.slides.pages[1]!.notes).toBe('Pause on retention.') - }) - - it('does not split slides on delimiters inside YAML literals, fences, comments, or native components', () => { - const markdown = `--- -title: |- - A title - --- -id: one ---- - -\`\`\`md ---- - -\`\`\` - - - - ---- -` - const compiled = compilePresentationMarkdown(markdown).document - - expect(compiled.slides.pages).toHaveLength(1) - expect(compiled.slides.pages[0]!.elements).toHaveLength(2) - expect(compiled.slides.pages[0]!.elements[0]).toHaveProperty('text', '---\n') - expect(compiled.slides.pages[0]!.elements[1]).toMatchObject({ id: 'rule', text: '---' }) - expect(inspectPresentationMarkdownAssets(markdown)).toEqual([]) + expect(markdown).toContain('id: slide-') + expect(markdown).toContain('name: Executive summary') + expect(markdown).toContain('') + expect(markdown).toContain('Revenue up 20%') + expect(markdown).not.toContain('x="37"') + expect(markdown).not.toContain('fontSize="44"') }) - it('honors fence length and multiline self-closing components while framing slides', () => { - const fenced = `--- -id: fenced ---- - -~~~~md ---- -~~~ ---- -~~~~` - const fencedDocument = compilePresentationMarkdown(fenced).document - expect(fencedDocument.slides.pages).toHaveLength(1) - expect(fencedDocument.slides.pages[0]!.elements[0]).toHaveProperty('text', '---\n~~~\n---') - - const multilineComponent = `--- -id: first ---- - - - ---- -id: second ---- - -# Second` - const componentDocument = compilePresentationMarkdown(multilineComponent).document - expect(componentDocument.slides.pages.map((slide) => slide.id)).toEqual(['first', 'second']) - expect(componentDocument.slides.pages[0]!.elements[0]).toMatchObject({ id: 'shape', type: 'rect' }) - }) - - it('compiles adjacent native components emitted in one HTML token', () => { - const markdown = `--- -id: adjacent ---- - - -Summary` - - const document = compilePresentationMarkdown(markdown).document - expect(document.slides.pages[0]!.elements).toHaveLength(2) - expect(document.slides.pages[0]!.elements.map((element) => element.id)).toEqual(['panel', 'label']) - }) - - it('round-trips every native element family through canonical Markdown without base64', () => { - const existing = createBlankPresentationDocument('Imported deck') - existing.assets = [ - { id: 'image-asset', kind: 'image', name: 'image.png', source: { dataUrl: 'data:image/png;base64,aW1hZ2U=', fileName: 'image.png', mimeType: 'image/png' } }, - { id: 'audio-asset', kind: 'audio', name: 'audio.mp3', source: { dataUrl: 'data:audio/mpeg;base64,YXVkaW8=', fileName: 'audio.mp3', mimeType: 'audio/mpeg' } }, - { id: 'video-asset', kind: 'video', name: 'video.mp4', source: { dataUrl: 'data:video/mp4;base64,dmlkZW8=', fileName: 'video.mp4', mimeType: 'video/mp4' } }, + it('uses workspace paths for linked media and opaque refs for embedded media', () => { + const document = createBlankPresentationProject('Media') + const slide = document.slides.pages[0]! + document.assets = [ + createPresentationAsset('image', { + assetId: 'linked', dataUrl: 'data:image/png;base64,cG5n', fileName: 'linked.png', mimeType: 'image/png', path: 'assets/linked.png', + }), + createPresentationAsset('image', { + assetId: 'embedded', dataUrl: 'data:image/png;base64,cG5n', fileName: 'embedded.png', mimeType: 'image/png', + }), ] - const slide = existing.slides.pages[0]! - slide.id = 'imported' - slide.name = 'Imported' - existing.slides.selectedPageId = slide.id - slide.notes = 'Speaker note' slide.elements = [ - { - id: 'text', - type: 'text', - text: ' Revenue & ', - x: 20, - y: 20, - width: 300, - height: 80, - rotation: 4, - flipHorizontal: true, - fontSize: 30, - fontFamily: 'Inter', - fontWeight: 700, - color: '#112233', - align: 'center', - textDirection: 'eastAsianVertical', - animation: 'fade', - animationStart: 'afterPrevious', - }, - { - id: 'shape', - type: 'roundRect', - x: 30, - y: 120, - width: 220, - height: 100, - rotation: 0, - fill: '#FF0000', - borderColor: '#000000', - borderWidth: 2, - }, - { - id: 'image', - type: 'image', - sourceAssetId: 'image-asset', - altText: 'Hero', - fit: 'cover', - clipShape: 'ellipse', - x: 280, - y: 120, - width: 300, - height: 180, - rotation: 0, - flipVertical: true, - }, - { - id: 'audio', - type: 'audio', - sourceAssetId: 'audio-asset', - autoplay: false, - loop: true, - muted: false, - x: 20, - y: 320, - width: 240, - height: 80, - rotation: 0, - }, - { - id: 'video', - type: 'video', - sourceAssetId: 'video-asset', - autoplay: false, - loop: false, - muted: true, - x: 280, - y: 320, - width: 300, - height: 180, - rotation: 0, - }, - { - id: 'table', - type: 'table', - cells: [['Name', 'Value'], ['A|B', 'Line 1\nLine 2']], - headerRow: true, - headerFill: '#EEEEEE', - bodyFill: '#FFFFFF', - textColor: '#111111', - borderColor: '#999999', - fontSize: 18, - x: 610, - y: 20, - width: 400, - height: 180, - rotation: 0, - }, - { - id: 'chart', - type: 'chart', - chartType: 'line', - categories: ['Q1', 'Q2'], - series: [{ name: 'ARR', values: [12, 18] }], - showLegend: true, - colors: ['#5B67F1'], - x: 610, - y: 230, - width: 500, - height: 300, - rotation: 0, - }, + { id: 'linked-image', type: 'image', sourceAssetId: 'linked', altText: 'Linked', fit: 'cover', x: 0, y: 0, width: 100, height: 100, rotation: 0 }, + { id: 'embedded-image', type: 'image', sourceAssetId: 'embedded', altText: 'Embedded', fit: 'contain', x: 100, y: 0, width: 100, height: 100, rotation: 0 }, ] - - const markdown = decompilePresentationSlideMarkdown(slide, existing) - expect(markdown).toContain(' element.type)).toEqual( - existing.slides.pages[0]!.elements.map((element) => element.type), - ) - expect(roundTripped.slides.pages[0]!.elements[0]).toMatchObject({ - id: 'text', - text: ' Revenue & ', - animation: 'fade', - animationStart: 'afterPrevious', - flipHorizontal: true, - textDirection: 'eastAsianVertical', - }) - expect(roundTripped.slides.pages[0]!.elements[2]).toMatchObject({ id: 'image', flipVertical: true, clipShape: 'ellipse' }) - expect(roundTripped.slides.pages[0]!.elements[5]).toMatchObject({ - id: 'table', - cells: [['Name', 'Value'], ['A|B', 'Line 1\nLine 2']], - }) - expect(roundTripped.slides.pages[0]!.elements[6]).toMatchObject({ - id: 'chart', - categories: ['Q1', 'Q2'], - series: [{ name: 'ARR', values: [12, 18] }], - }) + it('projects tables, charts, notes, and non-default page metadata', () => { + const document = createBlankPresentationProject('Data') + const slide = document.slides.pages[0]! + slide.background = '#123456' + slide.notes = 'Explain the growth assumptions.' + slide.footer = { text: 'Confidential', showDate: false, showSlideNumber: true } + slide.transition = { effect: 'fade', durationMs: 500 } + slide.elements = [ + { id: 'table', type: 'table', x: 0, y: 0, width: 500, height: 200, rotation: 0, cells: [['A', 'B'], ['1', '2']], headerRow: true, headerFill: '#000000', bodyFill: '#FFFFFF', textColor: '#111111', borderColor: '#CCCCCC', fontSize: 18 }, + { id: 'chart', type: 'chart', x: 0, y: 220, width: 500, height: 300, rotation: 0, chartType: 'column', categories: ['A'], series: [{ name: 'Revenue', values: [10] }], showLegend: false, colors: ['#123456'], title: 'Growth' }, + ] + const markdown = decompilePresentationSlideMarkdown(slide, document) + expect(markdown).toContain("background: '#123456'") + expect(markdown).toContain('effect: fade') + expect(markdown).toContain('') + expect(markdown).toContain('| A | B |') + expect(markdown).toContain('') + expect(markdown).toContain('') }) - it('compiles a single editable fragment while preserving or assigning its ref', () => { - const document = createBlankPresentationDocument('Element edits') + it('fails loudly when a media element refers to a missing asset', () => { + const document = createBlankPresentationProject('Broken') const slide = document.slides.pages[0]! slide.elements = [{ - id: 'title', type: 'text', text: 'Before', x: 20, y: 20, width: 300, height: 60, - rotation: 0, fontSize: 30, fontFamily: 'Aptos', fontWeight: 700, color: '#111111', align: 'left', + id: 'hero', type: 'image', sourceAssetId: 'missing', altText: 'Hero', fit: 'cover', + x: 0, y: 0, width: 100, height: 100, rotation: 0, }] - - const edited = compilePresentationElementMarkdown( - 'After', - { document, elementId: 'title', slide }, - ).element - const inserted = compilePresentationElementMarkdown( - '', - { document, slide }, - ).element - - expect(edited).toMatchObject({ id: 'title', text: 'After' }) - expect(inserted.id).not.toBe('title') - expect(() => compilePresentationElementMarkdown('Duplicate', { - document, - slide, - })).toThrow('must not provide id or ref') - }) - - it('uses one parser for local asset discovery and compilation', () => { - const markdown = `--- -id: media ---- - -![Hero](assets/hero.png) - -` - const textWithImageSyntax = [markdown, '![Not media](ignored.png)'].join('\n\n') - expect(inspectPresentationMarkdownAssets(textWithImageSyntax)).toEqual(['assets/hero.png', 'media/voice.mp3']) - expect(() => compilePresentationMarkdown(markdown)).toThrow('asset was not registered') - - const document = compilePresentationMarkdown(markdown, { - assets: { - 'assets/hero.png': { - assetId: 'asset-image', - dataUrl: 'bridgic-resource://hero', - fileName: 'hero.png', - mimeType: 'image/png', - path: 'assets/hero.png', - }, - 'media/voice.mp3': { - assetId: 'asset-audio', - dataUrl: 'bridgic-resource://voice', - fileName: 'voice.mp3', - mimeType: 'audio/mpeg', - path: 'media/voice.mp3', - }, - }, - }).document - expect(document.slides.pages[0]!.elements.map((element) => element.type)).toEqual(['image', 'audio']) - expect(inspectPresentationMarkdownAssets('')).toEqual([ - 'assets/detail.png', - ]) - expect(inspectPresentationMarkdownAssets('')).toEqual([]) - }) - - it('rejects duplicate refs, unknown component attributes, and arbitrary executable Vue', () => { - expect(() => compilePresentationMarkdown(`--- -id: duplicate ---- - -# One {#same} - -# Two {#same}`)).toThrow('Duplicate element ref') - expect(() => compilePresentationMarkdown(`--- -id: typo ---- - -Title`)).toThrow('Unsupported PptText attribute: widht') - expect(() => compilePresentationMarkdown(`--- -id: unsafe ---- - -`)).toThrow('Unsupported HTML or Vue block') - }) - - it('accepts style blocks as inert input and reports that they were not executed', () => { - const compiled = compilePresentationMarkdown(`--- -id: styled ---- - - - -# Native title`) - expect(compiled.document.slides.pages[0]!.elements).toHaveLength(1) - expect(compiled.diagnostics[0]).toContain('accepted but ignored') + expect(() => decompilePresentationSlideMarkdown(slide, document)).toThrow('has no source asset') }) }) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPersistence.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPersistence.test.ts deleted file mode 100644 index 92a21d5d..00000000 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPersistence.test.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { describe, expect, it } from 'bun:test' -import { createBlankPresentationDocument, type PresentationWorkspace } from '@/atoms/presentation' -import { createPresentationPersistence } from '../presentationPersistence' -import { createPresentationWorkspaceRuntime } from '../presentationWorkspaceRuntime' - -function workspace(title: string, revision = 1): PresentationWorkspace { - const document = { ...createBlankPresentationDocument(title), revision } - return { activeDocumentId: document.id, documents: [document] } -} - -function changed(state: PresentationWorkspace, title: string): PresentationWorkspace { - return { ...state, documents: state.documents.map((document) => ({ ...document, title, revision: document.revision + 1 })) } -} - -function deferred() { - let resolve!: () => void - let reject!: (error: unknown) => void - const promise = new Promise((yes, no) => { resolve = yes; reject = no }) - return { promise, resolve, reject } -} - -describe('presentation source persistence', () => { - it('declares source-file storage and does not write unbound or newly created UI tabs', async () => { - const writes: string[] = [] - const persistence = createPresentationPersistence({ sessionId: 'session-a', encode: async () => new Uint8Array(), write: async (path) => { writes.push(path) } }) - const first = workspace('Source') - await persistence.persist(first) - persistence.bindTarget('/tmp/source.pptx', first, true) - const blank = workspace('Untitled') - const tabs = { activeDocumentId: blank.activeDocumentId, documents: [...first.documents, ...blank.documents] } - await persistence.persist(tabs) - expect(writes).toEqual([]) - expect(persistence.targetFor(tabs)).toBeNull() - expect(persistence.targetFor(first)).toBe('/tmp/source.pptx') - expect(persistence.getSnapshot().policy).toEqual({ appKind: 'presentation', sessionId: 'session-a', kind: 'source', storage: 'source-file', automatic: true }) - }) - - it('returns the same actual write receipt to autosave and a matching protocol checkpoint', async () => { - const gate = deferred() - let writes = 0 - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => { writes += 1; await gate.promise } }) - const state = workspace('Source') - persistence.bindTarget('/tmp/source.pptx', state, false) - const autosave = persistence.persist(state) - const protocol = persistence.persist(state) - expect(protocol).toBe(autosave) - let settled = false - void protocol.then(() => { settled = true }) - await Promise.resolve() - await Promise.resolve() - expect(writes).toBe(1) - expect(settled).toBe(false) - gate.resolve() - await protocol - expect(settled).toBe(true) - await persistence.persist(state) - expect(writes).toBe(1) - }) - - it('keeps same-target revision writes ordered and waits for each receipt', async () => { - const firstGate = deferred() - const written: number[] = [] - const persistence = createPresentationPersistence({ - sessionId: 's', encode: async (document) => new Uint8Array([document.revision]), - write: async (_path, bytes) => { written.push(bytes[0]!); if (bytes[0] === 1) await firstGate.promise }, - }) - const state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - const first = persistence.persist(state) - const second = persistence.persist(changed(state, 'Second')) - await Promise.resolve() - await Promise.resolve() - expect(written).toEqual([1]) - firstGate.resolve() - await Promise.all([first, second]) - expect(written).toEqual([1, 2]) - }) - - it('lets a newer queued write settle after an older autosave fails', async () => { - const gate = deferred() - const written: number[] = [] - const persistence = createPresentationPersistence({ - sessionId: 's', encode: async (document) => new Uint8Array([document.revision]), - write: async (_path, bytes) => { written.push(bytes[0]!); if (bytes[0] === 1) await gate.promise }, - }) - const state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - const first = persistence.persist(state) - const firstOutcome = first.then(() => 'saved', () => 'failed') - const second = persistence.persist(changed(state, 'Second')) - gate.reject(new Error('First write failed')) - expect(await firstOutcome).toBe('failed') - await second - await persistence.flush() - expect(written).toEqual([1, 2]) - expect(persistence.getSnapshot().status).toBe('saved') - }) - - it('retains the latest failed write for an explicit retry and does not write bytes on encoding failure', async () => { - let encodes = 0 - let writes = 0 - const persistence = createPresentationPersistence({ - sessionId: 's', encode: async () => { if (++encodes === 1) throw new Error('Encoding failed'); return new Uint8Array() }, - write: async () => { writes += 1 }, - }) - const state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - await expect(persistence.persist(state)).rejects.toThrow('Encoding failed') - expect(writes).toBe(0) - await persistence.flush() - expect(writes).toBe(1) - expect(encodes).toBe(2) - expect(persistence.getSnapshot().status).toBe('saved') - }) - - it.each(['complete', 'fail'] as const)('keeps a previous target %s from changing a newly imported target baseline', async (outcome) => { - const gate = deferred() - const writes: string[] = [] - const persistence = createPresentationPersistence({ - sessionId: 's', encode: async () => new Uint8Array(), - write: async (target) => { writes.push(target); if (target === '/tmp/first.pptx') await gate.promise }, - }) - const first = workspace('First') - persistence.bindTarget('/tmp/first.pptx', first, false) - const pending = persistence.persist(first) - const completed = pending.then(() => undefined, () => undefined) - const second = workspace('Second') - persistence.bindTarget('/tmp/second.pptx', second, true) - const secondStatus = persistence.getSnapshot() - if (outcome === 'complete') gate.resolve() - else gate.reject(new Error('Old destination unavailable')) - await completed - await persistence.persist(second) - expect(persistence.getSnapshot()).toBe(secondStatus) - expect(persistence.getSnapshot().status).toBe('saved') - expect(writes).toEqual(['/tmp/first.pptx']) - }) - - it('continues a different target while an older destination is still saving', async () => { - const gate = deferred() - const writes: string[] = [] - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async (target) => { writes.push(target); if (target === '/tmp/first.pptx') await gate.promise } }) - const first = workspace('First') - persistence.bindTarget('/tmp/first.pptx', first, false) - const pending = persistence.persist(first) - const second = workspace('Second') - persistence.bindTarget('/tmp/second.pptx', second, false) - await persistence.persist(second) - expect(writes).toEqual(['/tmp/first.pptx', '/tmp/second.pptx']) - gate.resolve() - await pending - }) - - it('includes native edits made during a close checkpoint before acknowledging the close', async () => { - const gate = deferred() - const written: number[] = [] - const persistence = createPresentationPersistence({ sessionId: 's', encode: async (document) => new Uint8Array([document.revision]), write: async (_path, bytes) => { written.push(bytes[0]!); if (bytes[0] === 1) await gate.promise } }) - let state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - let closed = false - const checkpoint = persistence.checkpoint(() => state).then(() => { closed = true }) - state = changed(state, 'Typed while saving') - expect(closed).toBe(false) - gate.resolve() - await checkpoint - expect(written).toEqual([1, 2]) - expect(closed).toBe(true) - }) - - it('rejects a failed close checkpoint so its caller can preserve the editor', async () => { - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => { throw new Error('Disk unavailable') } }) - const state = workspace('First') - persistence.bindTarget('/tmp/source.pptx', state, false) - let closed = false - await expect(persistence.checkpoint(() => state).then(() => { closed = true })).rejects.toThrow('Disk unavailable') - expect(closed).toBe(false) - }) - - it('returns view_ppt to its existing source document after the user selects an unbound tab', async () => { - let writes = 0 - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => { writes += 1 } }) - const source = workspace('Source') - const blank = workspace('New UI tab') - persistence.bindTarget('/tmp/source.pptx', source, true) - let state = { activeDocumentId: blank.activeDocumentId, documents: [...source.documents, ...blank.documents] } - const controller = createPresentationWorkspaceRuntime({ sessionId: 's', read: () => state, write: (next) => { state = next } }) - const result = await controller.dispatchProtocol( - { method: 'view_ppt', params: { target: '/tmp/source.pptx', file_name: 'source.pptx', content_base64: 'Not reread for a reused document' } }, - () => ({ currentTarget: persistence.targetFor(state), fileName: 'source.pptx' }), - async () => undefined, - (request) => persistence.prepareProtocol(request, () => state, (next) => { state = next }), - ) - expect(result).toMatchObject({ ok: true, value: { reused: true, identity: { document_id: source.activeDocumentId } } }) - expect(state.activeDocumentId).toBe(source.activeDocumentId) - expect(state.documents).toHaveLength(2) - expect(writes).toBe(0) - }) - - it('rejects source mutations before they can modify an unbound UI tab', async () => { - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => undefined }) - const state = workspace('Unbound') - let commits = 0 - const controller = createPresentationWorkspaceRuntime({ sessionId: 's', read: () => state, write: () => { commits += 1 } }) - const result = await controller.dispatchProtocol( - { method: 'insert_ppt_page', params: { markdown: 'Must not be applied' } }, - () => ({ currentTarget: null, fileName: 'Unbound.pptx' }), - async () => { commits += 1 }, - (request) => persistence.prepareProtocol(request, () => state, () => { commits += 1 }), - ) - expect(result).toMatchObject({ ok: false, code: 'document_changed' }) - expect(commits).toBe(0) - expect(state.documents[0]!.slides.pages).toHaveLength(1) - }) - - it('requires fresh source bytes when reopening a replaced document with pending writes', async () => { - const gate = deferred() - const persistence = createPresentationPersistence({ sessionId: 's', encode: async () => new Uint8Array(), write: async () => gate.promise }) - const first = workspace('First') - persistence.bindTarget('/tmp/first.pptx', first, false) - const pending = persistence.persist(first) - const second = workspace('Second') - persistence.bindTarget('/tmp/second.pptx', second, true) - const request = { method: 'view_ppt' as const, params: { target: '/tmp/first.pptx', file_name: 'first.pptx', content_base64: 'Previously read bytes' } } - let writesToWorkspace = 0 - const preparation = persistence.prepareProtocol(request, () => second, () => { writesToWorkspace += 1 }) - gate.resolve() - await pending - await expect(preparation).rejects.toMatchObject({ code: 'document_changed' }) - expect(persistence.targetFor(second)).toBe('/tmp/second.pptx') - expect(writesToWorkspace).toBe(0) - await persistence.prepareProtocol(request, () => second, () => { writesToWorkspace += 1 }) - expect(writesToWorkspace).toBe(0) - }) -}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptx.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptx.test.ts index eeddeb46..208c0e8e 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptx.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptx.test.ts @@ -4,14 +4,14 @@ import { DOMParser } from '@xmldom/xmldom' import { PRESENTATION_PAGE_SIZES, createBlankPresentationSlide, - createInitialPresentationDocument as createEmptyPresentationDocument, + createInitialPresentationProject as createEmptyPresentationProject, type PresentationAsset, type PresentationAssetKind, type PresentationElement, type PresentationFileSource, type PresentationTransition, } from '@/atoms/presentation' -import { createPresentationTestDocument as createInitialPresentationDocument } from '@/test-fixtures/presentation' +import { createPresentationTestDocument as createInitialPresentationProject } from '@/test-fixtures/presentation' import { createPresentationPptx } from '../presentationPptx' function presentationAsset(id: string, kind: PresentationAssetKind, source: PresentationFileSource): PresentationAsset { @@ -20,7 +20,7 @@ function presentationAsset(id: string, kind: PresentationAssetKind, source: Pres describe('createPresentationPptx', () => { async function exportTransitionSlides(transitions: PresentationTransition[]): Promise { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() document.slides.pages = transitions.map((transition, index) => ({ ...createBlankPresentationSlide(`Transition ${index + 1}`), id: `transition-slide-${index + 1}`, @@ -37,7 +37,7 @@ describe('createPresentationPptx', () => { } it('does not export empty text boxes as slide content', async () => { - const document = createEmptyPresentationDocument() + const document = createEmptyPresentationProject() document.slides.pages[0]!.elements = [{ id: 'empty-title-placeholder', type: 'text', @@ -62,7 +62,7 @@ describe('createPresentationPptx', () => { }) it('exports inherited theme background and footer without page copies', async () => { - const document = createEmptyPresentationDocument() + const document = createEmptyPresentationProject() document.theme = { ...document.theme, background: '#112233', @@ -80,7 +80,7 @@ describe('createPresentationPptx', () => { }) it('exports every slide into a valid PowerPoint Open XML archive', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const title = document.slides.pages[0]?.elements.find((element) => element.type === 'text') if (document.slides.pages[0]) { document.slides.pages[0].notes = 'Speaker note exported from Bridgic.' @@ -154,7 +154,7 @@ describe('createPresentationPptx', () => { }) it('exports the document page size instead of forcing widescreen', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() document.pageSize = PRESENTATION_PAGE_SIZES.standard const archive = await JSZip.loadAsync(await createPresentationPptx(document)) @@ -164,7 +164,7 @@ describe('createPresentationPptx', () => { }) it('exports element animations as native PowerPoint timing targeted by object id', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const slide = document.slides.pages[0]! const title = slide.elements.find((element) => element.type === 'text')! title.animation = 'fade' @@ -295,7 +295,7 @@ describe('createPresentationPptx', () => { }) it('exports grouped card members in one synchronized native animation step', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const slide = document.slides.pages[0]! slide.elements = [ { @@ -370,7 +370,7 @@ describe('createPresentationPptx', () => { }) it('preserves after-previous steps when a with-previous effect follows them', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const slide = document.slides.pages[0]! const animatedShape = (id: string, animationStart: 'onClick' | 'withPrevious' | 'afterPrevious', animation: 'fade' | 'appear' | 'disappear', duration: number, x: number): PresentationElement => ({ id, @@ -411,7 +411,7 @@ describe('createPresentationPptx', () => { }) it('exports hyperlinks, embedded media, editable tables and charts, and slide footers', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() const sourceSlide = document.slides.pages[0]! const targetSlide = document.slides.pages[1]! const pngDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Z5QAAAABJRU5ErkJggg==' @@ -678,7 +678,7 @@ describe('createPresentationPptx', () => { }) it('canonicalizes QuickTime content types without relying on audio or transitions', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() document.assets.push(presentationAsset('quicktime-only-asset', 'video', { dataUrl: 'data:video/quicktime;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDE=', fileName: 'quicktime-only.mov', @@ -707,7 +707,7 @@ describe('createPresentationPptx', () => { }) it('skips malformed legacy elements and dangling hyperlinks without failing export', async () => { - const document = createInitialPresentationDocument() + const document = createInitialPresentationProject() document.assets.push( presentationAsset('broken-image-asset', 'image', { dataUrl: 'not-a-data-url', fileName: 'broken.png', mimeType: 'image/png' }), presentationAsset('mismatched-image-asset', 'image', { diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxDisplay.test.tsx b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxDisplay.test.tsx index c9403eed..a81725d1 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxDisplay.test.tsx +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxDisplay.test.tsx @@ -5,10 +5,10 @@ import { PresentationSlidePreview } from '../../components/app/PresentationSlide import { importPresentationPptx } from '../presentationPptxImport' import { createPresentationPptx } from '../presentationPptx' import { presentationTextStyleAt, presentationTextDisplaySegments } from '../presentationText' -import { createBlankPresentationDocument, layoutPresentationVerticalText } from '../../atoms/presentation' +import { createBlankPresentationProject, layoutPresentationVerticalText, type PresentationProject } from '../../atoms/presentation' import { DOMParser, XMLSerializer } from '@xmldom/xmldom' -import { compilePresentationSlideMarkdown, decompilePresentationSlideMarkdown } from '../presentationMarkdown' import { presentationElementSource } from '@/presentation/project' +import { editPresentationPage } from '@/presentation/agentCommands' const ns = 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"' const emu = (px: number) => Math.round(px * 9525) @@ -39,9 +39,15 @@ function firstText(model: Awaited>) { return text } +function agentEdit(model: PresentationProject): PresentationProject { + const page = model.slides.pages[0]! + const element = page.elements[0]! + return editPresentationPage(model, page.id, [{ type: 'patch', id: element.id, element_type: element.type, patch: { x: element.x } }]).project +} + describe('PowerPoint display fidelity', () => { it('renders theme background and footer when a page has no local overrides', () => { - const model = createBlankPresentationDocument('Theme preview') + const model = createBlankPresentationProject('Theme preview') model.theme = { ...model.theme, background: '#17182B', @@ -57,7 +63,7 @@ describe('PowerPoint display fidelity', () => { }) it.each([0, 1, 2])('keeps category/value indices when chart point %s is absent', async (missingIndex) => { - const model = createBlankPresentationDocument('Sparse data') + const model = createBlankPresentationProject('Sparse data') model.slides.pages[0]!.elements = [{ id: 'chart', type: 'chart', chartType: 'column', x: 100, y: 100, width: 800, height: 400, rotation: 0, categories: ['Jan', 'Feb', 'Mar'], series: [{ name: 'North', values: [10, 20, 30] }, { name: 'South', values: [40, 50, 60] }], colors: ['#2266EE', '#00AA88'], showLegend: true }] const zip = await JSZip.loadAsync(await createPresentationPptx(model)) @@ -83,7 +89,7 @@ describe('PowerPoint display fidelity', () => { }) it.each(['', ''])('retains sparse indices without relying on an ordered or complete cache (%s)', async (count) => { - const model = createBlankPresentationDocument('Unordered cache') + const model = createBlankPresentationProject('Unordered cache') model.slides.pages[0]!.elements = [{ id: 'chart', type: 'chart', chartType: 'line', x: 100, y: 100, width: 800, height: 400, rotation: 0, categories: ['Jan', 'Feb', 'Mar'], series: [{ name: 'Sales', values: [10, 20, 30] }], colors: ['#2266EE'], showLegend: true }] const zip = await JSZip.loadAsync(await createPresentationPptx(model)) @@ -103,7 +109,7 @@ describe('PowerPoint display fidelity', () => { expect(original.connectorPath).toStartWith('M 0 0 L 100 100') expect(original.connectorPath!.match(/ M /g)?.length).toBe(ends === 'both' ? 2 : 1) for (let round = 0; round < 2; round++) { - model.slides.pages = [compilePresentationSlideMarkdown(decompilePresentationSlideMarkdown(model.slides.pages[0]!), { document: model }).slide] + model = agentEdit(model) model = await importPresentationPptx(await createPresentationPptx(model)) const arrow = model.slides.pages[0]!.elements[0]! if (!('connectorPath' in arrow)) throw new Error('Lost arrow geometry') @@ -127,7 +133,7 @@ describe('PowerPoint display fidelity', () => { if (headerRow) expect(table).toMatchObject({ headerTextColor: '#000000', headerFill: '#FFFFFF' }) const markup = new DOMParser().parseFromString(preview(model), 'text/html') expect(markup.getElementsByTagName('td')[0]!.getAttribute('style')).toContain('color:#000000') - const edited = compilePresentationSlideMarkdown(decompilePresentationSlideMarkdown(model.slides.pages[0]!), { document: model }).slide + const edited = agentEdit(model).slides.pages[0]! expect(edited.elements[0]).toMatchObject({ headerRow, ...(headerRow ? { headerTextColor: '#000000' } : {}) }) model.slides.pages = [edited] const bytes = await createPresentationPptx(model) @@ -138,7 +144,7 @@ describe('PowerPoint display fidelity', () => { }) it('retains the existing white-on-accent default header separately from black body text', async () => { - const model = createBlankPresentationDocument('Header colors') + const model = createBlankPresentationProject('Header colors') model.slides.pages[0]!.elements = [{ id: 'table', type: 'table', x: 80, y: 80, width: 600, height: 300, rotation: 0, cells: [['Header', 'Value'], ['Body', '10']], headerRow: true, headerFill: '#6957D9', bodyFill: '#FFFFFF', textColor: '#000000', borderColor: '#D8D9E0', fontSize: 24 }] const reopened = await importPresentationPptx(await createPresentationPptx(model)) @@ -146,7 +152,7 @@ describe('PowerPoint display fidelity', () => { }) it.each(['pie', 'doughnut'] as const)('retains per-category %s colors through repeated exports', async (chartType) => { - let model = createBlankPresentationDocument('Category colors') + let model = createBlankPresentationProject('Category colors') model.slides.pages[0]!.elements = [{ id: 'pie', type: 'chart', chartType, x: 100, y: 100, width: 800, height: 400, rotation: 0, categories: ['A', 'B', 'C'], series: [{ name: 'Total', values: [50, 0, 20] }], colors: ['#FF0000', '#00AA00', '#0000FF'], showLegend: true }] for (let round = 0; round < 2; round++) { @@ -158,7 +164,7 @@ describe('PowerPoint display fidelity', () => { }) it.each(['pie', 'doughnut'] as const)('matches sparse, unordered %s point overrides by index and retains single-series fallback', async (chartType) => { - const model = createBlankPresentationDocument('Point overrides') + const model = createBlankPresentationProject('Point overrides') model.slides.pages[0]!.elements = [{ id: 'pie', type: 'chart', chartType, x: 100, y: 100, width: 800, height: 400, rotation: 0, categories: ['A', 'B', 'C'], series: [{ name: 'Total', values: [50, 30, 20] }], colors: ['#FF0000', '#00AA00', '#0000FF'], showLegend: true }] const zip = await JSZip.loadAsync(await createPresentationPptx(model)) @@ -213,7 +219,7 @@ describe('PowerPoint display fidelity', () => { }) it('exports CSS-pixel stroke widths in DrawingML point units', async () => { - const model = createBlankPresentationDocument('Stroke units') + const model = createBlankPresentationProject('Stroke units') model.slides.pages[0]!.elements = [{ id: 'outline', type: 'rect', x: 100, y: 100, width: 400, height: 300, rotation: 0, fill: 'transparent', borderColor: '#000000', borderWidth: 4 }] const xml = await (await JSZip.loadAsync(await createPresentationPptx(model))).file('ppt/slides/slide1.xml')!.async('text') @@ -242,7 +248,7 @@ describe('PowerPoint display fidelity', () => { let model = await readFixture(shape(1, 100, `${paragraphs}`)) const text = firstText(model) expect(text.paragraphs?.map(paragraph => paragraph.endStyle?.fontSize)).toEqual([64, undefined, 128, 16, undefined, 80]) - const slide = compilePresentationSlideMarkdown(decompilePresentationSlideMarkdown(model.slides.pages[0]!), { document: model }).slide + const slide = agentEdit(model).slides.pages[0]! expect(slide.elements.find(element => element.type === 'text')).toMatchObject({ paragraphs: text.paragraphs }) model.slides.pages = [slide] for (let round = 0; round < 2; round++) { @@ -257,7 +263,7 @@ describe('PowerPoint display fidelity', () => { it.each(['rect', 'line'] as const)('exports whole-object opacity on %s outlines as well as fills', async (type) => { for (const opacity of [0, 0.2, 0.65]) { - const model = createBlankPresentationDocument('Faded outline') + const model = createBlankPresentationProject('Faded outline') model.slides.pages[0]!.elements = [{ id: 'faded', type, x: 100, y: 100, width: 500, height: type === 'line' ? 1 : 300, rotation: 0, fill: 'transparent', borderColor: '#000000', borderWidth: 8, opacity }] const bytes = await createPresentationPptx(model) @@ -271,7 +277,7 @@ describe('PowerPoint display fidelity', () => { }) it('keeps outline interiors transparent and their borders visible through export and reopening', async () => { - let model = createBlankPresentationDocument('Outline') + let model = createBlankPresentationProject('Outline') model.slides.pages[0]!.background = '#152945' model.slides.pages[0]!.elements = [{ id: 'outline', type: 'rect', x: 80, y: 80, width: 500, height: 300, rotation: 0, fill: 'transparent', borderColor: '#FFCC00', borderWidth: 3 }] @@ -283,7 +289,7 @@ describe('PowerPoint display fidelity', () => { }) it('keeps matching fill and border opacity editable through repeated exports', async () => { - let model = createBlankPresentationDocument('Faded filled shape') + let model = createBlankPresentationProject('Faded filled shape') model.slides.pages[0]!.elements = [{ id: 'faded', type: 'rect', x: 100, y: 100, width: 400, height: 200, rotation: 0, fill: '#FF0000', borderColor: '#000000', borderWidth: 8, opacity: 0.25 }] for (let count = 0; count < 2; count++) { @@ -342,7 +348,7 @@ describe('PowerPoint display fidelity', () => { }) it.each([0, 1])('keeps borderless ellipses borderless through repeated export/import with width=%s', async (borderWidth) => { - let model = createBlankPresentationDocument('Borderless') + let model = createBlankPresentationProject('Borderless') model.slides.pages[0]!.elements = [{ id: 'circle', type: 'ellipse', x: 40, y: 40, width: 200, height: 100, rotation: 0, fill: '#745ADD', borderColor: 'transparent', borderWidth }] for (let count = 0; count < 2; count++) { @@ -372,7 +378,7 @@ describe('PowerPoint display fidelity', () => { expect(svg).toContain('fill-opacity="1"') }) it('writes legal rich-text paragraphs, including soft breaks, blank paragraphs, and hyperlink relationships', async () => { - const model = createBlankPresentationDocument('Rich text') + const model = createBlankPresentationProject('Rich text') model.slides.pages[0]!.elements = [{ id: 'rich', type: 'text', text: 'First\nSecond\n\nThird', x: 40, y: 40, width: 500, height: 250, rotation: 0, fontSize: 32, fontFamily: 'Arial', fontWeight: 400, color: '#111111', align: 'left', @@ -443,7 +449,7 @@ describe('PowerPoint display fidelity', () => { }) it('draws ellipse and round-rectangle previews at the same bounds and radii as the canvas', () => { - const model = createBlankPresentationDocument('Shapes') + const model = createBlankPresentationProject('Shapes') model.slides.pages[0]!.elements = ['ellipse', 'roundRect'].map((type, index) => ({ id: type, type: type as 'ellipse' | 'roundRect', x: index * 300, y: 0, width: 200, height: 100, rotation: 0, fill: '#FF0000', borderColor: 'transparent', borderWidth: 0, diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImages.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImages.test.ts index 1669e831..5525aa14 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImages.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImages.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'bun:test' import JSZip from 'jszip' import { DOMParser } from '@xmldom/xmldom' -import { createBlankPresentationDocument, createBlankPresentationSlide, type PresentationFileSource, type PresentationImageElement } from '@/atoms/presentation' +import { createBlankPresentationProject, createBlankPresentationSlide, type PresentationFileSource, type PresentationImageElement } from '@/atoms/presentation' import { createPresentationPptx } from '../presentationPptx' import { importPresentationPptx } from '../presentationPptxImport' @@ -11,7 +11,7 @@ const pixel: PresentationFileSource = { mimeType: 'image/png', } -function picture(document: ReturnType, id: string, source = pixel): PresentationImageElement { +function picture(document: ReturnType, id: string, source = pixel): PresentationImageElement { const sourceAssetId = `${id}-asset` document.assets.push({ id: sourceAssetId, kind: 'image', name: source.fileName, source }) return { id, type: 'image', sourceAssetId, altText: id, fit: 'contain', x: 10, y: 20, width: 200, height: 100, rotation: 0 } @@ -28,7 +28,7 @@ async function imageRelationships(archive: JSZip, slideNumber: number) { describe('PPTX shared image export', () => { it('deduplicates payloads across slides while keeping distinct images, frames, crops and links', async () => { const differentPixel = { ...pixel, dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLttAAAAABJRU5ErkJggg==' } - const document = createBlankPresentationDocument('Shared images') + const document = createBlankPresentationProject('Shared images') const first = document.slides.pages[0]! const second = createBlankPresentationSlide('Second') document.slides.pages.push(second) @@ -73,7 +73,7 @@ describe('PPTX shared image export', () => { }) it('keeps repeated save and reopen cycles compact after editing an imported deck', async () => { - const document = createBlankPresentationDocument('Shared backgrounds') + const document = createBlankPresentationProject('Shared backgrounds') document.slides.pages = Array.from({ length: 30 }, (_, index) => ({ ...createBlankPresentationSlide(`Page ${index + 1}`), elements: [picture(document, `image-${index}`)] })) document.slides.selectedPageId = document.slides.pages[0]!.id let bytes = await createPresentationPptx(document) @@ -99,7 +99,7 @@ describe('PPTX shared image export', () => { const svg = (color: string): PresentationFileSource => ({ dataUrl: `data:image/svg+xml;base64,${btoa(``)}`, fileName: 'shape.svg', mimeType: 'image/svg+xml' }) const red = svg('red') const blue = svg('blue') - const document = createBlankPresentationDocument('SVG sharing') + const document = createBlankPresentationProject('SVG sharing') document.slides.pages[0]!.elements = [picture(document, 'red', red), picture(document, 'blue', blue)] document.slides.pages.push({ ...createBlankPresentationSlide('Scaled SVG'), elements: [{ ...picture(document, 'scaled-red', { ...red }), width: 400, height: 300 }] }) const archive = await JSZip.loadAsync(await createPresentationPptx(document)) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImport.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImport.test.ts index 96a37514..f49d485b 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImport.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/presentationPptxImport.test.ts @@ -1,19 +1,19 @@ import { describe, expect, it } from 'bun:test' import JSZip from 'jszip' -import { PRESENTATION_PAGE_SIZES, type PresentationDocument, type PresentationFileSource } from '@/atoms/presentation' -import { createPresentationTestDocument as createInitialPresentationDocument } from '@/test-fixtures/presentation' +import { PRESENTATION_PAGE_SIZES, type PresentationProject, type PresentationFileSource } from '@/atoms/presentation' +import { createPresentationTestDocument as createInitialPresentationProject } from '@/test-fixtures/presentation' import { createPresentationPptx } from '../presentationPptx' import { normalizePresentationProject, presentationElementSource } from '@/presentation/project' -import { validatePresentationDocument } from '@/presentation/model/reducer' +import { validatePresentationProject } from '@/presentation/model/reducer' -function addImageAsset(document: PresentationDocument, id: string, source: PresentationFileSource): void { +function addImageAsset(document: PresentationProject, id: string, source: PresentationFileSource): void { document.assets.push({ id, kind: 'image', name: source.fileName, source }) } describe('importPresentationPptx', () => { it('preserves the editable master and footer through repeated save and reopen cycles', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const source = normalizePresentationProject(createInitialPresentationDocument()) + const source = normalizePresentationProject(createInitialPresentationProject()) source.theme.footer = { text: 'Confidential', showDate: true, showSlideNumber: true } source.theme.bodyFontFamily = 'Arial' source.theme.titleFontFamily = 'Georgia' @@ -22,26 +22,26 @@ describe('importPresentationPptx', () => { document = await importPresentationPptx(await createPresentationPptx(document), 'Report.pptx', { restoreEditorModel: true }) expect(document.theme).toEqual(source.theme) expect(document.slides.pages).toEqual(source.slides.pages) - expect(document.sourceProtected).toBe(false) + expect(document).not.toHaveProperty('sourceProtected') document.slides.pages[0]!.notes = `Edited note ${cycle}` source.slides.pages[0]!.notes = `Edited note ${cycle}` } }) - it('invalidates its embedded model after an external edit and protects that source', async () => { + it('invalidates its embedded model after an external edit without adding host metadata', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const archive = await JSZip.loadAsync(await createPresentationPptx(source)) const slide = archive.file('ppt/slides/slide1.xml')! archive.file(slide.name, (await slide.async('string')).replace(/[^<]*<\/a:t>/, 'Externally corrected')) const imported = await importPresentationPptx(await archive.generateAsync({ type: 'uint8array' }), 'Report.pptx', { restoreEditorModel: true }) expect(JSON.stringify(imported.slides.pages)).toContain('Externally corrected') - expect(imported.sourceProtected).toBe(true) + expect(imported).not.toHaveProperty('sourceProtected') }) it('falls back to native PPTX content when a matching embedded model is invalid', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const archive = await JSZip.loadAsync(await createPresentationPptx(source)) const modelFile = archive.file('bridgic/editor-model.json')! const envelope = JSON.parse(await modelFile.async('string')) as Record @@ -57,7 +57,7 @@ describe('importPresentationPptx', () => { ) expect(imported.slides.pages.length).toBeGreaterThan(0) expect(JSON.stringify(imported.slides.pages)).toContain('Primary message') - expect(imported.sourceProtected).toBe(true) + expect(imported).not.toHaveProperty('sourceProtected') expect(warnings[0]?.[0]).toContain('Ignoring an invalid embedded editor model') } finally { console.warn = originalWarn @@ -66,7 +66,7 @@ describe('importPresentationPptx', () => { it('shares a master image across slides and preserves sharing through worker transfer', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const second = structuredClone(source.slides.pages[0]!) second.id = 'second-slide' source.slides.pages = [source.slides.pages[0]!, second] @@ -93,7 +93,7 @@ describe('importPresentationPptx', () => { it('preserves slide, layout and master background images behind foreground elements', async () => { const { importPresentationPptx } = await import('../presentationPptxImport') - const bytes = await createPresentationPptx(createInitialPresentationDocument()) + const bytes = await createPresentationPptx(createInitialPresentationProject()) const owners = ['slides/slide1.xml', 'slideLayouts/slideLayout1.xml', 'slideMasters/slideMaster1.xml'] for (const owner of owners) { const archive = await JSZip.loadAsync(bytes) @@ -120,7 +120,7 @@ describe('importPresentationPptx', () => { }) it('round-trips editable slides, geometry, notes and page size', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() source.theme.accentColors = ['#123456', '#ABCDEF', '#CC5500', '#118844', '#663399', '#DDCC22'] source.theme.background = '#112233' source.theme.bodyFontFamily = 'Arial' @@ -152,7 +152,7 @@ describe('importPresentationPptx', () => { }) it('imports only the requested source slides for lightweight template previews', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const first = source.slides.pages[0]! const second = structuredClone(first) second.id = 'preview-slide-2' @@ -174,7 +174,7 @@ describe('importPresentationPptx', () => { }) it('cleans omitted page links and assets when restoring a page subset', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const [first, second] = source.slides.pages const firstText = first!.elements.find((element) => element.type === 'text')! firstText.hyperlink = { type: 'slide', slideId: second!.id } @@ -203,11 +203,11 @@ describe('importPresentationPptx', () => { expect(imported.slides.pages).toHaveLength(1) expect(imported.slides.pages[0]!.elements.find((element) => element.id === firstText.id)).not.toHaveProperty('hyperlink') expect(imported.assets.map((asset) => asset.id)).toEqual(['retained-asset']) - expect(validatePresentationDocument(imported)).toBe(imported) + expect(validatePresentationProject(imported)).toBe(imported) }) it('preserves mixed shape-picture z-order, source crop and text-box layout', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -283,7 +283,7 @@ describe('importPresentationPptx', () => { }) it('keeps color-keyed pictures visible and preserves picture mirroring', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -328,7 +328,7 @@ describe('importPresentationPptx', () => { }) it('imports an ellipse shape with a picture fill as a clipped image instead of its theme fallback color', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -384,7 +384,7 @@ describe('importPresentationPptx', () => { }) it('imports East Asian vertical text and DrawingML preset colors', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -426,7 +426,7 @@ describe('importPresentationPptx', () => { }) it('prefers the East Asian run font for CJK text', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -464,7 +464,7 @@ describe('importPresentationPptx', () => { }) it('keeps custom geometry as a fidelity-preserving SVG object', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -497,7 +497,7 @@ describe('importPresentationPptx', () => { }) it('imports an Office SVG extension when the picture has no raster fallback relationship', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id @@ -538,7 +538,7 @@ describe('importPresentationPptx', () => { }) it('imports common editable tables and charts', async () => { - const source = createInitialPresentationDocument() + const source = createInitialPresentationProject() const slide = source.slides.pages[0]! source.slides.pages = [slide] source.slides.selectedPageId = slide.id diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/presentationWorkspaceRuntime.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/presentationWorkspaceRuntime.test.ts deleted file mode 100644 index b3448384..00000000 --- a/desktop/apps/electron/src/renderer/lib/__tests__/presentationWorkspaceRuntime.test.ts +++ /dev/null @@ -1,277 +0,0 @@ -import { describe, expect, it } from 'bun:test' -import { createStore } from 'jotai' -import { - createBlankPresentationDocument, - createBlankPresentationSlide, - presentationWorkspaceFamily, - replacePresentationPages, - selectPresentationPage, - type PresentationDocument, - type PresentationWorkspace, -} from '@/atoms/presentation' -import { activeSessionIdAtom } from '@/atoms/sessions' -import { createPresentationWorkspaceRuntime } from '../presentationWorkspaceRuntime' -import { createOfficeEditorBinding } from '../office/officeEditorBinding' -import type { PowerPointDispatchResult, PowerPointRequest } from '../powerPointProtocol' - -function setup() { - const first = createBlankPresentationDocument('First') - let workspace: PresentationWorkspace = { activeDocumentId: first.id, documents: [first] } - const controller = createPresentationWorkspaceRuntime({ - sessionId: 'session-a', - read: () => workspace, - write: (next) => { workspace = next }, - }) - const apply = async (dispatched: PowerPointDispatchResult) => { - if (dispatched.workspace) workspace = dispatched.workspace - } - const context = () => ({ currentTarget: null, fileName: 'First.pptx' }) - return { first, controller, apply, context, read: () => workspace } -} - -describe('presentation workspace runtime', () => { - it('imports concurrent opens of the same file once and preserves its edited document on another click', async () => { - let target: string | null = null - let imports = 0 - let finish!: () => void - const gate = new Promise((resolve) => { finish = resolve }) - const initial = createBlankPresentationDocument('Initial') - let workspace: PresentationWorkspace = { activeDocumentId: initial.id, documents: [initial] } - const context = () => ({ - currentTarget: target, fileName: 'Deck.pptx', - importPptx: async () => { imports++; await gate; return createBlankPresentationDocument('Imported deck') }, - }) - const apply = async (result: PowerPointDispatchResult) => { - if (result.target) target = result.target - if (result.workspace) workspace = result.workspace - } - const runtime = createPresentationWorkspaceRuntime({ sessionId: 'session-a', read: () => workspace, write: (next) => { workspace = next } }) - const request = { method: 'view_ppt', params: { target: '/tmp/Deck.pptx', file_name: 'Deck.pptx', content_base64: 'AQ==' } } as const - const first = runtime.dispatchProtocol(request, context, apply) - const second = runtime.dispatchProtocol(request, context, apply) - finish() - expect(await first).toMatchObject({ ok: true, value: { reused: false } }) - expect(await second).toMatchObject({ ok: true, value: { reused: true } }) - expect(imports).toBe(1) - expect(workspace.documents).toHaveLength(1) - const document = workspace.documents[0]! - runtime.commitDocument(document, { ...document, title: 'User edits' }) - expect(await runtime.dispatchProtocol(request, context, apply)).toMatchObject({ ok: true, value: { reused: true } }) - expect(workspace.documents[0]!.id).toBe(document.id) - expect(workspace.documents[0]!.title).toBe('User edits') - expect(imports).toBe(1) - }) - - it('reconciles native edits before an Agent page read without changing the v5 response', async () => { - const { controller, first, read, context, apply } = setup() - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'session-a', documentId: first.id }) - binding.attach({ - readSnapshot: () => read().documents[0]!, - flush: () => { - const current = read().documents[0]! - controller.commitDocument(current, { ...current, slides: replacePresentationPages(current.slides, current.slides.pages.map((slide) => ({ ...slide, notes: 'Uncommitted native text' }))) }) - }, - dispose: () => undefined, - }) - controller.bindEditor(binding) - const result = await controller.dispatchProtocol({ method: 'get_ppt_page', params: { page_id: first.slides.selectedPageId } }, context, apply) - expect(result).toMatchObject({ ok: true, value: { page: { has_content: true } } }) - expect(read().documents[0]!.slides.pages[0]!.notes).toBe('Uncommitted native text') - }) - - it('flushes the original native document before creating a new tab', async () => { - const { controller, first, read } = setup() - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'session-a', documentId: first.id }) - binding.attach({ readSnapshot: () => read().documents[0]!, flush: () => { - const current = read().documents[0]! - controller.commitDocument(current, { ...current, title: 'Native text kept before switching' }) - }, dispose: () => undefined }) - controller.bindEditor(binding) - const result = await controller.createDocument() - expect(result.ok).toBe(true) - expect(read().documents[0]!.title).toBe('Native text kept before switching') - expect(read().activeDocumentId).not.toBe(first.id) - }) - - it('keeps the current workspace when native composition prevents a tab change or close', async () => { - const { controller, first, read } = setup() - let composing = true - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'session-a', documentId: first.id }) - binding.attach({ readSnapshot: () => first, flush: () => { if (composing) throw new Error('Finish composing') }, dispose: () => undefined }) - controller.bindEditor(binding) - const previous = read() - expect(await controller.createDocument()).toMatchObject({ ok: false, error: { message: 'Finish composing' } }) - expect(await controller.closeDocument(first.id)).toMatchObject({ ok: false, error: { message: 'Finish composing' } }) - expect(read()).toBe(previous) - composing = false - expect((await controller.createDocument()).ok).toBe(true) - }) - - it.each(['create', 'activate', 'close', 'protocol'] as const)('does not apply %s after the workspace was disposed during native flush', async (operation) => { - const { controller, first, read, context, apply } = setup() - let release!: () => void - let flushing = false - const gate = new Promise((resolve) => { release = resolve }) - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'session-a', documentId: first.id }) - binding.attach({ readSnapshot: () => first, flush: async () => { flushing = true; await gate }, dispose: () => undefined }) - controller.bindEditor(binding) - const before = read() - const operations = { - create: () => controller.createDocument(), - activate: () => controller.activateDocument(first.id), - close: () => controller.closeDocument(first.id), - protocol: () => controller.dispatchProtocol({ method: 'view_ppt', params: { target: '/tmp/after-close.pptx', file_name: 'after-close.pptx' } }, context, apply), - } - const pending = operations[operation]() - await Promise.resolve() - expect(flushing).toBe(true) - controller.runtime.dispose() - release() - expect(await pending).toMatchObject({ ok: false }) - expect(read()).toBe(before) - }) - - it('rejects editor bindings owned by another Session', () => { - const { controller, first } = setup() - const binding = createOfficeEditorBinding({ appKind: 'presentation', sessionId: 'another-session', documentId: first.id }) - expect(() => controller.bindEditor(binding)).toThrow('another Session') - }) - - it('projects blank document identity and honest capabilities without owning another model', () => { - const { controller, first } = setup() - expect(controller.runtime.getSnapshot()).toMatchObject({ - appKind: 'presentation', sessionId: 'session-a', activeDocumentId: first.id, - documents: [{ id: first.id, title: 'First', revision: 1, dirty: true }], - }) - expect(controller.runtime.supports('document.create')).toBe(true) - expect(controller.runtime.supports('powerpoint.edit_ppt_page')).toBe(true) - expect(controller.runtime.supports('document.save')).toBe(true) - expect(controller.runtime.supports('document.undo')).toBe(false) - }) - - it('keeps native editing synchronous and rejects stale document commits', () => { - const { controller, first, read } = setup() - const revisions: number[] = [] - controller.runtime.subscribe((snapshot) => { revisions.push(snapshot.documents[0]!.revision) }) - const changed = controller.commitDocument(first, { ...first, title: 'Typed' }) - expect(read().documents[0]).toBe(changed) - expect(changed.revision).toBe(2) - expect(revisions).toEqual([2]) - expect(() => controller.commitDocument(first, { ...first, title: 'Stale' })).toThrow() - expect(read().documents[0]!.title).toBe('Typed') - }) - - it('does not count selecting a slide as a content revision', () => { - const { controller, first, read } = setup() - const nextSlide = createBlankPresentationSlide('Second') - const withSlide = controller.commitDocument(first, { ...first, slides: replacePresentationPages(first.slides, [...first.slides.pages, nextSlide]) }) - const selected = controller.commitDocument(withSlide, { ...withSlide, slides: selectPresentationPage(withSlide.slides, nextSlide.id) }, false) - expect(selected.revision).toBe(withSlide.revision) - expect(read().documents[0]!.slides.selectedPageId).toBe(nextSlide.id) - }) - - it('routes create, activate and close through the existing workspace and preserves final-tab close', async () => { - const { controller, first, read } = setup() - const created = await controller.createDocument() - if (!created.ok) throw new Error(created.error.message) - expect(read().documents).toHaveLength(2) - expect(read().activeDocumentId).toBe(created.value) - expect((await controller.activateDocument(first.id)).ok).toBe(true) - expect(read().activeDocumentId).toBe(first.id) - expect(await controller.closeDocument(first.id)).toEqual({ ok: true, value: { closeSurface: false } }) - expect(read().activeDocumentId).toBe(created.value) - const before = read() - expect(await controller.closeDocument(created.value)).toEqual({ ok: true, value: { closeSurface: true } }) - expect(read()).toBe(before) - expect(await controller.closeDocument('missing')).toMatchObject({ ok: false, error: { code: 'document_not_found' } }) - }) - - it('orders UI tab commands after an Agent command and its persistence acknowledgement', async () => { - const { controller, context, apply, read } = setup() - let release: () => void = () => undefined - const gate = new Promise((resolve) => { release = resolve }) - let saving = false - const opened = controller.dispatchProtocol({ - method: 'view_ppt', params: { target: '/tmp/queued.pptx', file_name: 'Queued.pptx' }, - }, context, async (dispatched) => { - await apply(dispatched) - saving = true - await gate - }) - const created = controller.createDocument() - await Promise.resolve() - await Promise.resolve() - expect(saving).toBe(true) - expect(read().documents).toHaveLength(1) - expect(read().documents[0]!.title).toBe('Queued') - release() - expect((await opened).ok).toBe(true) - expect((await created).ok).toBe(true) - expect(read().documents).toHaveLength(2) - }) - - it('preserves native edits made while an Agent command prepares its workspace', async () => { - const { controller, first, context, apply, read } = setup() - const pending = controller.dispatchProtocol({ - method: 'view_ppt', params: { target: '/tmp/open.pptx', file_name: 'Opened.pptx' }, - }, context, apply) - controller.commitDocument(first, { ...first, title: 'User edit' }) - expect(await pending).toMatchObject({ ok: false, code: 'document_changed' }) - expect(read().documents[0]!.title).toBe('User edit') - expect((await controller.createDocument()).ok).toBe(true) - }) - - it('keeps protocol v5 revision errors and compiler diagnostics unchanged', async () => { - const { controller, first, context, apply } = setup() - const stale = await controller.dispatchProtocol({ - method: 'insert_ppt_element', - params: { page_id: first.slides.selectedPageId, expected_revision: 'stale', element: 'Text' }, - }, context, apply) - expect(stale).toMatchObject({ ok: false, code: 'page_changed', error: expect.any(String) }) - const readPage = await controller.dispatchProtocol({ method: 'get_ppt_page', params: { page_id: first.slides.selectedPageId } }, context, apply) - if (!readPage.ok) throw new Error(readPage.error) - const revision = (readPage.value as { page: { revision: string } }).page.revision - const invalid = await controller.dispatchProtocol({ - method: 'insert_ppt_element', - params: { page_id: first.slides.selectedPageId, expected_revision: revision, element: '# Invalid element' }, - }, context, apply) - expect(invalid).toMatchObject({ ok: true, value: { status: 'invalid' } }) - expect(await controller.dispatchProtocol({ method: 'invented' } as unknown as PowerPointRequest, context, apply)) - .toEqual({ ok: false, error: 'Unsupported PowerPoint method: invented' }) - }) - - it('preserves a committed model on persistence failure and allows following commands', async () => { - const { controller, context, apply, read } = setup() - const failed = await controller.dispatchProtocol({ - method: 'view_ppt', params: { target: '/tmp/failure.pptx', file_name: 'Committed.pptx' }, - }, context, async (dispatched) => { - await apply(dispatched) - throw new Error('Disk unavailable') - }) - expect(failed).toEqual({ ok: false, error: 'Disk unavailable' }) - expect(read().documents[0]!.title).toBe('Committed') - expect((await controller.createDocument()).ok).toBe(true) - }) - - it('keeps queued work bound to its Session when main navigation changes', async () => { - const store = createStore() - store.set(activeSessionIdAtom, 'session-a') - const atom = presentationWorkspaceFamily('session-a') - const controller = createPresentationWorkspaceRuntime({ - sessionId: 'session-a', read: () => store.get(atom), write: (workspace) => store.set(atom, workspace), - }) - let release: () => void = () => undefined - const gate = new Promise((resolve) => { release = resolve }) - const blocking = controller.runtime.execute({ sessionId: 'session-a', capability: 'document.create' }, () => gate) - const pending = controller.createDocument() - store.set(activeSessionIdAtom, 'session-b') - const sessionB = store.get(presentationWorkspaceFamily('session-b')) - release() - await blocking - expect((await pending).ok).toBe(true) - expect(store.get(atom).documents).toHaveLength(2) - expect(store.get(presentationWorkspaceFamily('session-b'))).toBe(sessionB) - const other = store.get(atom).documents[0] as PresentationDocument - expect(() => controller.commitDocument(other, { ...other, title: 'Wrong active document' })).toThrow() - }) -}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/rendererRoots.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/rendererRoots.test.ts new file mode 100644 index 00000000..d3b448cd --- /dev/null +++ b/desktop/apps/electron/src/renderer/lib/__tests__/rendererRoots.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from 'bun:test' +import { readFileSync } from 'node:fs' + +describe('standalone renderer roots', () => { + it('gives every Office entry root the full viewport height', () => { + const css = readFileSync(new URL('../../index.css', import.meta.url), 'utf8') + + expect(css).toMatch(/html,\s*body,\s*#root,\s*#excel-root,\s*#word-root\s*\{[^}]*height:\s*100%/s) + }) +}) diff --git a/desktop/apps/electron/src/renderer/lib/__tests__/tool-display.test.ts b/desktop/apps/electron/src/renderer/lib/__tests__/tool-display.test.ts index 7131a2ba..824e638c 100644 --- a/desktop/apps/electron/src/renderer/lib/__tests__/tool-display.test.ts +++ b/desktop/apps/electron/src/renderer/lib/__tests__/tool-display.test.ts @@ -191,26 +191,27 @@ describe('toolLabel — 已登记工具族(spec 驱动)', () => { // Preserve unmapped enum values instead of dropping them. expect(toolLabel('generic', 'browser_scroll', { direction: 'sideways' }).subject).toBe('sideways') }) - it('PPT 工具显示页面级动作和稳定页 id', () => { - expect(toolLabel('generic', 'view_ppt', { target: 'decks/review.pptx' })).toEqual({ + it('PPT 工具显示精简事务和渲染动作', () => { + expect(toolLabel('generic', 'ppt_open', { target: 'decks/review.pptx' })).toEqual({ verb: '打开 PPT', subject: 'review.pptx', subjectFull: 'decks/review.pptx', }) - expect(toolLabel('generic', 'edit_ppt_page', { page_id: 'page-2', ref: 'title' })).toEqual({ + expect(toolLabel('generic', 'ppt_edit_page', { document_id: 'deck', page_id: 'page-2', operations: [] })).toEqual({ verb: '编辑 PPT 页', subject: 'page-2', subjectMono: true, }) - expect(toolMeta('generic', 'edit_ppt_page', { page_id: 'page-2', ref: 'title' }, '').detail).toBe('title') - expect(toolLabel('generic', 'update_ppt_design', { theme: 'midnight' })).toEqual({ - verb: '更新 PPT 设计', - subject: 'midnight', + expect(toolLabel('generic', 'ppt_inspect', { document_id: 'deck', query: { kind: 'render', page_ids: ['page-2'] } })).toEqual({ + verb: '渲染 PPT', + subject: 'deck', + subjectMono: true, + }) + expect(toolLabel('generic', 'ppt_save', { document_id: 'deck' })).toEqual({ + verb: '保存 PPT', + subject: 'deck', + subjectFull: 'deck', }) - expect(toolMeta('generic', 'move_ppt_page', { - page_id: 'page-2', - target_page_id: 'page-4', - }, '').detail).toBe('page-4') }) it('无参工具只显示动词', () => { expect(toolLabel('generic', 'workspace_status', {})).toEqual({ verb: '查看工作区状态', subject: '' }) diff --git a/desktop/apps/electron/src/renderer/lib/apiStub.ts b/desktop/apps/electron/src/renderer/lib/apiStub.ts index d62b136d..565a95a2 100644 --- a/desktop/apps/electron/src/renderer/lib/apiStub.ts +++ b/desktop/apps/electron/src/renderer/lib/apiStub.ts @@ -122,6 +122,7 @@ export function installApiStub(): void { webContentsId: 0, loading: false, crashed: false, + documentCount: null, }), closeSession: async () => {}, activateSession: async () => {}, @@ -129,6 +130,7 @@ export function installApiStub(): void { setVisible: async () => {}, requestClose: async () => {}, setExpanded: async () => {}, + reportState: async () => {}, openFile: async () => { throw new Error('Opening PowerPoint files requires Electron') }, }, word: { @@ -155,6 +157,7 @@ export function installApiStub(): void { ready: false, crashed: false, dirty: false, + documentCount: null, }), openWorkbook: async () => {}, closeSession: async () => {}, diff --git a/desktop/apps/electron/src/renderer/lib/office/officeSurfaceStatus.ts b/desktop/apps/electron/src/renderer/lib/office/officeSurfaceStatus.ts index 45aa7516..af1ffb77 100644 --- a/desktop/apps/electron/src/renderer/lib/office/officeSurfaceStatus.ts +++ b/desktop/apps/electron/src/renderer/lib/office/officeSurfaceStatus.ts @@ -22,7 +22,7 @@ export interface OfficeSurfaceStatus { export type OfficeSurfaceStatuses = Readonly> -/** Adapt existing producers without changing their protocols or inventing document counts. */ +/** Adapt existing producers without inventing document counts. */ export function projectOfficeSurfaceStatuses({ sessionId, powerPointSession, @@ -47,8 +47,8 @@ export function projectOfficeSurfaceStatuses({ sessionId, hasNativeTarget: ppt !== null, runtimeState: nativeRuntimeState(ppt, ppt?.loading ?? false), - documentCount: null, - documentInventory: 'unsupported', + documentCount: ppt?.documentCount ?? null, + documentInventory: ppt?.documentCount != null ? 'ready' : 'pending', agentActivity: sessionId && powerPointAgentActive ? 'active' : 'idle', needsAttention: sessionId !== null && powerPointNeedsAttention, dirty: null, @@ -69,8 +69,8 @@ export function projectOfficeSurfaceStatuses({ sessionId, hasNativeTarget: excel !== null, runtimeState: nativeRuntimeState(excel, excel?.ready === false), - documentCount: null, - documentInventory: 'unsupported', + documentCount: excel?.documentCount ?? null, + documentInventory: excel?.documentCount != null ? 'ready' : 'pending', agentActivity: 'unavailable', needsAttention: null, dirty: excel?.dirty ?? null, @@ -84,7 +84,7 @@ function nativeRuntimeState(target: { crashed: boolean } | null, loading: boolea return loading ? 'loading' : 'ready' } -/** Preserve native-target markers until those runtimes publish authoritative document counts. */ +/** Only runtimes without document inventory fall back to their native-target marker. */ export function hasOfficeBackgroundContent(status: OfficeSurfaceStatus): boolean { if (status.sessionId === null) return false if (status.documentCount !== null) return status.documentCount > 0 diff --git a/desktop/apps/electron/src/renderer/lib/powerPointProtocol.ts b/desktop/apps/electron/src/renderer/lib/powerPointProtocol.ts index 0ff30109..bf67474e 100644 --- a/desktop/apps/electron/src/renderer/lib/powerPointProtocol.ts +++ b/desktop/apps/electron/src/renderer/lib/powerPointProtocol.ts @@ -1,54 +1,27 @@ import { - PRESENTATION_TRANSITION_DIRECTIONS, - PRESENTATION_TRANSITION_EFFECTS, - createBlankPresentationDocument, - replacePresentationPages, + createBlankPresentationProject, selectPresentationPage, type PresentationAgentChange, - type PresentationAsset, - type PresentationDocument, type PresentationFileSource, + type PresentationProject, type PresentationSlide, - type PresentationWorkspace, } from '@/atoms/presentation' -import { - applyPresentationDesign, - normalizePresentationDesignColor, - type PresentationDesignPatch, - type PresentationThemePresetId, -} from '@/lib/presentationDesign' -import { - compilePresentationElementMarkdown, - compilePresentationSlideMarkdown, - decompilePresentationSlideMarkdown, - inspectPresentationMarkdownAssets, - type PresentationMarkdownAssets, -} from '@/lib/presentationMarkdown' +import { decompilePresentationSlideMarkdown } from '@/lib/presentationMarkdown' import { importPresentationPptx } from '@/lib/presentationPptxImport' -import { validatePresentationDocument } from '@/presentation/model/reducer' -import { - clearPresentationHyperlinksToPages, - detachPresentationCommentsFromElements, - mergePresentationAssets, - presentationAsset, - presentationElementSource, -} from '@/presentation/project' +import { editPresentationPage, managePresentationDeck } from '@/presentation/agentCommands' +import { editPresentationProject } from '@/presentation/model/reducer' +import { presentationAsset, presentationElementSource } from '@/presentation/project' -export const POWERPOINT_PROTOCOL_VERSION = 5 as const +export const POWERPOINT_PROTOCOL_VERSION = 7 as const export type PowerPointMethod = - | 'save_ppt' - | 'view_ppt' - | 'inspect_ppt_assets' - | 'get_ppt_page' - | 'update_ppt_design' - | 'edit_ppt_page' - | 'insert_ppt_element' - | 'remove_ppt_element' - | 'insert_ppt_page' - | 'remove_ppt_page' - | 'move_ppt_page' - | 'goto_ppt_page' + | 'open' + | 'read_deck' + | 'read_page' + | 'inspect' + | 'edit_page' + | 'manage_deck' + | 'save' export interface PowerPointRequest { method: PowerPointMethod @@ -57,334 +30,222 @@ export interface PowerPointRequest { export interface PowerPointRuntimeContext { currentTarget: string | null - fileName: string - importPptx?: (encoded: string, fileName: string) => Promise + fileNameOf?: (projectId: string) => string | undefined + importPptx?: (encoded: string, fileName: string) => Promise + revisionOf?: (projectId: string) => number +} + +export interface PowerPointProjectCollection { + activeProjectId: string + projects: PresentationProject[] } export interface PowerPointDispatchResult { agentChange?: Omit + contentChanged?: boolean + changedProjectId?: string + projects?: PowerPointProjectCollection result: unknown - workspace?: PresentationWorkspace target?: string - persist?: boolean } +export type PowerPointProtocolErrorCode = 'document_changed' | 'document_not_found' | 'page_changed' + export class PowerPointProtocolError extends Error { - constructor(message: string, readonly code: 'deck_changed' | 'document_changed' | 'page_changed') { + constructor(message: string, readonly code: PowerPointProtocolErrorCode) { super(message) this.name = 'PowerPointProtocolError' } } -/** Execute one page-level PPT request against the same native model used by the editor. */ +/** Execute one structured PPT request against the editor's authoritative model. */ export async function executePowerPointRequest( - current: PresentationWorkspace, + current: PowerPointProjectCollection, request: PowerPointRequest, - context: PowerPointRuntimeContext = { currentTarget: null, fileName: 'Untitled.pptx' }, + context: PowerPointRuntimeContext = { currentTarget: null }, ): Promise { if (!request || typeof request !== 'object') throw new TypeError('PowerPoint request is required') const params = request.params ?? {} - if (request.method === 'view_ppt') { + if (request.method === 'open') { const target = requiredString(params.target, 'target') const fileName = requiredString(params.file_name, 'file_name') if (context.currentTarget === target) { - return { result: { ...deckOverview(requireActiveDocument(current), fileName), reused: true }, target } + const project = requireActiveProject(current) + return { result: { ...deckRead(project, fileName, revisionOf(context, project.id)), reused: true }, target } } const encoded = optionalString(params.content_base64, 'content_base64') - const document = encoded + const project = encoded ? await (context.importPptx ? context.importPptx(encoded, fileName) : importPresentationPptx(decodeBase64(encoded), fileName, { restoreEditorModel: true })) - : createBlankPresentationDocument(fileName.replace(/\.pptx$/i, '')) - const workspace = { activeDocumentId: document.id, documents: [document] } - return { result: { ...deckOverview(document, fileName), reused: false }, workspace, target, persist: !encoded } - } - - if (request.method === 'inspect_ppt_assets') { - return { result: inspectPresentationMarkdownAssets(requiredString(params.markdown, 'markdown')) } + : createBlankPresentationProject(fileName.replace(/\.pptx$/i, '')) + const projects = { activeProjectId: project.id, projects: [project] } + return { result: { ...deckRead(project, fileName, 1), reused: false }, projects, target } } - const document = requireActiveDocument(current) - if (request.method === 'get_ppt_page') { - return { result: pageView(document, requireSlide(document, requiredString(params.page_id, 'page_id'))) } - } - - if (request.method === 'goto_ppt_page') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - const nextDocument = { ...document, slides: selectPresentationPage(document.slides, slide.id) } + const documentId = requiredString(params.document_id, 'document_id') + const project = requireProject(current, documentId) + const activeProjects = current.activeProjectId === project.id + ? current + : { ...current, activeProjectId: project.id } + const projectRevision = revisionOf(context, project.id) + + if (request.method === 'read_deck') { + assertKeys(params, ['document_id', 'include_theme'], 'read_deck') + const includeTheme = optionalBoolean(params.include_theme, 'include_theme') ?? false + const fileName = context.fileNameOf?.(project.id) || `${project.title.replace(/\.pptx$/i, '') || 'Untitled'}.pptx` return { - result: { page_id: slide.id, index: document.slides.pages.indexOf(slide), visible: true }, - workspace: replaceDocument(current, nextDocument), - } - } - - if (request.method === 'update_ppt_design') { - assertDocumentRevision(document, requiredString(params.expected_document_revision, 'expected_document_revision')) - const designed = applyPresentationDesign(document, designPatch(params.design, document)) - const nextDocument = { ...designed, revision: document.revision + 1 } - const selectedSlide = requireSlide(nextDocument, nextDocument.slides.selectedPageId) - return { - agentChange: { - elementIds: selectedSlide.elements.map((element) => element.id), - kind: 'design', - slideId: selectedSlide.id, - }, - result: deckOverview(nextDocument, context.fileName), - workspace: replaceDocument(current, nextDocument), - persist: true, + result: deckRead(project, fileName, projectRevision, includeTheme), + ...(activeProjects === current ? {} : { projects: activeProjects }), } } - if (request.method === 'edit_ppt_page') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - assertPageRevision(document, slide, requiredString(params.expected_revision, 'expected_revision')) - const ref = requiredString(params.ref, 'ref') - const elementIndex = slide.elements.findIndex((element) => element.id === ref) - if (elementIndex < 0) throw new Error(`Unknown PowerPoint element ref: ${ref}`) - const compiled = compileElement( - requiredString(params.replacement, 'replacement'), document, slide, assetsValue(params.assets), ref, - ) - if ('invalid' in compiled) return { result: compiled.invalid } - const elements = [...slide.elements] - elements[elementIndex] = compiled.element - const replacement = { ...slide, elements } - const nextDocument = replaceSlide(document, replacement, compiled.assets) + if (request.method === 'read_page') { + assertKeys(params, ['document_id', 'page_id', 'format', 'element_ids'], 'read_page') + const slide = requireSlide(project, requiredString(params.page_id, 'page_id')) + const format = enumValue(params.format ?? 'compact', new Set(['compact', 'model', 'both'] as const), 'format') + const elementIds = stringArray(params.element_ids, 'element_ids') return { - agentChange: { - elementIds: [ref], - kind: 'content', - slideId: replacement.id, - }, - result: { - status: 'ready', - diagnostics: diagnostics(compiled.diagnostics), - document_revision: documentRevision(nextDocument), - element_ref: ref, - ...pageView(nextDocument, replacement), - }, - workspace: replaceDocument(current, nextDocument), - persist: true, + result: pageRead(project, slide, format, elementIds), + ...(activeProjects === current ? {} : { projects: activeProjects }), } } - if (request.method === 'insert_ppt_element') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - assertPageRevision(document, slide, requiredString(params.expected_revision, 'expected_revision')) - const compiled = compileElement( - requiredString(params.element, 'element'), document, slide, assetsValue(params.assets), - ) - if ('invalid' in compiled) return { result: compiled.invalid } - const replacement = { ...slide, elements: [...slide.elements, compiled.element] } - const nextDocument = replaceSlide(document, replacement, compiled.assets) + if (request.method === 'inspect') { + assertKeys(params, ['document_id', 'kind', 'page_id'], 'inspect') + if (params.kind !== 'render') throw new Error(`Unsupported PowerPoint inspection: ${String(params.kind)}`) + const slide = requireSlide(project, optionalString(params.page_id, 'page_id') ?? project.slides.selectedPageId) + const nextProject = { ...project, slides: selectPresentationPage(project.slides, slide.id) } return { - agentChange: { - elementIds: [compiled.element.id], - kind: 'content', - slideId: replacement.id, - }, result: { - status: 'ready', - diagnostics: diagnostics(compiled.diagnostics), - document_revision: documentRevision(nextDocument), - element_ref: compiled.element.id, - ...pageView(nextDocument, replacement), + kind: 'render', + document_id: project.id, + document_revision: projectRevision, + page_id: slide.id, + index: project.slides.pages.indexOf(slide), + revision: pageRevision(project, slide), }, - workspace: replaceDocument(current, nextDocument), - persist: true, + projects: replaceProject(activeProjects, nextProject), + changedProjectId: project.id, + contentChanged: false, } } - if (request.method === 'remove_ppt_element') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - assertPageRevision(document, slide, requiredString(params.expected_revision, 'expected_revision')) - const ref = requiredString(params.ref, 'ref') - if (!slide.elements.some((element) => element.id === ref)) { - throw new Error(`Unknown PowerPoint element ref: ${ref}`) + if (request.method === 'edit_page') { + assertKeys(params, ['document_id', 'page_id', 'expected_revision', 'operations', 'assets', 'validate_only'], 'edit_page') + const pageId = requiredString(params.page_id, 'page_id') + const slide = requireSlide(project, pageId) + assertPageRevision(project, slide, requiredString(params.expected_revision, 'expected_revision')) + const edited = editPresentationPage(project, pageId, params.operations, assetsValue(params.assets)) + const validateOnly = optionalBoolean(params.validate_only, 'validate_only') ?? false + if (validateOnly) { + return { result: { status: 'validated', document_id: project.id, page_id: pageId, changed_page_ids: edited.changedPageIds, changed_element_ids: edited.changedElementIds } } } - const replacement = { - ...detachPresentationCommentsFromElements(slide, new Set([ref])), - elements: slide.elements.filter((element) => element.id !== ref), - } - const nextDocument = replaceSlide(document, replacement) + const nextProject = editPresentationProject(project, edited.project) + const nextSlide = requireSlide(nextProject, pageId) + const nextRevision = projectRevision + 1 return { - agentChange: { elementIds: [], kind: 'content', slideId: replacement.id }, + agentChange: { elementIds: edited.changedElementIds, kind: 'content', slideId: pageId }, result: { status: 'ready', - diagnostics: [], - document_revision: documentRevision(nextDocument), - element_ref: ref, - ...pageView(nextDocument, replacement), + document_id: project.id, + page_id: pageId, + changed_page_ids: edited.changedPageIds, + changed_element_ids: edited.changedElementIds, + revision: pageRevision(nextProject, nextSlide), + deck_revision: documentRevision(nextProject, nextRevision), }, - workspace: replaceDocument(current, nextDocument), - persist: true, + projects: replaceProject(activeProjects, nextProject), + changedProjectId: project.id, + contentChanged: true, } } - if (request.method === 'insert_ppt_page') { - const compiled = compilePage(requiredString(params.markdown, 'markdown'), document, assetsValue(params.assets)) - if ('invalid' in compiled) return { result: compiled.invalid } - const afterPageId = optionalString(params.after_page_id, 'after_page_id') - const insertionIndex = afterPageId - ? document.slides.pages.findIndex((slide) => slide.id === afterPageId) + 1 - : document.slides.pages.length - if (afterPageId && insertionIndex === 0) throw new Error(`Unknown PowerPoint page: ${afterPageId}`) - const slides = [...document.slides.pages] - slides.splice(insertionIndex, 0, compiled.slide) - const nextDocument = { - ...document, - assets: mergePresentationAssets(document.assets, compiled.assets), - slides: replacePresentationPages(document.slides, slides, compiled.slide.id), - revision: document.revision + 1, + if (request.method === 'manage_deck') { + assertKeys(params, ['document_id', 'expected_revision', 'operations', 'validate_only'], 'manage_deck') + assertDocumentRevision(project, projectRevision, requiredString(params.expected_revision, 'expected_revision')) + const edited = managePresentationDeck(project, params.operations) + const validateOnly = optionalBoolean(params.validate_only, 'validate_only') ?? false + if (validateOnly) { + return { result: { status: 'validated', document_id: project.id, changed_page_ids: edited.changedPageIds } } } + const nextProject = editPresentationProject(project, edited.project) + const selected = requireSlide(nextProject, nextProject.slides.selectedPageId) return { - agentChange: { - elementIds: compiled.slide.elements.map((element) => element.id), - kind: 'content', - slideId: compiled.slide.id, - }, - result: { - status: 'ready', - diagnostics: diagnostics(compiled.diagnostics), - ...deckOverview(nextDocument, context.fileName), - ...pageView(nextDocument, compiled.slide), - }, - workspace: replaceDocument(current, nextDocument), - persist: true, - } - } - - if (request.method === 'remove_ppt_page') { - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - assertPageRevision(document, slide, requiredString(params.expected_revision, 'expected_revision')) - assertDeckRevision(document, requiredString(params.expected_deck_revision, 'expected_deck_revision')) - if (document.slides.pages.length === 1) throw new Error('A PowerPoint must keep at least one page') - const oldIndex = document.slides.pages.indexOf(slide) - const slides = clearPresentationHyperlinksToPages( - document.slides.pages.filter((item) => item.id !== slide.id), - new Set([slide.id]), - ) - const selectedPageId = document.slides.selectedPageId === slide.id - ? slides[Math.min(oldIndex, slides.length - 1)]!.id - : document.slides.selectedPageId - const nextDocument = { - ...document, - slides: replacePresentationPages(document.slides, slides, selectedPageId), - revision: document.revision + 1, - } - return { - result: deckOverview(nextDocument, context.fileName), - workspace: replaceDocument(current, nextDocument), - persist: true, - } - } - - if (request.method === 'move_ppt_page') { - assertDeckRevision(document, requiredString(params.expected_deck_revision, 'expected_deck_revision')) - const slide = requireSlide(document, requiredString(params.page_id, 'page_id')) - const target = requireSlide(document, requiredString(params.target_page_id, 'target_page_id')) - const position = requiredString(params.position, 'position') - if (slide.id === target.id) throw new Error('A PowerPoint page cannot be moved relative to itself') - if (position !== 'before' && position !== 'after') throw new Error("position must be 'before' or 'after'") - const slides = document.slides.pages.filter((item) => item.id !== slide.id) - const targetIndex = slides.findIndex((item) => item.id === target.id) - slides.splice(targetIndex + (position === 'after' ? 1 : 0), 0, slide) - const nextDocument = { - ...document, - slides: replacePresentationPages(document.slides, slides), - revision: document.revision + 1, - } - return { - result: deckOverview(nextDocument, context.fileName), - workspace: replaceDocument(current, nextDocument), - persist: true, + agentChange: { elementIds: selected.elements.map((element) => element.id), kind: edited.designChanged ? 'design' : 'content', slideId: selected.id }, + result: { status: 'ready', document_id: project.id, changed_page_ids: edited.changedPageIds, revision: documentRevision(nextProject, projectRevision + 1) }, + projects: replaceProject(activeProjects, nextProject), + changedProjectId: project.id, + contentChanged: true, } } throw new Error(`Unsupported PowerPoint method: ${String(request.method)}`) } -function compilePage(markdown: string, document: PresentationDocument, assets: PresentationMarkdownAssets): - | { assets: PresentationAsset[]; slide: PresentationSlide; diagnostics: string[] } - | { invalid: { status: 'invalid'; diagnostics: Array> } } { - try { - return compilePresentationSlideMarkdown(markdown, { assets, document, existingDocument: document }) - } catch (error) { - return { - invalid: { - status: 'invalid', - diagnostics: [{ - code: 'markdown_compile_error', - message: error instanceof Error ? error.message : String(error), - severity: 'error', - }], - }, - } - } -} - -function compileElement( - markdown: string, - document: PresentationDocument, - slide: PresentationSlide, - assets: PresentationMarkdownAssets, - elementId?: string, -): - | { assets: PresentationAsset[]; element: PresentationSlide['elements'][number]; diagnostics: string[] } - | { invalid: { status: 'invalid'; diagnostics: Array> } } { - try { - return compilePresentationElementMarkdown(markdown, { - assets, - document, - elementId, - existingDocument: document, - slide, - }) - } catch (error) { - return { - invalid: { - status: 'invalid', - diagnostics: [{ - code: 'element_compile_error', - message: error instanceof Error ? error.message : String(error), - severity: 'error', - }], - }, - } - } -} - -function deckOverview(document: PresentationDocument, fileName: string): Record { +function deckRead(document: PresentationProject, fileName: string, revision: number, includeTheme = true): Record { const selectedIndex = Math.max(0, document.slides.pages.findIndex((slide) => slide.id === document.slides.selectedPageId)) return { - identity: { - document_id: document.id, - name: document.title || fileName.replace(/\.pptx$/i, ''), - file_name: fileName, - }, - meta: { + document_id: document.id, + revision: documentRevision(document, revision), + deck: { + id: document.id, title: document.title, - theme: structuredClone(document.theme), + file_name: fileName, page_size: structuredClone(document.pageSize), total_pages: document.slides.pages.length, - current_page_id: document.slides.selectedPageId, - current_page_index: selectedIndex, - current_position: selectedIndex + 1, + active_page_id: document.slides.selectedPageId, + active_page_index: selectedIndex, + ...(includeTheme ? { theme: structuredClone(document.theme) } : {}), + pages: document.slides.pages.map((slide, index) => pageSummary(document, slide, index)), + }, + } +} + +function pageRead(document: PresentationProject, slide: PresentationSlide, format: 'both' | 'compact' | 'model', elementIds?: string[]): Record { + const index = document.slides.pages.findIndex((item) => item.id === slide.id) + const selectedElements = elementIds?.length + ? slide.elements.filter((element) => elementIds.includes(element.id)) + : slide.elements + if (elementIds?.some((id) => !slide.elements.some((element) => element.id === id))) { + throw new Error('element_ids contains an unknown PowerPoint element') + } + const assets = pageAssets(document, { ...slide, elements: selectedElements }) + return { + document_id: document.id, + page_id: slide.id, + revision: pageRevision(document, slide), + page: { + ...pageSummary(document, slide, index), + refs: selectedElements.map((element) => element.id), + ...(format === 'compact' || format === 'both' ? { markdown: decompilePresentationSlideMarkdown({ ...slide, elements: selectedElements }, document) } : {}), + ...(format === 'model' || format === 'both' ? { + model: { + id: slide.id, + name: slide.name, + layout: slide.layout, + background: slide.background, + notes: slide.notes, + footer: slide.footer, + transition: structuredClone(slide.transition), + comments: structuredClone(slide.comments ?? []), + elements: selectedElements.map((element) => pageModelElement(document, element)), + }, + } : {}), }, - deck_revision: deckRevision(document), - document_revision: documentRevision(document), - pages: document.slides.pages.map((slide, index) => pageSummary(document, slide, index)), + assets, } } -function pageSummary(document: PresentationDocument, slide: PresentationSlide, index: number): Record { +function pageSummary(document: PresentationProject, slide: PresentationSlide, index: number): Record { const text = slide.elements.flatMap((element) => ( 'text' in element && typeof element.text === 'string' ? [element.text.trim()] : [] )).filter(Boolean).join(' ') return { - page_id: slide.id, + id: slide.id, index, - title: slide.name, + name: slide.name, layout: slide.layout ?? 'blank', summary: text.slice(0, 240) || undefined, has_content: slide.elements.length > 0 || Boolean(slide.notes?.trim()), @@ -392,38 +253,13 @@ function pageSummary(document: PresentationDocument, slide: PresentationSlide, i } } -function pageView(document: PresentationDocument, slide: PresentationSlide): Record { - const index = document.slides.pages.findIndex((item) => item.id === slide.id) - const assets = pageAssets(document, slide) - return { - page: { - ...pageSummary(document, slide, index), - markdown: decompilePresentationSlideMarkdown(slide, document), - asset_paths: assets.map((asset) => asset.path), - refs: slide.elements.map((element) => element.id), - }, - assets, - } -} - -function pageAssets(document: PresentationDocument, slide: PresentationSlide): Array<{ - path: string - file_name: string - mime_type: string - data_url?: string -}> { - const found = new Map() +function pageAssets(document: PresentationProject, slide: PresentationSlide): Array<{ path: string; file_name: string; mime_type: string; data_url?: string }> { + const found = new Map() for (const element of slide.elements) { if (element.type !== 'image' && element.type !== 'audio' && element.type !== 'video') continue const source = presentationElementSource(document, element) if (!source) continue - const safeName = source.fileName.replace(/[^A-Za-z0-9._-]+/g, '-') || `${element.id}.bin` - const path = source.path ?? `.ppt-assets/${encodeURIComponent(source.assetId ?? element.id)}-${safeName}` + const path = pageAssetPath(source, element.id) if (found.has(path)) continue found.set(path, { path, @@ -435,17 +271,30 @@ function pageAssets(document: PresentationDocument, slide: PresentationSlide): A return [...found.values()] } +function pageModelElement(document: PresentationProject, element: PresentationSlide['elements'][number]): Record { + if (element.type !== 'image' && element.type !== 'audio' && element.type !== 'video') { + return structuredClone(element) as unknown as Record + } + const source = presentationElementSource(document, element) + if (!source) throw new Error(`PowerPoint element refers to a missing asset: ${element.id}`) + const { sourceAssetId: _sourceAssetId, ...projected } = structuredClone(element) + return { ...projected, src: pageAssetPath(source, element.id) } +} + +function pageAssetPath(source: PresentationFileSource, elementId: string): string { + const safeName = source.fileName.replace(/[^A-Za-z0-9._-]+/g, '-') || `${elementId}.bin` + return source.path ?? `.ppt-assets/${encodeURIComponent(source.assetId ?? elementId)}-${safeName}` +} + const mediaRevisions = new WeakMap() -function pageRevision(document: PresentationDocument, slide: PresentationSlide): string { +function pageRevision(document: PresentationProject, slide: PresentationSlide): string { const referencedAssets = slide.elements.flatMap((element) => { if (element.type !== 'image' && element.type !== 'audio' && element.type !== 'video') return [] const asset = presentationAsset(document, element.sourceAssetId) return asset ? [asset] : [] }) - // Large media payloads can be shared across pages. Hash each source object once, - // but include every referenced asset in the optimistic page revision. - return fingerprint(JSON.stringify({ slide, assets: referencedAssets }, function (key, value: unknown) { + return fingerprint(JSON.stringify({ slide, assets: referencedAssets, pageSize: document.pageSize, theme: document.theme }, function (key, value: unknown) { if (key !== 'dataUrl' || typeof value !== 'string') return value const source = this as object let cached = mediaRevisions.get(source) @@ -457,12 +306,8 @@ function pageRevision(document: PresentationDocument, slide: PresentationSlide): })) } -function deckRevision(document: PresentationDocument): string { - return fingerprint(JSON.stringify(document.slides.pages.map((slide) => slide.id))) -} - -function documentRevision(document: PresentationDocument): string { - return fingerprint(`${document.id}:${document.revision}`) +function documentRevision(document: PresentationProject, revision: number): string { + return fingerprint(`${document.id}:${revision}`) } function fingerprint(value: string): string { @@ -474,176 +319,90 @@ function fingerprint(value: string): string { return (hash >>> 0).toString(16).padStart(8, '0') } -function assertPageRevision(document: PresentationDocument, slide: PresentationSlide, expected: string): void { - if (pageRevision(document, slide) === expected) return - throw new PowerPointProtocolError( - `PowerPoint page ${slide.id} changed after it was read. Call get_ppt_page again before writing.`, - 'page_changed', - ) +function assertDocumentRevision(document: PresentationProject, revision: number, expected: string): void { + if (documentRevision(document, revision) === expected) return + throw new PowerPointProtocolError('The PowerPoint changed after it was read. Read the deck again before retrying.', 'document_changed') } -function assertDeckRevision(document: PresentationDocument, expected: string): void { - if (deckRevision(document) === expected) return - throw new PowerPointProtocolError( - 'The PowerPoint page order changed. Call view_ppt again before changing the structure.', - 'deck_changed', - ) +function assertPageRevision(document: PresentationProject, slide: PresentationSlide, expected: string): void { + if (pageRevision(document, slide) === expected) return + throw new PowerPointProtocolError(`PowerPoint page ${slide.id} changed after it was read. Read it again before retrying.`, 'page_changed') } -function assertDocumentRevision(document: PresentationDocument, expected: string): void { - if (documentRevision(document) === expected) return - throw new PowerPointProtocolError( - 'The PowerPoint changed after its design was read. Call view_ppt again before changing global design.', - 'document_changed', - ) +function assetsValue(value: unknown): Record { + if (value === undefined) return {} + if (!isRecord(value)) throw new TypeError('assets must be an object') + return value as Record } -function designPatch(value: unknown, document: PresentationDocument): PresentationDesignPatch { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('design must be a mapping') - const raw = value as Record - const patch: PresentationDesignPatch = {} - const themeIds = new Set(['lavender', 'light', 'midnight', 'paper']) - const pageSizes = new Set(['standard', 'wide'] as const) - const transitionEffects = new Set(PRESENTATION_TRANSITION_EFFECTS) - const transitionDirections = new Set(PRESENTATION_TRANSITION_DIRECTIONS) - - if (raw.theme !== undefined) patch.theme = enumValue(raw.theme, themeIds, 'design.theme') - if (raw.background !== undefined) patch.background = normalizePresentationDesignColor(requiredString(raw.background, 'design.background')) - if (raw.accent_colors !== undefined) { - if (!Array.isArray(raw.accent_colors) || raw.accent_colors.length === 0) { - throw new TypeError('design.accent_colors must be a non-empty string array') - } - patch.accentColors = raw.accent_colors.map((color) => ( - normalizePresentationDesignColor(requiredString(color, 'design.accent_colors[]')) - )) - } - if (raw.title_font_family !== undefined) patch.titleFontFamily = requiredString(raw.title_font_family, 'design.title_font_family') - if (raw.body_font_family !== undefined) patch.bodyFontFamily = requiredString(raw.body_font_family, 'design.body_font_family') - if (raw.page_size !== undefined) patch.pageSize = enumValue(raw.page_size, pageSizes, 'design.page_size') - if (raw.title !== undefined) { - if (typeof raw.title !== 'string') throw new TypeError('design.title must be a string') - patch.title = raw.title.trim() - } - if (raw.footer !== undefined) { - if (!raw.footer || typeof raw.footer !== 'object' || Array.isArray(raw.footer)) { - throw new TypeError('design.footer must be a mapping') - } - const footerRaw = raw.footer as Record - patch.footer = { - ...(footerRaw.text === undefined ? {} : { text: stringValue(footerRaw.text, 'design.footer.text') }), - ...(footerRaw.show_date === undefined ? {} : { showDate: booleanValue(footerRaw.show_date, 'design.footer.show_date') }), - ...(footerRaw.show_slide_number === undefined - ? {} - : { showSlideNumber: booleanValue(footerRaw.show_slide_number, 'design.footer.show_slide_number') }), - } - } - if (raw.transition !== undefined) { - if (!raw.transition || typeof raw.transition !== 'object' || Array.isArray(raw.transition)) { - throw new TypeError('design.transition must be a mapping') - } - const transitionRaw = raw.transition as Record - const fallback = document.slides.pages.find((slide) => slide.id === document.slides.selectedPageId)?.transition - ?? { effect: 'none' as const, durationMs: 500 } - patch.transition = { - effect: transitionRaw.effect === undefined - ? fallback.effect - : enumValue(transitionRaw.effect, transitionEffects, 'design.transition.effect'), - durationMs: transitionRaw.duration_ms === undefined - ? fallback.durationMs - : nonNegativeNumber(transitionRaw.duration_ms, 'design.transition.duration_ms'), - } - const direction = transitionRaw.direction === undefined - ? fallback.direction - : enumValue(transitionRaw.direction, transitionDirections, 'design.transition.direction') - if (direction) patch.transition.direction = direction - const throughBlack = transitionRaw.through_black === undefined - ? fallback.throughBlack - : booleanValue(transitionRaw.through_black, 'design.transition.through_black') - if (throughBlack !== undefined) patch.transition.throughBlack = throughBlack +function replaceProject(collection: PowerPointProjectCollection, project: PresentationProject): PowerPointProjectCollection { + return { + activeProjectId: project.id, + projects: collection.projects.map((candidate) => candidate.id === project.id ? project : candidate), } - if (Object.keys(patch).length === 0) throw new Error('update_ppt_design requires at least one design change') - return patch } -function diagnostics(items: string[]): Array> { - return items.map((message) => ({ code: 'markdown_notice', message, severity: 'warning' })) +function requireActiveProject(collection: PowerPointProjectCollection): PresentationProject { + return requireProject(collection, collection.activeProjectId) } -function assetsValue(value: unknown): PresentationMarkdownAssets { - if (value === undefined) return {} - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('assets must be a mapping') - return value as Record +function requireProject(collection: PowerPointProjectCollection, projectId: string): PresentationProject { + const project = collection.projects.find((candidate) => candidate.id === projectId) + if (!project) throw new PowerPointProtocolError(`PowerPoint project not found: ${projectId}`, 'document_not_found') + return project } -function decodeBase64(value: string): Uint8Array { - const decoded = atob(value) - return Uint8Array.from(decoded, (character) => character.charCodeAt(0)) +function revisionOf(context: PowerPointRuntimeContext, projectId: string): number { + return context.revisionOf?.(projectId) ?? 1 } -function replaceDocument(workspace: PresentationWorkspace, document: PresentationDocument): PresentationWorkspace { - const validated = validatePresentationDocument(document) - return { - activeDocumentId: validated.id, - documents: workspace.documents.map((item) => item.id === validated.id ? validated : item), - } -} - -function replaceSlide(document: PresentationDocument, slide: PresentationSlide, assets: readonly PresentationAsset[] = []): PresentationDocument { - return { - ...document, - assets: mergePresentationAssets(document.assets, assets), - slides: replacePresentationPages( - document.slides, - document.slides.pages.map((item) => item.id === slide.id ? slide : item), - slide.id, - ), - revision: document.revision + 1, - } +function requireSlide(document: PresentationProject, pageId: string): PresentationSlide { + const slide = document.slides.pages.find((candidate) => candidate.id === pageId) + if (!slide) throw new Error(`PowerPoint page not found: ${pageId}`) + return slide } -function requireActiveDocument(workspace: PresentationWorkspace): PresentationDocument { - const document = workspace.documents.find((item) => item.id === workspace.activeDocumentId) - if (!document) throw new Error('The Session has no active PowerPoint') - return document +function decodeBase64(value: string): Uint8Array { + const decoded = atob(value) + return Uint8Array.from(decoded, (character) => character.charCodeAt(0)) } -function requireSlide(document: PresentationDocument, pageId: string): PresentationSlide { - const slide = document.slides.pages.find((item) => item.id === pageId) - if (!slide) throw new Error(`Unknown PowerPoint page: ${pageId}`) - return slide +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value) } function requiredString(value: unknown, name: string): string { - if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${name} is required`) + if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${name} must be a non-empty string`) return value.trim() } function optionalString(value: unknown, name: string): string | undefined { - if (value === undefined || value === null || value === '') return undefined + if (value === undefined || value === null) return undefined if (typeof value !== 'string') throw new TypeError(`${name} must be a string`) return value.trim() || undefined } -function stringValue(value: unknown, name: string): string { - if (typeof value !== 'string') throw new TypeError(`${name} must be a string`) - return value.trim() -} - -function booleanValue(value: unknown, name: string): boolean { +function optionalBoolean(value: unknown, name: string): boolean | undefined { + if (value === undefined) return undefined if (typeof value !== 'boolean') throw new TypeError(`${name} must be a boolean`) return value } -function nonNegativeNumber(value: unknown, name: string): number { - if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) { - throw new TypeError(`${name} must be a non-negative number`) +function stringArray(value: unknown, name: string): string[] | undefined { + if (value === undefined) return undefined + if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || !item.trim())) { + throw new TypeError(`${name} must be an array of non-empty strings`) } - return value + return [...new Set(value.map((item) => item.trim()))] } function enumValue(value: unknown, allowed: ReadonlySet, name: string): T { - if (typeof value !== 'string' || !allowed.has(value as T)) { - throw new Error(`${name} must be one of: ${[...allowed].join(', ')}`) - } - return value as T + const normalized = requiredString(value, name) + if (!allowed.has(normalized as T)) throw new Error(`Unsupported ${name}: ${normalized}`) + return normalized as T +} + +function assertKeys(value: Record, allowed: readonly string[], name: string): void { + const unexpected = Object.keys(value).find((key) => !allowed.includes(key)) + if (unexpected) throw new Error(`Unsupported ${name} parameter: ${unexpected}`) } diff --git a/desktop/apps/electron/src/renderer/lib/presentationDesign.ts b/desktop/apps/electron/src/renderer/lib/presentationDesign.ts index 9229fc39..d7876913 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationDesign.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationDesign.ts @@ -4,7 +4,7 @@ import { presentationSlideBackground, replacePresentationPages, type PresentationChartElement, - type PresentationDocument, + type PresentationProject, type PresentationElement, type PresentationFooter, type PresentationPageSizePreset, @@ -99,7 +99,7 @@ export function presentationThemePreset(id: PresentationThemePresetId): Presenta return preset } -export function matchingPresentationTheme(document: PresentationDocument): PresentationThemePresetId | 'custom' { +export function matchingPresentationTheme(document: PresentationProject): PresentationThemePresetId | 'custom' { const master = document.theme return PRESENTATION_THEME_PRESETS.find((preset) => ( preset.background === master.background @@ -110,7 +110,7 @@ export function matchingPresentationTheme(document: PresentationDocument): Prese ))?.id ?? 'custom' } -export function applyPresentationDesign(document: PresentationDocument, patch: PresentationDesignPatch): PresentationDocument { +export function applyPresentationDesign(document: PresentationProject, patch: PresentationDesignPatch): PresentationProject { const preset = patch.theme ? presentationThemePreset(patch.theme) : null const background = normalizePresentationDesignColor(patch.background ?? preset?.background ?? document.theme.background) const accentColors = (patch.accentColors ?? preset?.accentColors ?? document.theme.accentColors) @@ -172,7 +172,7 @@ export function applyPresentationDesign(document: PresentationDocument, patch: P return element } - let next: PresentationDocument = { + let next: PresentationProject = { ...document, ...(patch.title === undefined ? {} : { title: patch.title }), theme: { accentColors, background, bodyFontFamily, footer, titleFontFamily }, @@ -185,11 +185,11 @@ export function applyPresentationDesign(document: PresentationDocument, patch: P } })), } - if (patch.pageSize) next = resizePresentationDocument(next, patch.pageSize) + if (patch.pageSize) next = resizePresentationProject(next, patch.pageSize) return next } -export function resizePresentationDocument(document: PresentationDocument, preset: PresentationPageSizePreset): PresentationDocument { +export function resizePresentationProject(document: PresentationProject, preset: PresentationPageSizePreset): PresentationProject { const previousSize = getPresentationPageSize(document) const nextSize = PRESENTATION_PAGE_SIZES[preset] if (previousSize.preset === preset && previousSize.width === nextSize.width && previousSize.height === nextSize.height) { diff --git a/desktop/apps/electron/src/renderer/lib/presentationEditorDriver.ts b/desktop/apps/electron/src/renderer/lib/presentationEditorDriver.ts index a6859941..28377b51 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationEditorDriver.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationEditorDriver.ts @@ -1,4 +1,4 @@ -import type { PresentationDocument } from '@/atoms/presentation' +import type { PresentationProject } from '@/atoms/presentation' import type { OfficeEditorDriver, OfficeEditorLease } from './office/officeEditorBinding' export interface PresentationEditingObject { @@ -8,7 +8,7 @@ export interface PresentationEditingObject { } /** Canvas callbacks also belong to a slide, while the common lease identifies its document. */ -export function bindPresentationNativeEdit(lease: OfficeEditorLease, slideId: string, readDocument: () => PresentationDocument, apply: (...args: TArgs) => void): (...args: TArgs) => void { +export function bindPresentationNativeEdit(lease: OfficeEditorLease, slideId: string, readDocument: () => PresentationProject, apply: (...args: TArgs) => void): (...args: TArgs) => void { return (...args) => { if (!lease.isCurrent()) return const document = readDocument() @@ -17,9 +17,9 @@ export function bindPresentationNativeEdit(lease: Offic } } -/** Fabric is a projection of the Jotai document, not another document snapshot store. */ +/** Fabric is a projection of the PresentationStore project, not another project store. */ export function createPresentationEditorDriver(options: { - readSnapshot: () => PresentationDocument | null + readSnapshot: () => PresentationProject | null readEditingObject: () => PresentationEditingObject | null flushPendingEdit: () => void dispose: () => void @@ -40,5 +40,5 @@ export function createPresentationEditorDriver(options: { lease.assertCurrent() }, dispose: options.dispose, - } satisfies OfficeEditorDriver + } satisfies OfficeEditorDriver } diff --git a/desktop/apps/electron/src/renderer/lib/presentationFileController.ts b/desktop/apps/electron/src/renderer/lib/presentationFileController.ts index 7cfb2cd5..bc356b70 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationFileController.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationFileController.ts @@ -1,111 +1,98 @@ -import type { PresentationDocument, PresentationWorkspace } from '@/atoms/presentation' -import type { OfficeFilesAPI } from '../../shared/office-files' +import type { PresentationProject } from '@/atoms/presentation' +import type { OfficeFileSource, OfficeFilesAPI } from '../../shared/office-files' +import { + migratePresentationCheckpoint, + type PresentationCheckpoint, + type PresentationProjectMetadata, +} from '@/presentation/checkpoint' import { createOfficePersistenceScheduler } from './office/officePersistence' -import { isPresentationDirty } from './presentationWorkspaceRuntime' import { i18n } from './i18n' -import { createOfficeAutoSave } from './office/officeAutoSave' -import { migratePresentationDocument } from '@/presentation/project' -/** Source files and recovery checkpoints have deliberately separate writers. */ +/** PPTX is an import/export boundary; automatic persistence stores only project checkpoints. */ export function createPresentationFileController(options: { sessionId: string files: OfficeFilesAPI - read: () => PresentationWorkspace - write: (workspace: PresentationWorkspace) => void - encode: (document: PresentationDocument) => Promise + read: () => PresentationCheckpoint + commitExport: (projectId: string, fileName: string, source: OfficeFileSource, exportedRevision: number) => void + encode: (project: PresentationProject) => Promise flushEditor: () => Promise - locale: () => string - automatic?: boolean - runAutoSave?: (save: () => Promise) => Promise - onSaveStatus?: (status: 'saving' | 'saved' | 'error', error?: string) => void + /** Whether the destination is a Session-managed file rather than a user-owned import. */ + managed: boolean + onExportStatus?: (status: 'saving' | 'saved' | 'error', error?: string) => void }) { - const { files, read, write } = options - let ready = false - const recovery = createOfficePersistenceScheduler({ + const recovery = createOfficePersistenceScheduler({ policy: { appKind: 'presentation', sessionId: options.sessionId, kind: 'recovery', storage: 'recovery-file', automatic: true }, delayMs: 150, - write: (workspace) => files.setRecovery('presentation', options.sessionId, JSON.stringify(workspace)), + write: (checkpoint) => options.files.setRecovery('presentation', options.sessionId, JSON.stringify(checkpoint)), }) - const save = async (documentId: string, saveAs = false, destination?: string, background = false): Promise => { - if (!background) await options.flushEditor() - const document = read().documents.find((item) => item.id === documentId) - if (!document) throw new Error('The presentation is no longer open') - if (!saveAs && !isPresentationDirty(document)) { - // A successful source write can still leave a failed recovery checkpoint. - await recovery.persist(read()) - return !isPresentationDirty(read().documents.find((item) => item.id === documentId)!) + let ready = false + + const save = async (projectId: string, saveAs = false, destination?: string): Promise => { + await options.flushEditor() + const checkpoint = options.read() + const project = checkpoint.projects.find((item) => item.id === projectId) + const metadata = checkpoint.projectMetadata[projectId] + if (!project || !metadata) throw new Error('The presentation project is no longer open') + if (!saveAs && !isPresentationProjectDirty(metadata)) { + await recovery.persist(options.read()) + const current = options.read().projectMetadata[projectId] + return Boolean(current && !isPresentationProjectDirty(current)) } - if (document.sourceProtected && !saveAs && !options.automatic) throw new Error(i18n.t('office.protectedSave')) - const result = await files.save({ kind: 'presentation', managed: options.automatic, documentId, source: document.source, preserveSource: document.sourceProtected, saveAs, destination, suggestedName: `${document.title.replace(/\.pptx$/i, '') || 'Untitled'}.pptx`, bytes: await options.encode(document) }) + if (metadata.sourceProtected && !saveAs && !options.managed) throw new Error(i18n.t('office.protectedSave')) + const exportedRevision = metadata.revision + const result = await options.files.save({ + kind: 'presentation', + managed: options.managed, + documentId: projectId, + source: metadata.source, + preserveSource: metadata.sourceProtected, + saveAs, + destination, + suggestedName: `${project.title.replace(/\.pptx$/i, '') || 'Untitled'}.pptx`, + bytes: await options.encode(project), + }) if (!result.ok) { if (result.reason === 'conflict') throw new Error('The file changed outside the editor. Your edits have been retained; retry after resolving the file change.') if (result.reason === 'source-protected') throw new Error(i18n.t('office.protectedSave')) return false } - if (!background) await options.flushEditor() - const current = read() - write({ ...current, documents: current.documents.map((item) => { - if (item.id === documentId) return { ...item, title: result.fileName.replace(/\.pptx$/i, ''), source: result.source, sourceProtected: false, savedRevision: document.revision } - return item.source?.path === result.source.path ? { ...item, source: undefined, savedRevision: undefined } : item - }) }) - await recovery.persist(read()) - return !isPresentationDirty(read().documents.find((item) => item.id === documentId)!) + await options.flushEditor() + options.commitExport(projectId, result.fileName, result.source, exportedRevision) + await recovery.persist(options.read()) + const current = options.read().projectMetadata[projectId] + return Boolean(current && !isPresentationProjectDirty(current)) } - const saveDirty = async (requireComplete = false, background = false) => { - if (!background) await options.flushEditor() - for (const document of read().documents.filter(isPresentationDirty)) { - if (!await save(document.id, false, undefined, background) && requireComplete) throw new Error(i18n.t('office.changedDuringClose')) - } - } - const autoSave = createOfficeAutoSave(() => options.runAutoSave ? options.runAutoSave(() => saveDirty(false, true)) : saveDirty(false, true), options.onSaveStatus) + return { recovery, - autoSave, - saveDirty, - async restore() { - const serialized = await files.getRecovery('presentation', options.sessionId) - if (serialized !== null) { - const workspace = JSON.parse(serialized) as { activeDocumentId?: unknown; documents?: unknown } - if (!Array.isArray(workspace.documents) || typeof workspace.activeDocumentId !== 'string') throw new Error('The PowerPoint recovery checkpoint is invalid') - const documents = workspace.documents.map((document) => migratePresentationDocument(document)) - if (documents.length) write({ activeDocumentId: workspace.activeDocumentId, documents: documents.map((document) => ({ - ...document, sourceProtected: document.sourceProtected ?? Boolean(document.source && document.source.mtimeMs !== null), - })) }) - } + async restore(): Promise { + const serialized = await options.files.getRecovery('presentation', options.sessionId) + const checkpoint = serialized === null ? null : migratePresentationCheckpoint(JSON.parse(serialized)) ready = true - if (options.automatic) autoSave.schedule(read().documents.filter(isPresentationDirty).map((document) => `${document.id}:${document.revision}`).join('|')) + return checkpoint }, schedule() { - if (!ready) return - recovery.schedule(read()) - if (options.automatic) autoSave.schedule(read().documents.filter(isPresentationDirty).map((document) => `${document.id}:${document.revision}`).join('|')) + if (ready) recovery.schedule(options.read()) }, async flush() { if (!ready) throw new Error('PowerPoint recovery is not ready') await options.flushEditor() - await recovery.persist(read()) + await recovery.persist(options.read()) }, - async save(documentId: string, saveAs = false, destination?: string) { - options.onSaveStatus?.('saving') + async save(projectId: string, saveAs = false, destination?: string) { + options.onExportStatus?.('saving') try { - const saved = await save(documentId, saveAs, destination) - options.onSaveStatus?.(saved ? 'saved' : 'saving') + const saved = await save(projectId, saveAs, destination) + options.onExportStatus?.(saved ? 'saved' : 'saving') return saved } catch (error) { - options.onSaveStatus?.('error', error instanceof Error ? error.message : String(error)) + options.onExportStatus?.('error', error instanceof Error ? error.message : String(error)) throw error } }, - async beforeClose(documentId: string): Promise { - await options.flushEditor() - const document = read().documents.find((item) => item.id === documentId) - if (!document || !isPresentationDirty(document)) return true - if (options.automatic) return save(documentId) - const decision = await files.confirmClose(`${document.title.replace(/\.pptx$/i, '')}.pptx`, options.locale()) - if (decision === 'cancel') return false - if (decision === 'save') return save(documentId, Boolean(document.sourceProtected)) - await options.flushEditor() - return read().documents.find((item) => item.id === documentId)?.revision === document.revision - }, } } + +export function isPresentationProjectDirty(metadata: PresentationProjectMetadata): boolean { + return !metadata.source || metadata.source.mtimeMs === null || metadata.savedRevision !== metadata.revision +} diff --git a/desktop/apps/electron/src/renderer/lib/presentationImport.ts b/desktop/apps/electron/src/renderer/lib/presentationImport.ts index c4d168df..9c7c7e0e 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationImport.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationImport.ts @@ -1,4 +1,4 @@ -import type { PresentationDocument } from '@/atoms/presentation' +import type { PresentationProject } from '@/atoms/presentation' import type { PresentationPptxImportOptions } from './presentationPptxImport' import { runOfficeImportWorker } from './office/officeImportWorker' @@ -8,12 +8,12 @@ export interface PresentationImportRequest { options: PresentationPptxImportOptions } -export function importPresentationInBackground(input: Uint8Array | ArrayBuffer | string, fileName: string, options: PresentationPptxImportOptions = {}): Promise { +export function importPresentationInBackground(input: Uint8Array | ArrayBuffer | string, fileName: string, options: PresentationPptxImportOptions = {}): Promise { let owned: Uint8Array | string if (typeof input === 'string') owned = input else if (input instanceof Uint8Array) owned = input.slice() else owned = new Uint8Array(input.slice(0)) - return runOfficeImportWorker( + return runOfficeImportWorker( () => new Worker(new URL('./presentationImport.worker.ts', import.meta.url), { type: 'module' }), { input: owned, fileName, options: { restoreEditorModel: true, ...options } } satisfies PresentationImportRequest, typeof owned === 'string' ? [] : [owned.buffer], diff --git a/desktop/apps/electron/src/renderer/lib/presentationImport.worker.ts b/desktop/apps/electron/src/renderer/lib/presentationImport.worker.ts index 823b6a1c..452aa392 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationImport.worker.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationImport.worker.ts @@ -1,10 +1,10 @@ import { importPresentationPptx } from './presentationPptxImport' import type { PresentationImportRequest } from './presentationImport' -import type { PresentationDocument } from '@/atoms/presentation' +import type { PresentationProject } from '@/atoms/presentation' import type { OfficeImportWorkerReply } from './office/officeImportWorker' self.onmessage = async ({ data }: MessageEvent) => { - let response: OfficeImportWorkerReply + let response: OfficeImportWorkerReply try { const bytes = typeof data.input === 'string' ? Uint8Array.from(atob(data.input), (character) => character.charCodeAt(0)) diff --git a/desktop/apps/electron/src/renderer/lib/presentationMarkdown.ts b/desktop/apps/electron/src/renderer/lib/presentationMarkdown.ts index f7e77ccf..5a82935c 100644 --- a/desktop/apps/electron/src/renderer/lib/presentationMarkdown.ts +++ b/desktop/apps/electron/src/renderer/lib/presentationMarkdown.ts @@ -1,1158 +1,18 @@ -import { dump, load } from 'js-yaml' -import { marked, type Token, type Tokens } from 'marked' -import { - PRESENTATION_ANIMATION_EFFECTS, - PRESENTATION_ANIMATION_STARTS, - PRESENTATION_ANIMATION_TRIGGERS, - PRESENTATION_CHART_TYPES, - PRESENTATION_PAGE_SIZES, - PRESENTATION_SHAPE_TYPES, - PRESENTATION_SLIDE_LAYOUTS, - PRESENTATION_TRANSITION_DIRECTIONS, - PRESENTATION_TRANSITION_EFFECTS, - createBlankPresentationDocument, - createBlankPresentationSlide, - presentationSlideBackground, - replacePresentationPages, - type PresentationAsset, - type PresentationChartElement, - type PresentationDocument, - type PresentationElement, - type PresentationFileSource, - type PresentationFooter, - type PresentationPageSize, - type PresentationShapeType, - type PresentationSlide, - type PresentationSlideLayout, - type PresentationTheme, - type PresentationTextElement, - type PresentationTextRun, - type PresentationTextParagraph, - type PresentationParagraphStyle, - type PresentationTextStyle, - type PresentationTransition, -} from '@/atoms/presentation' -import { normalizePresentationDesignColor, presentationThemeTextColors } from '@/lib/presentationDesign' -import { patchPresentationText, PRESENTATION_TEXT_STYLE_KEYS, PRESENTATION_TEXT_RUN_STYLE_KEYS, PRESENTATION_PARAGRAPH_STYLE_KEYS, PRESENTATION_NUMBER_FORMATS } from '@/lib/presentationText' -import { createPresentationAsset, mergePresentationAssets, normalizePresentationProject, presentationAsset, presentationElementSource } from '@/presentation/project' +import { dump } from 'js-yaml' +import type { PresentationProject, PresentationElement, PresentationSlide } from '@/atoms/presentation' +import { presentationElementSource } from '@/presentation/project' -export type PresentationMarkdownAssets = Record - -interface CompilePresentationMarkdownOptions { - assets?: PresentationMarkdownAssets - existingDocument?: PresentationDocument -} - -interface CompilePresentationMarkdownResult { - diagnostics: string[] - document: PresentationDocument -} - -interface CompilePresentationSlideMarkdownOptions extends CompilePresentationMarkdownOptions { - document: PresentationDocument -} - -interface CompilePresentationSlideMarkdownResult { - assets: PresentationAsset[] - diagnostics: string[] - slide: PresentationSlide -} - -interface CompilePresentationElementMarkdownOptions extends CompilePresentationMarkdownOptions { - document: PresentationDocument - elementId?: string - slide: PresentationSlide -} - -interface CompilePresentationElementMarkdownResult { - assets: PresentationAsset[] - diagnostics: string[] - element: PresentationElement -} - -interface ParsedSlideSource { - body: string - frontmatter: Record - index: number -} - -interface ParsedBody { - body: string - notes: string -} - -interface LayoutCursor { - full: number - left: number - right: number - slot: 'full' | 'left' | 'right' -} - -interface ElementCompilerContext { - assets: PresentationMarkdownAssets - background: string - cursor: LayoutCursor - diagnostics: string[] - elementOrdinal: number - existingDocument?: PresentationDocument - pageSize: PresentationPageSize - projectAssets: PresentationAsset[] - slideId: string - theme: PresentationTheme - usedElementIds: Set -} - -interface NativeComponent { - attrs: Record - body: string - name: 'PptAudio' | 'PptChart' | 'PptImage' | 'PptShape' | 'PptTable' | 'PptText' | 'PptVideo' -} - -const MAX_SLIDES = 200 -const MAX_ELEMENTS_PER_SLIDE = 1_000 -const ID_PATTERN = /^[A-Za-z0-9_.:-]+$/ -const NATIVE_COMPONENT_PATTERN = /^]*?)(?:\/\s*>|>([\s\S]*?)<\/Ppt\1\s*>)/ -const SHAPE_TYPES = new Set(PRESENTATION_SHAPE_TYPES) -const LAYOUTS = new Set(PRESENTATION_SLIDE_LAYOUTS) -const TRANSITION_EFFECTS = new Set(PRESENTATION_TRANSITION_EFFECTS) -const TRANSITION_DIRECTIONS = new Set>(PRESENTATION_TRANSITION_DIRECTIONS) -const ANIMATION_EFFECTS = new Set(PRESENTATION_ANIMATION_EFFECTS) -const ANIMATION_STARTS = new Set(PRESENTATION_ANIMATION_STARTS) -const ANIMATION_TRIGGERS = new Set(PRESENTATION_ANIMATION_TRIGGERS) -const CHART_TYPES = new Set(PRESENTATION_CHART_TYPES) -const MEDIA_COMPONENT_NAMES = new Set(['PptImage', 'PptAudio', 'PptVideo']) -const COMMON_COMPONENT_ATTRS = new Set([ - 'id', 'ref', 'x', 'y', 'width', 'height', 'rotation', 'opacity', 'groupId', 'shadow', - 'flipHorizontal', 'flipVertical', - 'animation', 'animationDuration', 'animationDelay', 'animationStart', 'animationTrigger', - 'animationColor', 'href', 'slideHref', 'tooltip', -]) -const COMPONENT_ATTRS: Record> = { - PptText: new Set([ - ...COMMON_COMPONENT_ATTRS, - 'fontSize', 'fontFamily', 'fontWeight', 'italic', 'underline', 'strikethrough', 'baseline', - 'highlightColor', 'characterSpacing', 'lineHeight', 'indentLevel', 'listStyle', 'color', 'align', - 'verticalAlign', 'textDirection', 'wordWrap', 'insetLeft', 'insetTop', 'insetRight', 'insetBottom', 'textRuns', 'paragraphs', 'lineSpacing', - ]), - PptShape: new Set([...COMMON_COMPONENT_ATTRS, 'kind', 'type', 'fill', 'borderColor', 'borderWidth', 'radius', 'connectorPath']), - PptImage: new Set([ - ...COMMON_COMPONENT_ATTRS, - 'src', 'alt', 'altText', 'fit', 'clipShape', 'cropLeft', 'cropTop', 'cropRight', 'cropBottom', - ]), - PptAudio: new Set([...COMMON_COMPONENT_ATTRS, 'src', 'autoplay', 'loop', 'muted']), - PptVideo: new Set([...COMMON_COMPONENT_ATTRS, 'src', 'autoplay', 'loop', 'muted']), - PptTable: new Set([ - ...COMMON_COMPONENT_ATTRS, - 'headerRow', 'headerFill', 'headerTextColor', 'bodyFill', 'textColor', 'borderColor', 'fontSize', - ]), - PptChart: new Set([ - ...COMMON_COMPONENT_ATTRS, - 'type', 'chartType', 'showLegend', 'showValue', 'displayBlanksAs', 'holeSize', 'title', 'colors', 'chartAreaFill', - 'plotAreaFill', 'categoryAxisLabelColor', 'valueAxisLabelColor', 'gridLineColor', 'dataLabelColor', - ]), -} - -/** Compile a complete Slidev-style Markdown deck into the native editable PPT IR. */ -export function compilePresentationMarkdown( - markdown: string, - options: CompilePresentationMarkdownOptions = {}, -): CompilePresentationMarkdownResult { - const sources = parsePresentationMarkdown(markdown) - if (sources.length > MAX_SLIDES) throw new Error(`A presentation may contain at most ${MAX_SLIDES} slides`) - const blank = createBlankPresentationDocument(optionalString(sources[0]!.frontmatter.title) ?? '') - const pageSize = parsePageSize(sources[0]!.frontmatter.pageSize) - const theme = parseTheme(sources[0]!.frontmatter.theme, blank.theme) - const usedSlideIds = new Set() - const usedElementIds = new Set() - const diagnostics: string[] = [] - const projectAssets: PresentationAsset[] = [] - const slides = sources.map((source) => compileSlideSource(source, { - assets: options.assets ?? {}, - diagnostics, - existingDocument: options.existingDocument, - pageSize, - projectAssets, - theme, - usedElementIds, - usedSlideIds, - })) - const existingSelection = options.existingDocument?.slides.selectedPageId - const selectedPageId = existingSelection && slides.some((slide) => slide.id === existingSelection) - ? existingSelection - : slides[0]!.id - return { - diagnostics, - document: normalizePresentationProject({ - ...blank, - id: options.existingDocument?.id ?? blank.id, - theme, - pageSize, - assets: projectAssets, - slides: replacePresentationPages(blank.slides, slides, selectedPageId), - title: optionalString(sources[0]!.frontmatter.title) ?? options.existingDocument?.title ?? '', - revision: options.existingDocument?.revision ?? 1, - }), - } -} - -/** Compile exactly one slide Markdown fragment against an existing document. */ -export function compilePresentationSlideMarkdown( - markdown: string, - options: CompilePresentationSlideMarkdownOptions, -): CompilePresentationSlideMarkdownResult { - const sources = parsePresentationMarkdown(markdown) - if (sources.length !== 1) throw new Error('A slide update must contain exactly one Markdown slide') - const usedSlideIds = new Set(options.document.slides.pages.map((slide) => slide.id)) - const requestedId = optionalString(sources[0]!.frontmatter.id) - if (requestedId) usedSlideIds.delete(requestedId) - const usedElementIds = new Set(options.document.slides.pages.flatMap((slide) => ( - slide.id === requestedId ? [] : slide.elements.map((element) => element.id) - ))) - const diagnostics: string[] = [] - const projectAssets: PresentationAsset[] = [] - const slide = compileSlideSource(sources[0]!, { - assets: options.assets ?? {}, - diagnostics, - existingDocument: options.existingDocument ?? options.document, - pageSize: options.document.pageSize, - projectAssets, - theme: options.document.theme, - usedElementIds, - usedSlideIds, - }) - return { assets: projectAssets, diagnostics, slide } -} - -/** Compile exactly one canonical Ppt* element fragment against a live slide. */ -export function compilePresentationElementMarkdown( - markdown: string, - options: CompilePresentationElementMarkdownOptions, -): CompilePresentationElementMarkdownResult { - if (typeof markdown !== 'string' || !markdown.trim()) throw new TypeError('PowerPoint element Markdown is required') - const components = parseNativeComponents(markdown) - if (!components || components.length !== 1) { - throw new Error('PowerPoint element Markdown must contain exactly one Ppt* element') - } - const component = components[0]! - const requested = componentRef(component.attrs) - if (options.elementId) { - if (requested && requested !== options.elementId) { - throw new Error(`PowerPoint element ref must remain ${options.elementId}`) - } - component.attrs.ref = options.elementId - delete component.attrs.id - } else if (requested) { - throw new Error('A new PowerPoint element must not provide id or ref; the editor assigns its ref') - } - const usedElementIds = new Set(options.document.slides.pages.flatMap((slide) => ( - slide.elements.flatMap((element) => element.id === options.elementId ? [] : [element.id]) - ))) - const diagnostics: string[] = [] - const projectAssets: PresentationAsset[] = [] - const context: ElementCompilerContext = { - assets: options.assets ?? {}, - background: presentationSlideBackground(options.document.theme, options.slide), - cursor: { full: 56, left: 76, right: 76, slot: 'full' }, - diagnostics, - elementOrdinal: options.slide.elements.length, - existingDocument: options.existingDocument ?? options.document, - pageSize: options.document.pageSize, - projectAssets, - slideId: options.slide.id, - theme: options.document.theme, - usedElementIds, - } - return { assets: projectAssets, diagnostics, element: compileNativeComponent(component, context) } -} - -/** Return the local paths referenced by parsed Markdown without mutating any presentation state. */ -export function inspectPresentationMarkdownAssets(markdown: string): string[] { - const paths = new Set() - if (markdown.trimStart().startsWith(' { - if (nestedToken.type === 'image') collectAssetPath((nestedToken as Tokens.Image).href, paths) - }) - } - } - return [...paths] -} - -/** Produce one canonical, self-contained slide Markdown fragment. */ +/** Produce a compact, read-only Agent projection of one native slide. */ export function decompilePresentationSlideMarkdown( slide: PresentationSlide, - project?: Pick, + project?: Pick, ): string { - return decompileSlide(slide, project) -} - -/** Produce one canonical Agent-editable element fragment with a stable ref. */ -export function decompilePresentationElementMarkdown(element: PresentationElement, project?: Pick): string { - return decompileElement(element, project) -} - -function parsePresentationMarkdown(markdown: string): ParsedSlideSource[] { - if (typeof markdown !== 'string' || !markdown.trim()) throw new TypeError('PowerPoint Markdown is required') - const lines = markdown.replace(/\r\n?/g, '\n').split('\n') - const delimiters = findTopLevelDelimiters(lines) - const firstContentLine = lines.findIndex((line) => line.trim()) - if (firstContentLine < 0 || delimiters[0] !== firstContentLine) { - throw new Error('PowerPoint Markdown must begin with a --- frontmatter block') - } - if (delimiters.length < 2 || delimiters.length % 2 !== 0) { - throw new Error('Every PowerPoint slide must have a closed --- frontmatter block') - } - const slides: ParsedSlideSource[] = [] - for (let pair = 0; pair < delimiters.length; pair += 2) { - const open = delimiters[pair]! - const close = delimiters[pair + 1]! - const next = delimiters[pair + 2] ?? lines.length - if (close <= open + 0) throw new Error(`Slide ${pair / 2 + 1} has invalid frontmatter`) - const yamlSource = lines.slice(open + 1, close).join('\n') - let value: unknown - try { - value = load(yamlSource) ?? {} - } catch (error) { - throw new Error(`Invalid YAML in slide ${pair / 2 + 1}: ${error instanceof Error ? error.message : String(error)}`) - } - if (!isRecord(value)) throw new TypeError(`Slide ${pair / 2 + 1} frontmatter must be a YAML mapping`) - slides.push({ body: lines.slice(close + 1, next).join('\n').trim(), frontmatter: value, index: pair / 2 }) - } - if (slides.length === 0) throw new Error('A presentation must contain at least one slide') - return slides -} - -function findTopLevelDelimiters(lines: string[]): number[] { - const delimiters: number[] = [] - let fence: { character: '`' | '~'; length: number } | null = null - let inComment = false - let opaqueTag: 'script' | 'style' | 'template' | null = null - let nativeComponent: { name: string; openingTag: boolean } | null = null - lines.forEach((line, index) => { - if (fence) { - if (new RegExp(`^ {0,3}${fence.character}{${fence.length},}\\s*$`).test(line)) fence = null - return - } - if (inComment) { - if (line.includes('-->')) inComment = false - return - } - if (opaqueTag) { - if (new RegExp(``, 'i').test(line)) opaqueTag = null - return - } - if (nativeComponent) { - if (nativeComponent.openingTag) { - if (/\/\s*>/.test(line)) nativeComponent = null - else if (/>/.test(line)) { - nativeComponent = new RegExp(``).test(line) - ? null - : { ...nativeComponent, openingTag: false } - } - } else if (new RegExp(``).test(line)) { - nativeComponent = null - } - return - } - const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})/) - if (fenceMatch) { - fence = { - character: fenceMatch[1]![0] as '`' | '~', - length: fenceMatch[1]!.length, - } - return - } - const commentStart = line.indexOf('', commentStart + 4) < 0) { - inComment = true - return - } - const opaqueMatch = line.match(/<(script|style|template)\b/i) - if (opaqueMatch && !new RegExp(``, 'i').test(line)) { - opaqueTag = opaqueMatch[1]!.toLowerCase() as 'script' | 'style' | 'template' - return - } - const nativeMatch = line.match(/<(Ppt(?:Text|Shape|Image|Audio|Video|Table|Chart))\b/) - if (nativeMatch && !/\/\s*>/.test(line) && !new RegExp(``).test(line)) { - nativeComponent = { name: nativeMatch[1]!, openingTag: !/>/.test(line) } - return - } - if (/^---\s*$/.test(line)) delimiters.push(index) - }) - return delimiters -} - -function compileSlideSource( - source: ParsedSlideSource, - context: Omit & { usedSlideIds: Set }, -): PresentationSlide { - const frontmatter = source.frontmatter - const id = optionalString(frontmatter.id) ?? `slide-${source.index + 1}` - validateId(id, 'slide id') - if (context.usedSlideIds.has(id)) throw new Error(`Duplicate slide id: ${id}`) - context.usedSlideIds.add(id) - const template = createBlankPresentationSlide(optionalString(frontmatter.name) ?? `Slide ${source.index + 1}`) - const background = frontmatter.background === undefined - ? undefined - : requiredString(frontmatter.background, 'background') - const parsedBody = extractNotes(source.body) - const cursor: LayoutCursor = { full: 56, left: 76, right: 76, slot: 'full' } - const elementContext: ElementCompilerContext = { - ...context, - background: background ?? context.theme.background, - cursor, - elementOrdinal: 0, - slideId: id, - } - const elements = compileMarkdownBlocks(parsedBody.body, elementContext) - if (elements.length > MAX_ELEMENTS_PER_SLIDE) { - throw new Error(`Slide ${id} may contain at most ${MAX_ELEMENTS_PER_SLIDE} elements`) - } - return { - ...template, - ...(background === undefined ? {} : { background }), - ...(frontmatter.comments === undefined ? {} : { comments: parseComments(frontmatter.comments, id) }), - elements, - ...(frontmatter.footer === undefined ? {} : { footer: parseFooter(frontmatter.footer, 'footer') }), - id, - layout: parseLayout(frontmatter.layout), - name: optionalString(frontmatter.name) ?? `Slide ${source.index + 1}`, - notes: parsedBody.notes, - transition: parseTransition(frontmatter.transition, template.transition), - } -} - -function extractNotes(body: string): ParsedBody { - const match = body.match(/(?:^|\n)\s*\s*$/i) - if (!match || match.index === undefined) return { body, notes: '' } - return { body: body.slice(0, match.index).trimEnd(), notes: match[1]!.trim() } -} - -function parseNativeComponents(source: string): NativeComponent[] | null { - let remaining = source.trim() - const components: NativeComponent[] = [] - while (remaining) { - const match = remaining.match(NATIVE_COMPONENT_PATTERN) - if (!match) return null - components.push({ - attrs: parseComponentAttrs(match[2] ?? ''), - body: (match[3] ?? '').replace(/^\n/, '').replace(/\n$/, ''), - name: `Ppt${match[1]}` as NativeComponent['name'], - }) - remaining = remaining.slice(match[0].length).trimStart() - } - return components.length > 0 ? components : null -} - -function parseComponentAttrs(source: string): Record { - const attrs: Record = {} - const consumed = source.replace(/([A-Za-z_][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g, (_, key: string, double: string, single: string) => { - attrs[key] = decodeEntities(double ?? single ?? '') - return ' ' - }) - for (const token of consumed.trim().split(/\s+/).filter(Boolean)) { - if (!/^[A-Za-z_][\w:.-]*$/.test(token)) throw new Error(`Invalid native component attributes: ${source.trim()}`) - attrs[token] = 'true' - } - return attrs -} - -function compileMarkdownBlocks(source: string, context: ElementCompilerContext): PresentationElement[] { - if (!source.trim()) return [] - const elements: PresentationElement[] = [] - for (const token of marked.lexer(source, { gfm: true })) { - if (token.type === 'space') continue - if (token.type !== 'code') { - const components = parseNativeComponents(token.raw) - if (components) { - for (const component of components) { - const element = compileNativeComponent(component, context) - elements.push(element) - const slot = context.cursor.slot - context.cursor[slot] = Math.max(context.cursor[slot], element.y + element.height + 18) - } - continue - } - } - if (token.type === 'html') { - const raw = token.raw.trim() - if (/^$/.test(raw)) continue - if (/^$/i.test(raw)) { - context.diagnostics.push(`[slide_ref=${context.slideId}]