diff --git a/docs/images/paper-writing-workbench.png b/docs/images/paper-writing-workbench.png new file mode 100644 index 0000000000..5349fdbf21 Binary files /dev/null and b/docs/images/paper-writing-workbench.png differ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 92b333e909..6977203024 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -540,6 +540,9 @@ importers: path-browserify: specifier: ^1.0.1 version: 1.0.1 + pdf-lib: + specifier: 1.17.1 + version: 1.17.1 pdfjs-dist: specifier: 5.4.624 version: 5.4.624 diff --git a/src/apps/desktop/README.md b/src/apps/desktop/README.md index 0c2233d81b..3af4631ee1 100644 --- a/src/apps/desktop/README.md +++ b/src/apps/desktop/README.md @@ -137,7 +137,33 @@ agent to draft or revise files in your workspace. Open the main `.tex` file from the file tree or its chat link. The editor shows source on the left and the typeset PDF on the right. Use **Save & compile** or turn on **Auto compile** to save and recompile the main source after you pause. A failed build keeps the -last successful preview and shows the compiler log. +last successful preview and shows the compiler log. The source and PDF panes can +be closed independently, restored from the header, and resized by dragging their +divider. Hidden source views retain the document and its undo history. + +The source toolbar includes undo/redo, find/replace, a section outline, and +snippets for equations, figures, tables, and references. Command, environment, +and in-document label completions are available in Monaco. Select the main TeX +entry when editing an included chapter, or add a `% !TeX root = ../main.tex` +comment. Compiler diagnostics for the current file link back to their source line. + +PDF review supports text highlights, sticky notes, comment threads, freehand ink, +annotation colors, resolution, deletion, and undo/redo. Reviews are automatically +saved beside the source as `.openbitfun-review.json`; include that file +when moving or sharing the project. **Save PDF** writes an editable +`.annotated.pdf` to the workspace. **Export annotated PDF** saves a copy +on the viewing device. Saved PDFs embed their review state so notes and threads +can be edited again when reopened in OpenBitFun; other PDF applications see +standard PDF annotations. Replacing an existing output checks its current +version and asks before overwriting an externally changed file. + +Annotations retain PDF page coordinates across compilation. Check their positions +when a revision changes the layout; the preview shows a reminder after recompiling. +LaTeX source remains the place to change manuscript text and figures. + +![LaTeX source, PDF preview, and review notes in a sample writing workspace](../../../docs/images/paper-writing-workbench.png) + +The image uses a sample paper in an isolated UI fixture. Install `latexmk` and the selected pdfLaTeX or XeLaTeX engine on the machine that owns the workspace. For SSH, Docker, and WSL workspaces, compile in that diff --git a/src/apps/desktop/src/api/latex_api.rs b/src/apps/desktop/src/api/latex_api.rs index 0e84c617d6..cbe9bca005 100644 --- a/src/apps/desktop/src/api/latex_api.rs +++ b/src/apps/desktop/src/api/latex_api.rs @@ -54,6 +54,13 @@ pub struct CompileWorkspaceLatexRequest { #[serde(rename_all = "camelCase")] pub struct CompileWorkspaceLatexResponse { pdf_base64: String, + log: String, +} + +#[derive(Debug)] +struct CompiledLatex { + pdf: Vec, + log: String, } #[tauri::command] @@ -63,15 +70,16 @@ pub async fn compile_workspace_latex( let workspace = WorkspaceBinding::resolve(&request.workspace_id) .await .map_err(|error| error.to_string())?; - let pdf_base64 = if workspace.is_remote() { + let (pdf_base64, log) = if workspace.is_remote() { let connection_id = workspace .connection_id() .ok_or("Remote workspace is disconnected.")?; compile_remote(connection_id, &workspace.root_path_string(), &request).await? } else { - BASE64.encode(compile_local(workspace.root_path(), &request).await?) + let output = compile_local(workspace.root_path(), &request).await?; + (BASE64.encode(output.pdf), output.log) }; - Ok(CompileWorkspaceLatexResponse { pdf_base64 }) + Ok(CompileWorkspaceLatexResponse { pdf_base64, log }) } // latexmk invokes TeX and bibliography programs via their command templates. @@ -93,7 +101,7 @@ fn source_stem(file_name: &str) -> Result<&str, String> { async fn compile_local( root: &Path, request: &CompileWorkspaceLatexRequest, -) -> Result, String> { +) -> Result { let source = root.join(&request.file_path); let root = tokio::fs::canonicalize(root) .await @@ -156,14 +164,14 @@ async fn compile_local( .await .map_err(|_| "LaTeX compilation timed out.")? .map_err(|error| error.to_string())?; + let log = format!("{stdout}\n{stderr}"); if !status.success() { - let log = format!("{stdout}\n{stderr}"); return Err(format!("latexmk exited with {status}.\n{}", log.trim())); } drop(child); let pdf = build.path().join(format!("{stem}.pdf")); - tokio::task::spawn_blocking(move || { + let pdf = tokio::task::spawn_blocking(move || -> Result, String> { let _build = build; let metadata = std::fs::symlink_metadata(&pdf).map_err(|_| MISSING_PDF)?; if !metadata.is_file() || is_symlink_or_reparse(&metadata) { @@ -176,7 +184,8 @@ async fn compile_local( } }) .await - .map_err(|error| error.to_string())? + .map_err(|error| error.to_string())??; + Ok(CompiledLatex { pdf, log }) } async fn read_log_tail(mut reader: impl AsyncRead + Unpin) -> std::io::Result { @@ -229,6 +238,7 @@ if latexmk {arguments} "-outdir=$build" "$source" "$build/compile.lo pdf="$build/"{pdf} [ -f "$pdf" ] && [ ! -L "$pdf" ] || {{ echo "{MISSING_PDF}" >&2; exit 1; }} [ "$(wc -c < "$pdf")" -le {MAX_PDF_BYTES} ] || {{ echo "The PDF exceeds the 8 MiB preview limit." >&2; exit 1; }} + tail -c {MAX_LOG_BYTES} "$build/compile.log" >&2 base64 < "$pdf" else tail -c {MAX_LOG_BYTES} "$build/compile.log" >&2 @@ -247,7 +257,7 @@ async fn compile_remote( connection_id: &str, root: &str, request: &CompileWorkspaceLatexRequest, -) -> Result { +) -> Result<(String, String), String> { let command = remote_build_command(root, &request.file_path, request.engine)?; let manager = get_remote_workspace_manager().ok_or("Remote workspace is unavailable.")?; let ssh = manager @@ -288,7 +298,7 @@ async fn compile_remote( if pdf.len() > MAX_PDF_BYTES || !pdf.starts_with(b"%PDF-") { return Err(MISSING_PDF.into()); } - Ok(encoded) + Ok((encoded, result.stderr)) } #[cfg(test)] @@ -353,7 +363,8 @@ mod tests { engine: LatexEngine::PdfLatex, }; let pdf = compile_local(root.path(), &request).await.unwrap(); - assert!(pdf.starts_with(b"%PDF-")); + assert!(pdf.pdf.starts_with(b"%PDF-")); + assert!(pdf.log.contains("Latexmk")); assert!(!root.path().join("main draft.aux").exists()); assert_eq!( std::fs::read_to_string(previous_pdf).unwrap(), diff --git a/src/web-ui/package.json b/src/web-ui/package.json index 4a6ec2f2ba..a82dc0bfe9 100644 --- a/src/web-ui/package.json +++ b/src/web-ui/package.json @@ -79,6 +79,7 @@ "parse-entities": "^4.0.2", "partial-json": "^0.1.7", "path-browserify": "^1.0.1", + "pdf-lib": "1.17.1", "pdfjs-dist": "5.4.624", "prismjs": "^1.30.0", "qrcode.react": "^4.2.0", diff --git a/src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx b/src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx index a69daa198b..661b66c860 100644 --- a/src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx +++ b/src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx @@ -41,7 +41,7 @@ const ImageViewer = lazyWithRecovery(() => ); const PdfViewer = lazyWithRecovery(() => - import('@/tools/editor/components/PdfViewer').then(module => ({ + import('@/tools/editor/pdf-review/PdfReviewEditor').then(module => ({ default: module.default, })) ); @@ -417,6 +417,7 @@ const FlexiblePanel: React.FC = memo(({ isActiveTab={isActive} filePath={pdfViewerData.filePath || ''} fileName={content.title} + onDirtyStateChange={onDirtyStateChange} className="openbitfun-flexible-panel__pdf-viewer" /> )} diff --git a/src/web-ui/src/app/workbench/ContentResourceView.tsx b/src/web-ui/src/app/workbench/ContentResourceView.tsx index 2fc1d437f9..2ec096cb3e 100644 --- a/src/web-ui/src/app/workbench/ContentResourceView.tsx +++ b/src/web-ui/src/app/workbench/ContentResourceView.tsx @@ -39,8 +39,8 @@ export default function ContentResourceView({ resourceId, isActive }: { resource cancelText: t('workbench.cancel'), type: 'warning' }); if (choice === 'cancel') return false; if (choice === 'secondary') return true; - if (!document?.save || latest.scope.surfaceId !== getActiveSurfaceId()) return false; - await document.save(); + if (!document || latest.scope.surfaceId !== getActiveSurfaceId()) return false; + await document.saveAll(); return !useContentResourceStore.getState().resources[resourceId]?.isDirty; }), [document, resourceId, t]); useTabCloseShortcut('workbench-content', diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts index 287394fb51..91891e2293 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const peerModeMock = vi.hoisted(() => ({ active: true })); const stateMachineMock = vi.hoisted(() => ({ + getOrCreate: vi.fn(), get: vi.fn(() => ({ getCurrentState: () => 'idle', getContext: () => ({ lastUpdateTime: 0 }), @@ -20,9 +21,11 @@ vi.mock('@/infrastructure/peer-device/peerModeFlag', () => ({ vi.mock('../../state-machine', () => ({ stateMachineManager: stateMachineMock, + SessionExecutionEvent: { START: 'start' }, })); -vi.mock('../liveSessionInteractionStore', () => ({ +vi.mock('../liveSessionInteractionStore', async importOriginal => ({ + ...await importOriginal(), installLiveSessionInteractionMailbox: vi.fn(), })); @@ -42,9 +45,15 @@ import { runtimeProjectionCaughtUp, } from './PeerSessionRefreshModule'; import { processToolEvent } from './ToolEventModule'; +import { processNormalTextChunkInternal } from './TextChunkModule'; +import { convertDialogTurnToBackendFormat } from './PersistenceModule'; +import { resetDeviceSurfaceSwitchedForTest } from '@/infrastructure/peer-device/deviceSurfaceReconcile'; import { + isRuntimeSessionProjectionStale, markRuntimeSessionProjectionStale, + readRuntimeSessionProgress, resetRuntimeSessionEventGateForTest, + routeRuntimeSessionEvent, } from '@/infrastructure/peer-device/runtimeSessionEventGate'; describe('PeerSessionRefreshModule', () => { @@ -1067,6 +1076,8 @@ describe('PeerSessionRefreshModule journal apply', () => { vi.useFakeTimers(); peerModeMock.active = true; resetRuntimeSessionEventGateForTest(); + resetDeviceSurfaceSwitchedForTest(); + activateSurface(LOCAL_SURFACE_ID); stateMachineMock.get.mockReturnValue({ getCurrentState: () => 'processing', getContext: () => ({ lastUpdateTime: Date.now(), version: 0 }), @@ -1094,10 +1105,160 @@ describe('PeerSessionRefreshModule journal apply', () => { activeSessionId: null, })); vi.clearAllMocks(); + vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers(); }); + it.each([true, false])('replays a pristine local active restore when refresh is installed before hydrate: %s', async installBeforeHydrate => { + peerModeMock.active = false; + const store = FlowChatStore.getInstance(); + const sessionId = 'local-reload'; + const turnId = 'turn-live'; + const roundId = 'round-live'; + store.setState(prev => ({ + ...prev, + activeSessionId: sessionId, + sessions: new Map([[sessionId, { + sessionId, + title: 'Local reload', + workspaceId: 'workspace-1', + workspacePath: '/repo/OpenBitFun', + historyState: 'metadata-only', + isHistorical: true, + isTransient: false, + dialogTurns: [], + config: { agentType: 'PaperWriting' }, + createdAt: 1, + lastActiveAt: 1, + todos: [], + } as any]]), + })); + const context = { + flowChatStore: store, + eventBatcher: { flushNow: vi.fn(), clear: vi.fn(), getBufferSize: () => 0 }, + contentBuffers: new Map(), + activeTextItems: new Map(), + runtimeStatusTimers: new Map(), + saveDebouncers: new Map(), + lastSaveTimestamps: new Map(), + lastSaveHashes: new Map(), + turnSaveInFlight: new Map(), + turnSavePending: new Set(), + } as any; + const apply = (eventName: string, payload: any): boolean => { + if (eventName === 'agentic://model-round-started') { + store.addModelRound(sessionId, turnId, { + id: roundId, index: 0, items: [], status: 'streaming', + isStreaming: true, isComplete: false, startTime: 1, + }); + } else if (eventName === 'agentic://text-chunk') { + processNormalTextChunkInternal(context, sessionId, turnId, roundId, payload.text); + } else if (eventName === 'agentic://tool-event') { + processToolEvent(context, sessionId, turnId, roundId, payload.toolEvent); + } + return true; + }; + agenticListenerMock.dispatchExternal.mockImplementation(apply); + const events = [ + { eventName: 'agentic://dialog-turn-started', payload: { sessionId, turnId } }, + { eventName: 'agentic://model-round-started', payload: { sessionId, turnId, roundId } }, + { eventName: 'agentic://text-chunk', payload: { sessionId, turnId, roundId, text: 'Hello' } }, + { eventName: 'agentic://tool-event', payload: { sessionId, turnId, roundId, toolEvent: { + event_type: 'Started', tool_id: 'read-1', tool_name: 'Read', params: { file_path: 'main.tex' }, + } } }, + { eventName: 'agentic://tool-event', payload: { sessionId, turnId, roundId, toolEvent: { + event_type: 'Completed', tool_id: 'read-1', tool_name: 'Read', result: 'source', + } } }, + ]; + const view = { + session: { sessionId, agentType: 'PaperWriting', state: 'Processing', createdAt: 1, turnCount: 7 }, + turns: [{ + turnId, turnIndex: 6, sessionId, timestamp: 1, + userMessage: { id: 'user-live', content: 'Open LaTeX', timestamp: 1 }, + modelRounds: [], startTime: 1, status: 'inprogress', + }], + contextRestoreState: 'pending', isPartial: true, loadedTurnCount: 1, totalTurnCount: 7, + turnCatalog: { schemaVersion: 1, sessionId, revision: 'catalog-1', complete: true, + totalTurnCount: 7, entries: [] }, + runtimeEventSnapshot: { sessionId, streamId: 'runtime-local', cursor: 5, activeTurnId: turnId, events }, + } as any; + let resolveRefresh!: (value: any) => void; + const restore = vi.spyOn(agentAPI, 'restoreSessionView') + .mockResolvedValueOnce(view) + .mockImplementationOnce(() => new Promise(resolve => { resolveRefresh = resolve; })); + let cleanup: (() => void) | undefined; + try { + if (installBeforeHydrate) cleanup = installPeerSessionRefresh(context); + await store.loadSessionHistory(sessionId); + expect(store.getState().sessions.get(sessionId)?.dialogTurns[0].modelRounds).toEqual([]); + expect(isRuntimeSessionProjectionStale(LOCAL_SURFACE_ID, sessionId)).toBe(true); + if (!installBeforeHydrate) cleanup = installPeerSessionRefresh(context); + await vi.advanceTimersByTimeAsync(1); + expect(restore).toHaveBeenCalledTimes(2); + + // Live delivery races the host read: the covered prefix must not repeat, + // and the suffix must wait for the journal's model round to exist. + const deliver = (cursor: number, text: string) => routeRuntimeSessionEvent( + LOCAL_SURFACE_ID, 'agentic://text-chunk', { + sessionId, turnId, roundId, text, + __openbitfunRuntimeStreamId: 'runtime-local', __openbitfunRuntimeEventCursor: cursor, + }, payload => { apply('agentic://text-chunk', payload); }, + ); + deliver(3, 'Hello'); + deliver(6, ' world'); + expect(agenticListenerMock.dispatchExternal).not.toHaveBeenCalled(); + resolveRefresh(view); + await vi.advanceTimersByTimeAsync(1); + + const turn = store.getState().sessions.get(sessionId)!.dialogTurns[0]; + expect(turn.modelRounds).toHaveLength(1); + expect(turn.modelRounds[0].items.find(item => item.type === 'text')).toMatchObject({ content: 'Hello world' }); + expect(store.findToolItem(sessionId, turnId, 'read-1')?.status).toBe('completed'); + expect(convertDialogTurnToBackendFormat(turn).modelRounds).toHaveLength(1); + expect(readRuntimeSessionProgress(LOCAL_SURFACE_ID, sessionId)).toEqual({ streamId: 'runtime-local', cursor: 6 }); + expect(isRuntimeSessionProjectionStale(LOCAL_SURFACE_ID, sessionId)).toBe(false); + await vi.advanceTimersByTimeAsync(60_000); + expect(restore).toHaveBeenCalledTimes(2); + } finally { + cleanup?.(); + } + }); + + it.each(['Idle', 'Processing'])('keeps pristine local persisted content without extra reads when a %s host has no journal', async state => { + peerModeMock.active = false; + const store = FlowChatStore.getInstance(); + const sessionId = 'local-legacy'; + store.setState(prev => ({ ...prev, activeSessionId: sessionId, sessions: new Map([[sessionId, { + sessionId, title: 'Local', workspaceId: 'workspace-1', workspacePath: '/repo/OpenBitFun', + historyState: 'metadata-only', isHistorical: true, isTransient: false, + dialogTurns: [], config: { agentType: 'PaperWriting' }, createdAt: 1, lastActiveAt: 1, todos: [], + } as any]]) })); + const restore = vi.spyOn(agentAPI, 'restoreSessionView').mockResolvedValue({ + session: { sessionId, state, agentType: 'PaperWriting', createdAt: 1 }, + turns: [{ + turnId: 'turn-legacy', turnIndex: 0, sessionId, timestamp: 1, + userMessage: { id: 'user-legacy', content: 'Open LaTeX', timestamp: 1 }, + modelRounds: [{ id: 'round-legacy', roundIndex: 0, startTime: 1, status: 'streaming', + textItems: [{ id: 'text-legacy', content: 'Persisted reply', timestamp: 1 }], toolItems: [], thinkingItems: [] }], + startTime: 1, status: state === 'Idle' ? 'completed' : 'inprogress', + }], contextRestoreState: 'ready', + } as any); + const cleanup = installPeerSessionRefresh({ + flowChatStore: store, eventBatcher: { flushNow: vi.fn(), clear: vi.fn() }, + contentBuffers: new Map(), activeTextItems: new Map(), + } as any); + try { + await store.loadSessionHistory(sessionId); + await vi.advanceTimersByTimeAsync(60_000); + expect(store.getState().sessions.get(sessionId)?.dialogTurns[0].modelRounds[0].items[0]).toMatchObject({ content: 'Persisted reply' }); + expect(restore).toHaveBeenCalledTimes(1); + expect(agenticListenerMock.dispatchExternal).not.toHaveBeenCalled(); + } finally { + cleanup(); + } + }); + it('replays a cursor-covered ToolEnd until the card is completed', async () => { const store = FlowChatStore.getInstance(); store.setState(prev => ({ diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.ts index 42ea6a9cbc..aec3790e41 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.ts @@ -81,8 +81,16 @@ export function isSessionProjectionAttachable( type RefreshRequester = (sessionId?: string) => void; let installedRefreshRequester: RefreshRequester | null = null; +function canReconcileSession(sessionId?: string): boolean { + return isSurfaceReconcileEnabled() + || Boolean(sessionId && isRuntimeSessionProjectionStale( + getActiveSurfaceScope().surfaceId, + sessionId, + )); +} + export function requestPeerSessionRefresh(sessionId?: string): void { - if (!isSurfaceReconcileEnabled()) { + if (!canReconcileSession(sessionId)) { return; } installedRefreshRequester?.(sessionId); @@ -452,12 +460,20 @@ export function installPeerSessionRefresh(context: FlowChatContext): () => void requestedSessionId?: string, staleOnly = false, ): Promise { - if (disposed || inFlight || !isSurfaceReconcileEnabled()) { + if (disposed || inFlight) { if (inFlight) { enqueueFollowUpRefresh(requestedSessionId); } return; } + const state = context.flowChatStore.getState(); + const sessionId = requestedSessionId || state.activeSessionId; + // A pristine local window can reload while its host keeps executing. Its + // explicitly stale projection needs the same fenced journal replay as a + // device switch, without enabling reconciliation for ordinary idle opens. + if (!canReconcileSession(sessionId ?? undefined)) { + return; + } // Peer history and live records share the durable subscription. Runtime // projection hydration remains only for the controller's local surface. if (getActiveSurfaceScope().surfaceId !== 'local') { @@ -482,8 +498,6 @@ export function installPeerSessionRefresh(context: FlowChatContext): () => void void context.ensureLiveSubscription?.(); } - const state = context.flowChatStore.getState(); - const sessionId = requestedSessionId || state.activeSessionId; // Attach is per (surface, session), not per the tab currently focused. // After a switch, every live session on this surface may have missed // DialogTurnStarted; dropped-event refresh requests name those sessions @@ -564,7 +578,7 @@ export function installPeerSessionRefresh(context: FlowChatContext): () => void // every non-active running chat after a multi-session switch. requireActiveSession: false, shouldApply: () => { - if (!isSurfaceReconcileEnabled()) { + if (!canReconcileSession(sessionId)) { return false; } const currentMachine = stateMachineManager.get(sessionId); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index ccf03b053b..634bc3ee9f 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -9787,11 +9787,19 @@ export class FlowChatStore { }); } } - if (activeTurnId && isSurfaceReconcileEnabled()) { - const { requestPeerSessionRefresh } = await import( + if (activeTurnId && (restoredRuntimeEventSnapshot || isSurfaceReconcileEnabled())) { + const { requestPeerSessionRefresh, requestRuntimeProjectionRepair } = await import( '../services/flow-chat-manager/PeerSessionRefreshModule' ); - requestPeerSessionRefresh(sessionId); + scope.assertCurrent('request restored Runtime projection replay'); + if (restoredRuntimeEventSnapshot) { + // The active Turn above is an empty journal-replay shell. A local + // reload also needs replay, even if this window never changed device. + // The stream gap survives a request made before refresh installation. + requestRuntimeProjectionRepair(sessionId); + } else { + requestPeerSessionRefresh(sessionId); + } } completeSessionMutationReconciliation(sessionId); startupTrace.markPhase('historical_session_hydrate_end', { diff --git a/src/web-ui/src/infrastructure/api/service-api/LatexAPI.ts b/src/web-ui/src/infrastructure/api/service-api/LatexAPI.ts index 1b9d283726..1620a72213 100644 --- a/src/web-ui/src/infrastructure/api/service-api/LatexAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/LatexAPI.ts @@ -12,7 +12,7 @@ export function supportsLatexPreview(surfaceId: string, capabilities?: PeerHostC export async function compileWorkspaceLatex(origin: ContentResourceScope, filePath: string, engine: LatexEngine) { const { workspaceId, surfaceId } = origin; - return invokePrepared<{ pdfBase64: string }>('compile_workspace_latex', async scope => { + return invokePrepared<{ pdfBase64: string; log?: string }>('compile_workspace_latex', async scope => { if (scope.surfaceId !== surfaceId || !workspaceId) { throw new Error('The LaTeX source workspace is unavailable on this device.'); } diff --git a/src/web-ui/src/infrastructure/file-export/savePdfFile.test.ts b/src/web-ui/src/infrastructure/file-export/savePdfFile.test.ts new file mode 100644 index 0000000000..b3b75650ca --- /dev/null +++ b/src/web-ui/src/infrastructure/file-export/savePdfFile.test.ts @@ -0,0 +1,20 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { savePdfFile } from './savePdfFile'; +const mocks = vi.hoisted(() => ({ native: false, save: vi.fn(), write: vi.fn() })); +vi.mock('@/infrastructure/runtime', () => ({ supportsNativeWindowControls: () => mocks.native })); +vi.mock('@tauri-apps/plugin-dialog', () => ({ save: mocks.save })); +vi.mock('@tauri-apps/plugin-fs', () => ({ writeFile: mocks.write })); +beforeEach(() => { vi.clearAllMocks(); }); +afterEach(() => { vi.restoreAllMocks(); }); +it('saves exact PDF bytes to the path chosen on the viewing device', async () => { + mocks.native = true; mocks.save.mockResolvedValue('/chosen/review.pdf'); + const bytes = new Uint8Array([37, 80, 68, 70]); + expect(await savePdfFile('review.pdf', bytes, 'Export')).toBe(true); + expect(mocks.write).toHaveBeenCalledWith('/chosen/review.pdf', bytes); +}); +it('treats a cancelled native picker as cancellation without writing', async () => { + mocks.native = true; mocks.save.mockResolvedValue(null); + expect(await savePdfFile('review.pdf', new Uint8Array(), 'Export')).toBe(false); + expect(mocks.write).not.toHaveBeenCalled(); +}); diff --git a/src/web-ui/src/infrastructure/file-export/savePdfFile.ts b/src/web-ui/src/infrastructure/file-export/savePdfFile.ts new file mode 100644 index 0000000000..e8206febf0 --- /dev/null +++ b/src/web-ui/src/infrastructure/file-export/savePdfFile.ts @@ -0,0 +1,21 @@ +import { supportsNativeWindowControls } from '@/infrastructure/runtime'; + +/** Explicit export belongs to the viewing device; workspace saves use the host upload port. */ +export async function savePdfFile(fileName: string, bytes: Uint8Array, title: string): Promise { + if (supportsNativeWindowControls()) { + const [{ save }, { writeFile }] = await Promise.all([ + import('@tauri-apps/plugin-dialog'), import('@tauri-apps/plugin-fs'), + ]); + const path = await save({ title, defaultPath: fileName, filters: [{ name: 'PDF', extensions: ['pdf'] }] }); + if (!path) return false; + await writeFile(path, bytes); + return true; + } + const url = URL.createObjectURL(new Blob([bytes as BlobPart], { type: 'application/pdf' })); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = fileName; + anchor.click(); + window.setTimeout(() => URL.revokeObjectURL(url), 1000); + return true; +} diff --git a/src/web-ui/src/infrastructure/files/controllerFiles.ts b/src/web-ui/src/infrastructure/files/controllerFiles.ts index aa41c20f96..739da41140 100644 --- a/src/web-ui/src/infrastructure/files/controllerFiles.ts +++ b/src/web-ui/src/infrastructure/files/controllerFiles.ts @@ -86,6 +86,8 @@ export interface UploadBytesToHostOptions { /** Throw once the target changed; checked around every host call. */ assertCurrent: () => void; onProgress?: (sentBytes: number, totalBytes: number) => void; + /** SHA-256 of the existing destination; omitted means create a new file only. */ + expectedHash?: string; } interface UploadStatus { @@ -96,10 +98,11 @@ interface UploadStatus { } /** - * Publish bytes at a new destination on the rendered execution host. + * Publish bytes on the rendered execution host. * * The host verifies the SHA-256 digest and, because the expected hash is - * empty, refuses to replace an existing file. An unknown append outcome is + * empty by default, refuses to replace an existing file. A supplied expected + * hash permits replacing only that exact destination version. An unknown append outcome is * resolved from the host cursor before any byte is resent. */ export async function uploadBytesToHost(options: UploadBytesToHostOptions): Promise { @@ -128,7 +131,7 @@ export async function uploadBytesToHost(options: UploadBytesToHostOptions): Prom action: 'begin', totalBytes: bytes.byteLength, sha256: await sha256Hex(bytes), - expectedHash: '', + expectedHash: options.expectedHash ?? '', }); try { options.onProgress?.(status.nextOffset, bytes.byteLength); diff --git a/src/web-ui/src/locales/en-US/tools.json b/src/web-ui/src/locales/en-US/tools.json index a9ad27b1cb..45f9b48cf7 100644 --- a/src/web-ui/src/locales/en-US/tools.json +++ b/src/web-ui/src/locales/en-US/tools.json @@ -131,7 +131,36 @@ "unavailable": "LaTeX compilation requires a supported OpenBitFun Desktop host and an opened workspace.", "compileFailed": "Compilation failed. View log", "stalePreview": "Compilation failed. Showing the last successful PDF", - "saveFailed": "The source could not be saved. Save your changes before compiling." + "saveFailed": "The source could not be saved. Save your changes before compiling.", + "source": "LaTeX source", + "panes": "Writing panes", + "undo": "Undo source edit", + "redo": "Redo source edit", + "insert": "Insert", + "find": "Find / replace", + "logs": "Compile logs", + "save": "Save", + "outline": "Document outline", + "outlineEmpty": "Add sections to navigate your paper.", + "mainFile": "Main TeX file", + "mainFileHint": "Compile this project entry. Relative paths resolve beside this source; % !TeX root is also supported.", + "closeSource": "Close source pane", + "closePdf": "Close PDF pane", + "closeLogs": "Close compile logs", + "compileSuccess": "Compilation finished successfully.", + "noLogs": "Compile to see diagnostics here.", + "panesClosed": "Source and PDF panes are closed. Your edits are retained.", + "restorePanes": "Open source and PDF", + "snippets": { + "section": "Section", + "equation": "Equation", + "figure": "Figure", + "table": "Table", + "cite": "Citation", + "reference": "Cross-reference", + "bibliography": "Bibliography", + "itemize": "Bullet list" + } }, "pdfViewer": { "loading": "Loading PDF...", @@ -145,7 +174,8 @@ "zoomOut": "Zoom out", "zoomLevel": "Zoom level", "zoomIn": "Zoom in", - "rotate90": "Rotate 90°" + "rotate90": "Rotate 90°", + "fitWidth": "Fit page width" }, "meditor": { "placeholder": "Enter Markdown...", @@ -232,6 +262,51 @@ "selectLanguageModeHint": "Select Language Mode (click to switch)", "indentOptionSpaces": "Spaces: {{n}}", "indentOptionTab": "Tab: {{n}}" + }, + "pdfReview": { + "tools": "PDF annotation tools", + "select": "Select text", + "highlight": "Highlight", + "note": "Note", + "ink": "Draw", + "color": "Annotation color", + "colors": { + "yellow": "Yellow", + "green": "Green", + "blue": "Blue", + "pink": "Pink" + }, + "undo": "Undo annotation", + "redo": "Redo annotation", + "comments": "Notes & comments", + "closeComments": "Close comments", + "savePdf": "Save PDF", + "export": "Export annotated PDF", + "saving": "Saving…", + "saved": "Annotations saved to workspace", + "unsaved": "Unsaved annotations", + "savedFile": "Saved: {{path}}", + "exported": "Annotated PDF exported.", + "saveFailed": "Could not save annotations. Your edits are retained.", + "empty": "Select text to highlight, click a page to leave a note, or draw on the PDF.", + "page": "Page {{page}}", + "commentPlaceholder": "Write a comment…", + "addComment": "Comment", + "resolve": "Resolve thread", + "reopen": "Reopen thread", + "remove": "Delete annotation", + "recompiled": "The PDF was recompiled. Annotations are retained by page; check their positions before saving.", + "hints": { + "highlight": "Select text in the PDF to highlight it.", + "note": "Click a position on the PDF to add a note.", + "ink": "Drag on the PDF to draw. Use Undo to remove the last stroke." + }, + "editComment": "Edit comment", + "saveComment": "Save comment", + "replaceTitle": "Replace annotated PDF?", + "replaceMessage": "The destination already exists or changed outside this editor: {{path}}. Replace this version with your current review?", + "replace": "Replace this version", + "cancel": "Cancel" } }, "terminal": { diff --git a/src/web-ui/src/locales/zh-CN/tools.json b/src/web-ui/src/locales/zh-CN/tools.json index f2b1d20e97..37034c6d27 100644 --- a/src/web-ui/src/locales/zh-CN/tools.json +++ b/src/web-ui/src/locales/zh-CN/tools.json @@ -131,7 +131,36 @@ "unavailable": "LaTeX 编译需要支持此功能的 OpenBitFun 桌面宿主,以及已打开的工作区。", "compileFailed": "编译失败,查看日志", "stalePreview": "编译失败,正在显示上次成功的 PDF", - "saveFailed": "源码保存未完成。请保存修改后再编译。" + "saveFailed": "源码保存未完成。请保存修改后再编译。", + "source": "LaTeX 源码", + "panes": "写作面板", + "undo": "撤销源码修改", + "redo": "重做源码修改", + "insert": "插入", + "find": "查找 / 替换", + "logs": "编译日志", + "save": "保存", + "outline": "论文大纲", + "outlineEmpty": "添加章节后可在这里跳转。", + "mainFile": "主 TeX 文件", + "mainFileHint": "编译这个项目入口。相对路径以当前源码所在目录为准,也支持 % !TeX root。", + "closeSource": "关闭源码栏", + "closePdf": "关闭 PDF 栏", + "closeLogs": "关闭编译日志", + "compileSuccess": "编译成功。", + "noLogs": "编译后在这里查看诊断信息。", + "panesClosed": "源码与 PDF 栏已关闭,编辑内容仍保留。", + "restorePanes": "打开源码与 PDF", + "snippets": { + "section": "章节", + "equation": "公式", + "figure": "图片", + "table": "表格", + "cite": "文献引用", + "reference": "交叉引用", + "bibliography": "参考文献", + "itemize": "项目列表" + } }, "pdfViewer": { "loading": "正在加载 PDF...", @@ -145,7 +174,8 @@ "zoomOut": "缩小", "zoomLevel": "缩放比例", "zoomIn": "放大", - "rotate90": "旋转 90°" + "rotate90": "旋转 90°", + "fitWidth": "适合页面宽度" }, "meditor": { "placeholder": "请输入 Markdown 内容...", @@ -232,6 +262,51 @@ "selectLanguageModeHint": "选择语言模式(点击即切换)", "indentOptionSpaces": "空格: {{n}}", "indentOptionTab": "Tab: {{n}}" + }, + "pdfReview": { + "tools": "PDF 批注工具", + "select": "选择文字", + "highlight": "高亮", + "note": "笔记", + "ink": "涂写", + "color": "批注颜色", + "colors": { + "yellow": "黄色", + "green": "绿色", + "blue": "蓝色", + "pink": "粉色" + }, + "undo": "撤销批注", + "redo": "重做批注", + "comments": "笔记与评论", + "closeComments": "关闭评论栏", + "savePdf": "保存 PDF", + "export": "导出带批注的 PDF", + "saving": "正在保存…", + "saved": "批注已保存到工作区", + "unsaved": "批注尚未保存", + "savedFile": "已保存:{{path}}", + "exported": "已导出带批注的 PDF。", + "saveFailed": "批注保存失败,编辑内容仍保留。", + "empty": "选中文字添加高亮,点击页面留下笔记,或在 PDF 上涂写。", + "page": "第 {{page}} 页", + "commentPlaceholder": "写下评论…", + "addComment": "评论", + "resolve": "解决此评论", + "reopen": "重新打开评论", + "remove": "删除批注", + "recompiled": "PDF 已重新编译,批注按页保留;保存前请核对位置。", + "hints": { + "highlight": "在 PDF 中选中文字即可添加高亮。", + "note": "点击 PDF 中的位置即可添加笔记。", + "ink": "在 PDF 上拖动即可涂写,可撤销最后一笔。" + }, + "editComment": "编辑评论", + "saveComment": "保存评论", + "replaceTitle": "替换已有的批注 PDF?", + "replaceMessage": "目标文件已存在,或已被其他程序修改:{{path}}。是否用当前批注替换这个版本?", + "replace": "替换此版本", + "cancel": "取消" } }, "terminal": { diff --git a/src/web-ui/src/locales/zh-TW/tools.json b/src/web-ui/src/locales/zh-TW/tools.json index 5bb31f315d..5045f0be63 100644 --- a/src/web-ui/src/locales/zh-TW/tools.json +++ b/src/web-ui/src/locales/zh-TW/tools.json @@ -131,7 +131,36 @@ "unavailable": "LaTeX 編譯需要支援此功能的 OpenBitFun 桌面主機,以及已開啟的工作區。", "compileFailed": "編譯失敗,查看記錄", "stalePreview": "編譯失敗,正在顯示上次成功的 PDF", - "saveFailed": "原始碼尚未儲存。請儲存變更後再編譯。" + "saveFailed": "原始碼尚未儲存。請儲存變更後再編譯。", + "source": "LaTeX 原始碼", + "panes": "寫作面板", + "undo": "復原原始碼修改", + "redo": "重做原始碼修改", + "insert": "插入", + "find": "尋找 / 取代", + "logs": "編譯日誌", + "save": "儲存", + "outline": "論文大綱", + "outlineEmpty": "新增章節後可在這裡跳轉。", + "mainFile": "主 TeX 檔案", + "mainFileHint": "編譯這個專案入口。相對路徑以目前原始碼所在目錄為準,也支援 % !TeX root。", + "closeSource": "關閉原始碼欄", + "closePdf": "關閉 PDF 欄", + "closeLogs": "關閉編譯日誌", + "compileSuccess": "編譯成功。", + "noLogs": "編譯後在這裡查看診斷資訊。", + "panesClosed": "原始碼與 PDF 欄已關閉,編輯內容仍保留。", + "restorePanes": "開啟原始碼與 PDF", + "snippets": { + "section": "章節", + "equation": "公式", + "figure": "圖片", + "table": "表格", + "cite": "文獻引用", + "reference": "交叉引用", + "bibliography": "參考文獻", + "itemize": "項目清單" + } }, "pdfViewer": { "loading": "正在載入 PDF...", @@ -145,7 +174,8 @@ "zoomOut": "縮小", "zoomLevel": "縮放比例", "zoomIn": "放大", - "rotate90": "旋轉 90°" + "rotate90": "旋轉 90°", + "fitWidth": "符合頁面寬度" }, "meditor": { "placeholder": "請輸入 Markdown 內容...", @@ -232,6 +262,51 @@ "selectLanguageModeHint": "選擇語言模式(點擊即切換)", "indentOptionSpaces": "空格: {{n}}", "indentOptionTab": "Tab: {{n}}" + }, + "pdfReview": { + "tools": "PDF 註解工具", + "select": "選取文字", + "highlight": "醒目提示", + "note": "筆記", + "ink": "塗寫", + "color": "註解顏色", + "colors": { + "yellow": "黃色", + "green": "綠色", + "blue": "藍色", + "pink": "粉紅色" + }, + "undo": "復原註解", + "redo": "重做註解", + "comments": "筆記與評論", + "closeComments": "關閉評論欄", + "savePdf": "儲存 PDF", + "export": "匯出含註解的 PDF", + "saving": "正在儲存…", + "saved": "註解已儲存至工作區", + "unsaved": "註解尚未儲存", + "savedFile": "已儲存:{{path}}", + "exported": "已匯出含註解的 PDF。", + "saveFailed": "註解儲存失敗,編輯內容仍保留。", + "empty": "選取文字加入醒目提示,點擊頁面留下筆記,或在 PDF 上塗寫。", + "page": "第 {{page}} 頁", + "commentPlaceholder": "寫下評論…", + "addComment": "評論", + "resolve": "解決此評論", + "reopen": "重新開啟評論", + "remove": "刪除註解", + "recompiled": "PDF 已重新編譯,註解按頁保留;儲存前請核對位置。", + "hints": { + "highlight": "在 PDF 中選取文字即可加入醒目提示。", + "note": "點擊 PDF 中的位置即可新增筆記。", + "ink": "在 PDF 上拖曳即可塗寫,可復原最後一筆。" + }, + "editComment": "編輯評論", + "saveComment": "儲存評論", + "replaceTitle": "取代既有的註解 PDF?", + "replaceMessage": "目標檔案已存在,或已被其他程式修改:{{path}}。是否用目前註解取代這個版本?", + "replace": "取代此版本", + "cancel": "取消" } }, "terminal": { diff --git a/src/web-ui/src/tools/editor/components/CodeEditor.test.tsx b/src/web-ui/src/tools/editor/components/CodeEditor.test.tsx index ea66222145..2b0d219b7d 100644 --- a/src/web-ui/src/tools/editor/components/CodeEditor.test.tsx +++ b/src/web-ui/src/tools/editor/components/CodeEditor.test.tsx @@ -209,6 +209,49 @@ afterEach(async () => { vi.useRealTimers(); }); +describe('CodeEditor initialization lifecycle', () => { + it('closes safely before the first Monaco initialization completes', async () => { + const runtime = createRuntime(); + const pending = deferred(); + const createEditor = vi.spyOn(runtime.editor, 'create'); + const createModel = vi.spyOn(runtime.editor, 'createModel'); + setMonacoRuntime(null); + mocks.initialize.mockReturnValueOnce(pending.promise); + + await act(async () => root.render()); + expect(mocks.initialize).toHaveBeenCalledTimes(1); + await act(async () => root.render(null)); + await act(async () => { + setMonacoRuntime(runtime); + pending.resolve(runtime); + }); + + expect(createEditor).not.toHaveBeenCalled(); + expect(createModel).not.toHaveBeenCalled(); + expect(mocks.logError).not.toHaveBeenCalled(); + }); + + it('does not release another view model when closed before acquiring it', async () => { + const runtime = createRuntime(); + const pending = deferred(); + setMonacoRuntime(runtime); + const retainedModel = monacoModelManager.getOrCreateModel(path, 'plaintext', 'disk', undefined, session.modelKey); + mocks.initialize.mockReturnValueOnce(pending.promise); + + try { + await act(async () => root.render()); + expect(mocks.initialize).toHaveBeenCalledTimes(1); + await act(async () => root.render(null)); + await act(async () => pending.resolve(runtime)); + + expect(model()).toBe(retainedModel); + expect(metadata().referenceCount).toBe(1); + } finally { + monacoModelManager.releaseModel(session.modelKey); + } + }); +}); + describe('CodeEditor disk synchronization', () => { it('keeps remote external edits responsive and immediately checks again on window focus', async () => { session.scope.remoteConnectionId = 'ssh-a'; diff --git a/src/web-ui/src/tools/editor/components/CodeEditor.tsx b/src/web-ui/src/tools/editor/components/CodeEditor.tsx index 5cecaab4c4..c16507a208 100644 --- a/src/web-ui/src/tools/editor/components/CodeEditor.tsx +++ b/src/web-ui/src/tools/editor/components/CodeEditor.tsx @@ -92,6 +92,8 @@ export interface CodeEditorProps { className?: string; /** Content change callback */ onContentChange?: (content: string, hasChanges: boolean) => void; + /** Host actions operate on the retained editor instead of global focus. */ + onEditorReady?: (editor: monaco.editor.IStandaloneCodeEditor | null) => void; /** Save callback */ onSave?: (content: string) => void; /** Jump to line number (deprecated, use jumpToRange) */ @@ -178,6 +180,7 @@ const CodeEditor: React.FC = ({ className = '', onContentChange, onSave, + onEditorReady, jumpToLine, jumpToColumn, jumpToRange, @@ -330,6 +333,8 @@ const CodeEditor: React.FC = ({ const showLineNumbersRuntimeRef = useRef(showLineNumbers); const showMinimapRuntimeRef = useRef(showMinimap); const onContentChangeRef = useRef(onContentChange); + const onEditorReadyRef = useRef(onEditorReady); + onEditorReadyRef.current = onEditorReady; const tRef = useRef(t); const contentRef = useRef(content); const loadingRef = useRef(loading); @@ -844,6 +849,7 @@ const CodeEditor: React.FC = ({ editor = monacoApi.editor.create(container, editorOptions); editorRef.current = editor; + onEditorReadyRef.current?.(editor); if (documentSession?.viewState) editor.restoreViewState(documentSession.viewState as monaco.editor.ICodeEditorViewState); // Monaco's viewState does not serialize find/replace state. Keep the // view while it owns a query, including a closed widget used by F3. @@ -1096,6 +1102,7 @@ const CodeEditor: React.FC = ({ } if (editorRef.current) { + onEditorReadyRef.current?.(null); if (documentSession) documentSession.viewState = editorRef.current.saveViewState(); editorRef.current.dispose(); editorRef.current = null; @@ -1105,7 +1112,9 @@ const CodeEditor: React.FC = ({ delete (container as any).__monacoEditor; } - monacoModelManager.releaseModel(modelKey); + // Cleanup can run before asynchronous Monaco initialization acquires a + // model. Release only the reference owned by this initialization. + if (model) monacoModelManager.releaseModel(modelKey); }; }, [clearScheduledNavigationSettlement, detectedLanguage, detectLargeFileMode, documentSession, filePath, modelKey, viewResident]); diff --git a/src/web-ui/src/tools/editor/components/LatexEditor.appearance.ts b/src/web-ui/src/tools/editor/components/LatexEditor.appearance.ts index f866b48a99..5482eab843 100644 --- a/src/web-ui/src/tools/editor/components/LatexEditor.appearance.ts +++ b/src/web-ui/src/tools/editor/components/LatexEditor.appearance.ts @@ -3,6 +3,7 @@ import type { AppearanceSurfaceDescriptor } from '@/infrastructure/appearance'; export const latexEditorAppearanceDescriptor: AppearanceSurfaceDescriptor = { id: 'latex-editor', parts: [ + { id: 'root' }, { id: 'header' }, { id: 'source' }, { id: 'outline' }, { id: 'preview' }, { id: 'toolbar' }, { id: 'diagnostics' }, diff --git a/src/web-ui/src/tools/editor/components/LatexEditor.scss b/src/web-ui/src/tools/editor/components/LatexEditor.scss index 4d5db83b2f..8d21ed66dc 100644 --- a/src/web-ui/src/tools/editor/components/LatexEditor.scss +++ b/src/web-ui/src/tools/editor/components/LatexEditor.scss @@ -1,63 +1,40 @@ .latex-editor { - width: 100%; - height: 100%; - min-width: 0; - min-height: 0; - - &__preview { - display: flex; - flex-direction: column; - height: 100%; - min-width: 0; - min-height: 0; - background: var(--openbitfun-color-surface-canvas); - color: var(--openbitfun-color-content-primary); - font-size: var(--openbitfun-type-body-sm-font-size); - } - - &__toolbar { - display: flex; - flex-wrap: wrap; - flex-shrink: 0; - align-items: center; - gap: var(--openbitfun-space-2); - padding: var(--openbitfun-space-2) var(--openbitfun-space-3); - border-bottom: 1px solid var(--openbitfun-color-border-subtle); - } - - &__auto { - display: inline-flex; - align-items: center; - gap: var(--openbitfun-space-2); - } - - &__engine { - width: 110px; - } - - &__empty { - display: grid; - flex: 1; - place-content: center; - padding: var(--openbitfun-space-5); - color: var(--openbitfun-color-content-secondary); - text-align: center; - } - - &__diagnostics { - max-height: 45%; - padding: var(--openbitfun-space-2) var(--openbitfun-space-3); - overflow: auto; - border-bottom: 1px solid var(--openbitfun-color-border-subtle); - } - - &__log { - white-space: pre-wrap; - overflow-wrap: anywhere; - } - - &__pdf { - flex: 1; - min-height: 0; - } + display: flex; + flex-direction: column; + width: 100%; height: 100%; min-width: 0; min-height: 0; + overflow: hidden; + background: var(--openbitfun-color-surface-canvas); + color: var(--openbitfun-color-content-primary); + font-family: var(--openbitfun-type-body-sm-font-family); + font-size: var(--openbitfun-type-body-sm-font-size); + line-height: var(--openbitfun-type-body-sm-line-height); + + &__header, &__toolbar, &__source-bar, &__preview-bar { display: flex; align-items: center; gap: var(--openbitfun-space-2); flex-shrink: 0; border-bottom: 1px solid var(--openbitfun-color-border-subtle); padding: var(--openbitfun-space-2) var(--openbitfun-space-3); } + &__header { justify-content: space-between; } + &__file, &__preview-bar > span { display: flex; align-items: center; gap: var(--openbitfun-space-2); } + &__view-controls { display: flex; gap: var(--openbitfun-space-1); } + &__toolbar { flex-wrap: wrap; } + &__engine { width: 118px; } + &__insert { width: 115px; } + &__auto { display: inline-flex; align-items: center; gap: var(--openbitfun-space-2); white-space: nowrap; } + &__separator { height: 18px; border-inline-start: 1px solid var(--openbitfun-color-border-subtle); margin-inline: var(--openbitfun-space-1); } + &__body, &__split { flex: 1; min-height: 0; min-width: 0; } + &__body[hidden] { display: none; } + &__split { height: 100%; } + &__source, &__preview { display: flex; flex-direction: column; height: 100%; min-height: 0; min-width: 0; } + &__preview-bar { justify-content: space-between; } + &__source-bar > [data-openbitfun-component='input'] { flex: 1; min-width: 0; } + &__source-body { display: flex; flex: 1; min-height: 0; min-width: 0; } + &__code, &__pdf { flex: 1; min-height: 0; min-width: 0; } + &__outline { flex: 0 0 170px; overflow: auto; min-width: 0; padding: var(--openbitfun-space-2) 0; border-inline-end: 1px solid var(--openbitfun-color-border-subtle); } + &__outline button { display: block; width: 100%; padding: var(--openbitfun-space-2); border: 0; text-align: start; color: var(--openbitfun-color-content-secondary); background: none; cursor: pointer; font: inherit; overflow-wrap: anywhere; } + &__outline button:hover { background: var(--openbitfun-color-surface-subtle); color: var(--openbitfun-color-content-primary); } + &__outline p { padding: var(--openbitfun-space-2); color: var(--openbitfun-color-content-muted); } + &__empty { display: flex; flex: 1; flex-direction: column; align-items: center; justify-content: center; gap: var(--openbitfun-space-3); padding: var(--openbitfun-space-6); color: var(--openbitfun-color-content-secondary); text-align: center; } + &__empty p { max-width: 420px; } + &__stale { padding: var(--openbitfun-space-2) var(--openbitfun-space-3); color: var(--openbitfun-color-content-secondary); background: var(--openbitfun-color-surface-subtle); } + &__diagnostics { flex: 0 1 200px; min-height: 80px; overflow: auto; border-top: 1px solid var(--openbitfun-color-border-subtle); padding: var(--openbitfun-space-2) var(--openbitfun-space-3); background: var(--openbitfun-color-surface-subtle); } + &__diagnostics header { display: flex; align-items: center; justify-content: space-between; margin-bottom: var(--openbitfun-space-2); } + &__log-line { display: block; border: 0; padding: 0; white-space: pre-wrap; overflow-wrap: anywhere; text-align: start; color: var(--openbitfun-color-content-secondary); background: none; font-family: var(--openbitfun-type-code-sm-font-family); font-size: var(--openbitfun-type-code-sm-font-size); line-height: var(--openbitfun-type-code-sm-line-height); } + button.latex-editor__log-line { color: var(--openbitfun-color-accent-default); cursor: pointer; } } diff --git a/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx b/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx index a73e09da01..5ef3cda554 100644 --- a/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx +++ b/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx @@ -1,6 +1,7 @@ // @vitest-environment jsdom -import { act } from 'react'; +import { act, type ComponentProps } from 'react'; +import type * as Monaco from 'monaco-editor'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import LatexEditor from './LatexEditor'; @@ -11,8 +12,17 @@ const mocks = vi.hoisted(() => ({ invoke: vi.fn(), supported: true, sourceProps: undefined as import('./CodeEditor').CodeEditorProps | undefined, + insertSnippet: undefined as ((value: string) => void) | undefined, })); +vi.mock('@openbitfun/ui', async importOriginal => { + const actual = await importOriginal(); + return { ...actual, Select: (props: ComponentProps) => { + if (props['aria-label'] === 'editor.latexEditor.insert') mocks.insertSnippet = props.onValueChange; + return ; + } }; +}); + vi.mock('@/infrastructure/api/service-api/LatexAPI', () => ({ compileWorkspaceLatex: mocks.invoke, supportsLatexPreview: () => mocks.supported, @@ -27,7 +37,7 @@ vi.mock('./CodeEditor', () => ({ return