Skip to content

Commit 0c474e3

Browse files
authored
Merge pull request #3870 from nonoqing/codex/paper-writing-review
feat(paper-writing): add a resizable LaTeX workbench with PDF annotations
2 parents 57afe3d + b1025b7 commit 0c474e3

40 files changed

Lines changed: 2293 additions & 221 deletions
411 KB
Loading

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/apps/desktop/README.md‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,33 @@ agent to draft or revise files in your workspace. Open the main `.tex` file
137137
from the file tree or its chat link. The editor shows source on the left and the
138138
typeset PDF on the right. Use **Save & compile** or turn on **Auto compile**
139139
to save and recompile the main source after you pause. A failed build keeps the
140-
last successful preview and shows the compiler log.
140+
last successful preview and shows the compiler log. The source and PDF panes can
141+
be closed independently, restored from the header, and resized by dragging their
142+
divider. Hidden source views retain the document and its undo history.
143+
144+
The source toolbar includes undo/redo, find/replace, a section outline, and
145+
snippets for equations, figures, tables, and references. Command, environment,
146+
and in-document label completions are available in Monaco. Select the main TeX
147+
entry when editing an included chapter, or add a `% !TeX root = ../main.tex`
148+
comment. Compiler diagnostics for the current file link back to their source line.
149+
150+
PDF review supports text highlights, sticky notes, comment threads, freehand ink,
151+
annotation colors, resolution, deletion, and undo/redo. Reviews are automatically
152+
saved beside the source as `<source>.openbitfun-review.json`; include that file
153+
when moving or sharing the project. **Save PDF** writes an editable
154+
`<paper>.annotated.pdf` to the workspace. **Export annotated PDF** saves a copy
155+
on the viewing device. Saved PDFs embed their review state so notes and threads
156+
can be edited again when reopened in OpenBitFun; other PDF applications see
157+
standard PDF annotations. Replacing an existing output checks its current
158+
version and asks before overwriting an externally changed file.
159+
160+
Annotations retain PDF page coordinates across compilation. Check their positions
161+
when a revision changes the layout; the preview shows a reminder after recompiling.
162+
LaTeX source remains the place to change manuscript text and figures.
163+
164+
![LaTeX source, PDF preview, and review notes in a sample writing workspace](../../../docs/images/paper-writing-workbench.png)
165+
166+
The image uses a sample paper in an isolated UI fixture.
141167

142168
Install `latexmk` and the selected pdfLaTeX or XeLaTeX engine on the machine that
143169
owns the workspace. For SSH, Docker, and WSL workspaces, compile in that

‎src/apps/desktop/src/api/latex_api.rs‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ pub struct CompileWorkspaceLatexRequest {
5454
#[serde(rename_all = "camelCase")]
5555
pub struct CompileWorkspaceLatexResponse {
5656
pdf_base64: String,
57+
log: String,
58+
}
59+
60+
#[derive(Debug)]
61+
struct CompiledLatex {
62+
pdf: Vec<u8>,
63+
log: String,
5764
}
5865

5966
#[tauri::command]
@@ -63,15 +70,16 @@ pub async fn compile_workspace_latex(
6370
let workspace = WorkspaceBinding::resolve(&request.workspace_id)
6471
.await
6572
.map_err(|error| error.to_string())?;
66-
let pdf_base64 = if workspace.is_remote() {
73+
let (pdf_base64, log) = if workspace.is_remote() {
6774
let connection_id = workspace
6875
.connection_id()
6976
.ok_or("Remote workspace is disconnected.")?;
7077
compile_remote(connection_id, &workspace.root_path_string(), &request).await?
7178
} else {
72-
BASE64.encode(compile_local(workspace.root_path(), &request).await?)
79+
let output = compile_local(workspace.root_path(), &request).await?;
80+
(BASE64.encode(output.pdf), output.log)
7381
};
74-
Ok(CompileWorkspaceLatexResponse { pdf_base64 })
82+
Ok(CompileWorkspaceLatexResponse { pdf_base64, log })
7583
}
7684

7785
// latexmk invokes TeX and bibliography programs via their command templates.
@@ -93,7 +101,7 @@ fn source_stem(file_name: &str) -> Result<&str, String> {
93101
async fn compile_local(
94102
root: &Path,
95103
request: &CompileWorkspaceLatexRequest,
96-
) -> Result<Vec<u8>, String> {
104+
) -> Result<CompiledLatex, String> {
97105
let source = root.join(&request.file_path);
98106
let root = tokio::fs::canonicalize(root)
99107
.await
@@ -156,14 +164,14 @@ async fn compile_local(
156164
.await
157165
.map_err(|_| "LaTeX compilation timed out.")?
158166
.map_err(|error| error.to_string())?;
167+
let log = format!("{stdout}\n{stderr}");
159168
if !status.success() {
160-
let log = format!("{stdout}\n{stderr}");
161169
return Err(format!("latexmk exited with {status}.\n{}", log.trim()));
162170
}
163171
drop(child);
164172

165173
let pdf = build.path().join(format!("{stem}.pdf"));
166-
tokio::task::spawn_blocking(move || {
174+
let pdf = tokio::task::spawn_blocking(move || -> Result<Vec<u8>, String> {
167175
let _build = build;
168176
let metadata = std::fs::symlink_metadata(&pdf).map_err(|_| MISSING_PDF)?;
169177
if !metadata.is_file() || is_symlink_or_reparse(&metadata) {
@@ -176,7 +184,8 @@ async fn compile_local(
176184
}
177185
})
178186
.await
179-
.map_err(|error| error.to_string())?
187+
.map_err(|error| error.to_string())??;
188+
Ok(CompiledLatex { pdf, log })
180189
}
181190

182191
async fn read_log_tail(mut reader: impl AsyncRead + Unpin) -> std::io::Result<String> {
@@ -229,6 +238,7 @@ if latexmk {arguments} "-outdir=$build" "$source" </dev/null >"$build/compile.lo
229238
pdf="$build/"{pdf}
230239
[ -f "$pdf" ] && [ ! -L "$pdf" ] || {{ echo "{MISSING_PDF}" >&2; exit 1; }}
231240
[ "$(wc -c < "$pdf")" -le {MAX_PDF_BYTES} ] || {{ echo "The PDF exceeds the 8 MiB preview limit." >&2; exit 1; }}
241+
tail -c {MAX_LOG_BYTES} "$build/compile.log" >&2
232242
base64 < "$pdf"
233243
else
234244
tail -c {MAX_LOG_BYTES} "$build/compile.log" >&2
@@ -247,7 +257,7 @@ async fn compile_remote(
247257
connection_id: &str,
248258
root: &str,
249259
request: &CompileWorkspaceLatexRequest,
250-
) -> Result<String, String> {
260+
) -> Result<(String, String), String> {
251261
let command = remote_build_command(root, &request.file_path, request.engine)?;
252262
let manager = get_remote_workspace_manager().ok_or("Remote workspace is unavailable.")?;
253263
let ssh = manager
@@ -288,7 +298,7 @@ async fn compile_remote(
288298
if pdf.len() > MAX_PDF_BYTES || !pdf.starts_with(b"%PDF-") {
289299
return Err(MISSING_PDF.into());
290300
}
291-
Ok(encoded)
301+
Ok((encoded, result.stderr))
292302
}
293303

294304
#[cfg(test)]
@@ -353,7 +363,8 @@ mod tests {
353363
engine: LatexEngine::PdfLatex,
354364
};
355365
let pdf = compile_local(root.path(), &request).await.unwrap();
356-
assert!(pdf.starts_with(b"%PDF-"));
366+
assert!(pdf.pdf.starts_with(b"%PDF-"));
367+
assert!(pdf.log.contains("Latexmk"));
357368
assert!(!root.path().join("main draft.aux").exists());
358369
assert_eq!(
359370
std::fs::read_to_string(previous_pdf).unwrap(),

‎src/web-ui/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979
"parse-entities": "^4.0.2",
8080
"partial-json": "^0.1.7",
8181
"path-browserify": "^1.0.1",
82+
"pdf-lib": "1.17.1",
8283
"pdfjs-dist": "5.4.624",
8384
"prismjs": "^1.30.0",
8485
"qrcode.react": "^4.2.0",

‎src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ const ImageViewer = lazyWithRecovery(() =>
4141
);
4242

4343
const PdfViewer = lazyWithRecovery(() =>
44-
import('@/tools/editor/components/PdfViewer').then(module => ({
44+
import('@/tools/editor/pdf-review/PdfReviewEditor').then(module => ({
4545
default: module.default,
4646
}))
4747
);
@@ -417,6 +417,7 @@ const FlexiblePanel: React.FC<ExtendedFlexiblePanelProps> = memo(({
417417
isActiveTab={isActive}
418418
filePath={pdfViewerData.filePath || ''}
419419
fileName={content.title}
420+
onDirtyStateChange={onDirtyStateChange}
420421
className="openbitfun-flexible-panel__pdf-viewer"
421422
/>
422423
)}

‎src/web-ui/src/app/workbench/ContentResourceView.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ export default function ContentResourceView({ resourceId, isActive }: { resource
3939
cancelText: t('workbench.cancel'), type: 'warning' });
4040
if (choice === 'cancel') return false;
4141
if (choice === 'secondary') return true;
42-
if (!document?.save || latest.scope.surfaceId !== getActiveSurfaceId()) return false;
43-
await document.save();
42+
if (!document || latest.scope.surfaceId !== getActiveSurfaceId()) return false;
43+
await document.saveAll();
4444
return !useContentResourceStore.getState().resources[resourceId]?.isDirty;
4545
}), [document, resourceId, t]);
4646
useTabCloseShortcut('workbench-content',

‎src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts‎

Lines changed: 162 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
22

33
const peerModeMock = vi.hoisted(() => ({ active: true }));
44
const stateMachineMock = vi.hoisted(() => ({
5+
getOrCreate: vi.fn(),
56
get: vi.fn(() => ({
67
getCurrentState: () => 'idle',
78
getContext: () => ({ lastUpdateTime: 0 }),
@@ -20,9 +21,11 @@ vi.mock('@/infrastructure/peer-device/peerModeFlag', () => ({
2021

2122
vi.mock('../../state-machine', () => ({
2223
stateMachineManager: stateMachineMock,
24+
SessionExecutionEvent: { START: 'start' },
2325
}));
2426

25-
vi.mock('../liveSessionInteractionStore', () => ({
27+
vi.mock('../liveSessionInteractionStore', async importOriginal => ({
28+
...await importOriginal<typeof import('../liveSessionInteractionStore')>(),
2629
installLiveSessionInteractionMailbox: vi.fn(),
2730
}));
2831

@@ -42,9 +45,15 @@ import {
4245
runtimeProjectionCaughtUp,
4346
} from './PeerSessionRefreshModule';
4447
import { processToolEvent } from './ToolEventModule';
48+
import { processNormalTextChunkInternal } from './TextChunkModule';
49+
import { convertDialogTurnToBackendFormat } from './PersistenceModule';
50+
import { resetDeviceSurfaceSwitchedForTest } from '@/infrastructure/peer-device/deviceSurfaceReconcile';
4551
import {
52+
isRuntimeSessionProjectionStale,
4653
markRuntimeSessionProjectionStale,
54+
readRuntimeSessionProgress,
4755
resetRuntimeSessionEventGateForTest,
56+
routeRuntimeSessionEvent,
4857
} from '@/infrastructure/peer-device/runtimeSessionEventGate';
4958

5059
describe('PeerSessionRefreshModule', () => {
@@ -1067,6 +1076,8 @@ describe('PeerSessionRefreshModule journal apply', () => {
10671076
vi.useFakeTimers();
10681077
peerModeMock.active = true;
10691078
resetRuntimeSessionEventGateForTest();
1079+
resetDeviceSurfaceSwitchedForTest();
1080+
activateSurface(LOCAL_SURFACE_ID);
10701081
stateMachineMock.get.mockReturnValue({
10711082
getCurrentState: () => 'processing',
10721083
getContext: () => ({ lastUpdateTime: Date.now(), version: 0 }),
@@ -1094,10 +1105,160 @@ describe('PeerSessionRefreshModule journal apply', () => {
10941105
activeSessionId: null,
10951106
}));
10961107
vi.clearAllMocks();
1108+
vi.restoreAllMocks();
10971109
vi.unstubAllGlobals();
10981110
vi.useRealTimers();
10991111
});
11001112

1113+
it.each([true, false])('replays a pristine local active restore when refresh is installed before hydrate: %s', async installBeforeHydrate => {
1114+
peerModeMock.active = false;
1115+
const store = FlowChatStore.getInstance();
1116+
const sessionId = 'local-reload';
1117+
const turnId = 'turn-live';
1118+
const roundId = 'round-live';
1119+
store.setState(prev => ({
1120+
...prev,
1121+
activeSessionId: sessionId,
1122+
sessions: new Map([[sessionId, {
1123+
sessionId,
1124+
title: 'Local reload',
1125+
workspaceId: 'workspace-1',
1126+
workspacePath: '/repo/OpenBitFun',
1127+
historyState: 'metadata-only',
1128+
isHistorical: true,
1129+
isTransient: false,
1130+
dialogTurns: [],
1131+
config: { agentType: 'PaperWriting' },
1132+
createdAt: 1,
1133+
lastActiveAt: 1,
1134+
todos: [],
1135+
} as any]]),
1136+
}));
1137+
const context = {
1138+
flowChatStore: store,
1139+
eventBatcher: { flushNow: vi.fn(), clear: vi.fn(), getBufferSize: () => 0 },
1140+
contentBuffers: new Map(),
1141+
activeTextItems: new Map(),
1142+
runtimeStatusTimers: new Map(),
1143+
saveDebouncers: new Map(),
1144+
lastSaveTimestamps: new Map(),
1145+
lastSaveHashes: new Map(),
1146+
turnSaveInFlight: new Map(),
1147+
turnSavePending: new Set(),
1148+
} as any;
1149+
const apply = (eventName: string, payload: any): boolean => {
1150+
if (eventName === 'agentic://model-round-started') {
1151+
store.addModelRound(sessionId, turnId, {
1152+
id: roundId, index: 0, items: [], status: 'streaming',
1153+
isStreaming: true, isComplete: false, startTime: 1,
1154+
});
1155+
} else if (eventName === 'agentic://text-chunk') {
1156+
processNormalTextChunkInternal(context, sessionId, turnId, roundId, payload.text);
1157+
} else if (eventName === 'agentic://tool-event') {
1158+
processToolEvent(context, sessionId, turnId, roundId, payload.toolEvent);
1159+
}
1160+
return true;
1161+
};
1162+
agenticListenerMock.dispatchExternal.mockImplementation(apply);
1163+
const events = [
1164+
{ eventName: 'agentic://dialog-turn-started', payload: { sessionId, turnId } },
1165+
{ eventName: 'agentic://model-round-started', payload: { sessionId, turnId, roundId } },
1166+
{ eventName: 'agentic://text-chunk', payload: { sessionId, turnId, roundId, text: 'Hello' } },
1167+
{ eventName: 'agentic://tool-event', payload: { sessionId, turnId, roundId, toolEvent: {
1168+
event_type: 'Started', tool_id: 'read-1', tool_name: 'Read', params: { file_path: 'main.tex' },
1169+
} } },
1170+
{ eventName: 'agentic://tool-event', payload: { sessionId, turnId, roundId, toolEvent: {
1171+
event_type: 'Completed', tool_id: 'read-1', tool_name: 'Read', result: 'source',
1172+
} } },
1173+
];
1174+
const view = {
1175+
session: { sessionId, agentType: 'PaperWriting', state: 'Processing', createdAt: 1, turnCount: 7 },
1176+
turns: [{
1177+
turnId, turnIndex: 6, sessionId, timestamp: 1,
1178+
userMessage: { id: 'user-live', content: 'Open LaTeX', timestamp: 1 },
1179+
modelRounds: [], startTime: 1, status: 'inprogress',
1180+
}],
1181+
contextRestoreState: 'pending', isPartial: true, loadedTurnCount: 1, totalTurnCount: 7,
1182+
turnCatalog: { schemaVersion: 1, sessionId, revision: 'catalog-1', complete: true,
1183+
totalTurnCount: 7, entries: [] },
1184+
runtimeEventSnapshot: { sessionId, streamId: 'runtime-local', cursor: 5, activeTurnId: turnId, events },
1185+
} as any;
1186+
let resolveRefresh!: (value: any) => void;
1187+
const restore = vi.spyOn(agentAPI, 'restoreSessionView')
1188+
.mockResolvedValueOnce(view)
1189+
.mockImplementationOnce(() => new Promise(resolve => { resolveRefresh = resolve; }));
1190+
let cleanup: (() => void) | undefined;
1191+
try {
1192+
if (installBeforeHydrate) cleanup = installPeerSessionRefresh(context);
1193+
await store.loadSessionHistory(sessionId);
1194+
expect(store.getState().sessions.get(sessionId)?.dialogTurns[0].modelRounds).toEqual([]);
1195+
expect(isRuntimeSessionProjectionStale(LOCAL_SURFACE_ID, sessionId)).toBe(true);
1196+
if (!installBeforeHydrate) cleanup = installPeerSessionRefresh(context);
1197+
await vi.advanceTimersByTimeAsync(1);
1198+
expect(restore).toHaveBeenCalledTimes(2);
1199+
1200+
// Live delivery races the host read: the covered prefix must not repeat,
1201+
// and the suffix must wait for the journal's model round to exist.
1202+
const deliver = (cursor: number, text: string) => routeRuntimeSessionEvent(
1203+
LOCAL_SURFACE_ID, 'agentic://text-chunk', {
1204+
sessionId, turnId, roundId, text,
1205+
__openbitfunRuntimeStreamId: 'runtime-local', __openbitfunRuntimeEventCursor: cursor,
1206+
}, payload => { apply('agentic://text-chunk', payload); },
1207+
);
1208+
deliver(3, 'Hello');
1209+
deliver(6, ' world');
1210+
expect(agenticListenerMock.dispatchExternal).not.toHaveBeenCalled();
1211+
resolveRefresh(view);
1212+
await vi.advanceTimersByTimeAsync(1);
1213+
1214+
const turn = store.getState().sessions.get(sessionId)!.dialogTurns[0];
1215+
expect(turn.modelRounds).toHaveLength(1);
1216+
expect(turn.modelRounds[0].items.find(item => item.type === 'text')).toMatchObject({ content: 'Hello world' });
1217+
expect(store.findToolItem(sessionId, turnId, 'read-1')?.status).toBe('completed');
1218+
expect(convertDialogTurnToBackendFormat(turn).modelRounds).toHaveLength(1);
1219+
expect(readRuntimeSessionProgress(LOCAL_SURFACE_ID, sessionId)).toEqual({ streamId: 'runtime-local', cursor: 6 });
1220+
expect(isRuntimeSessionProjectionStale(LOCAL_SURFACE_ID, sessionId)).toBe(false);
1221+
await vi.advanceTimersByTimeAsync(60_000);
1222+
expect(restore).toHaveBeenCalledTimes(2);
1223+
} finally {
1224+
cleanup?.();
1225+
}
1226+
});
1227+
1228+
it.each(['Idle', 'Processing'])('keeps pristine local persisted content without extra reads when a %s host has no journal', async state => {
1229+
peerModeMock.active = false;
1230+
const store = FlowChatStore.getInstance();
1231+
const sessionId = 'local-legacy';
1232+
store.setState(prev => ({ ...prev, activeSessionId: sessionId, sessions: new Map([[sessionId, {
1233+
sessionId, title: 'Local', workspaceId: 'workspace-1', workspacePath: '/repo/OpenBitFun',
1234+
historyState: 'metadata-only', isHistorical: true, isTransient: false,
1235+
dialogTurns: [], config: { agentType: 'PaperWriting' }, createdAt: 1, lastActiveAt: 1, todos: [],
1236+
} as any]]) }));
1237+
const restore = vi.spyOn(agentAPI, 'restoreSessionView').mockResolvedValue({
1238+
session: { sessionId, state, agentType: 'PaperWriting', createdAt: 1 },
1239+
turns: [{
1240+
turnId: 'turn-legacy', turnIndex: 0, sessionId, timestamp: 1,
1241+
userMessage: { id: 'user-legacy', content: 'Open LaTeX', timestamp: 1 },
1242+
modelRounds: [{ id: 'round-legacy', roundIndex: 0, startTime: 1, status: 'streaming',
1243+
textItems: [{ id: 'text-legacy', content: 'Persisted reply', timestamp: 1 }], toolItems: [], thinkingItems: [] }],
1244+
startTime: 1, status: state === 'Idle' ? 'completed' : 'inprogress',
1245+
}], contextRestoreState: 'ready',
1246+
} as any);
1247+
const cleanup = installPeerSessionRefresh({
1248+
flowChatStore: store, eventBatcher: { flushNow: vi.fn(), clear: vi.fn() },
1249+
contentBuffers: new Map(), activeTextItems: new Map(),
1250+
} as any);
1251+
try {
1252+
await store.loadSessionHistory(sessionId);
1253+
await vi.advanceTimersByTimeAsync(60_000);
1254+
expect(store.getState().sessions.get(sessionId)?.dialogTurns[0].modelRounds[0].items[0]).toMatchObject({ content: 'Persisted reply' });
1255+
expect(restore).toHaveBeenCalledTimes(1);
1256+
expect(agenticListenerMock.dispatchExternal).not.toHaveBeenCalled();
1257+
} finally {
1258+
cleanup();
1259+
}
1260+
});
1261+
11011262
it('replays a cursor-covered ToolEnd until the card is completed', async () => {
11021263
const store = FlowChatStore.getInstance();
11031264
store.setState(prev => ({

0 commit comments

Comments
 (0)