File size: 17,521 Bytes
47a5323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Runs the actual webview and Project message handler against disposable files.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const vm = require('node:vm');
const assert = require('node:assert/strict');
const { createRequire } = require('node:module');
const { pathToFileURL } = require('node:url');
const { spawn } = require('node:child_process');
const extensionDir = path.resolve(__dirname, '..');
const nodeRequire = createRequire(path.join(extensionDir, 'extension.js'));

// Headless Chromium: $CHROME_PATH, else the newest Playwright headless shell in ~/.cache/ms-playwright.
function chromePath() {
  if (process.env.CHROME_PATH) return process.env.CHROME_PATH;
  const cache = path.join(os.homedir(), '.cache/ms-playwright');
  const dirs = fs.existsSync(cache) ? fs.readdirSync(cache).filter((d) => d.startsWith('chromium_headless_shell-')).sort((a, b) => +b.split('-')[1] - +a.split('-')[1]) : [];
  for (const d of dirs) for (const sub of fs.readdirSync(path.join(cache, d))) {
    const exe = path.join(cache, d, sub, 'chrome-headless-shell');
    if (fs.existsSync(exe)) return exe;
  }
  throw new Error('Headless Chromium not found: set CHROME_PATH or run `npx playwright install chromium-headless-shell`.');
}
const sleep = ms => new Promise(r => setTimeout(r, ms));

(async () => {
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'overleaf-webview-sync-'));
  const root = path.join(tmp, 'project'); fs.mkdirSync(root);
  const file = path.join(root, 'main.tex'); fs.writeFileSync(file, 'alpha\nbeta\ngamma\n');
  const file2 = path.join(root, 'other.tex'); fs.writeFileSync(file2, 'second file\n');
  const uri = p => ({ fsPath: p, toString: () => pathToFileURL(p).href });
  const noEvent = () => ({ dispose() {} });
  let handleMessage, project, ws, delaySave = false, held = [], compileSnapshots = [], reloads = 0;
  let delayAck = false, heldAcks = [];
  const errors = [], sent = [], received = [];
  let send;
  const panel = {
    webview: {
      options: {}, cspSource: 'file:', asWebviewUri: x => x,
      onDidReceiveMessage: fn => { handleMessage = fn; },
      postMessage: m => {
        received.push(m);
        if (delayAck && m.type === 'saved') { heldAcks.push(m); return Promise.resolve(true); }
        return send('Runtime.evaluate', { expression: `window.dispatchEvent(new MessageEvent('message',{data:${JSON.stringify(m)}}))` });
      },
    }, onDidDispose: noEvent, onDidChangeViewState: noEvent,
  };
  const vscode = {
    Uri: { file: uri, joinPath: (u, ...p) => uri(path.join(u.fsPath, ...p)) },
    ViewColumn: { Active: 1 }, RelativePattern: class {},
    workspace: { getConfiguration: () => ({ get: () => undefined }), createFileSystemWatcher: () => ({ onDidChange: noEvent, onDidCreate: noEvent, onDidDelete: noEvent, dispose() {} }) },
    window: { createWebviewPanel: () => panel }, commands: { executeCommand: async () => {} },
  };
  const sandbox = { require: name => name === 'vscode' ? vscode : nodeRequire(name), module: { exports: {} }, console, Buffer, process, setTimeout, clearTimeout, setInterval, clearInterval, URL };
  vm.runInNewContext(fs.readFileSync(path.join(extensionDir, 'extension.js'), 'utf8') + '\nmodule.exports.Project = Project;', sandbox, { filename: 'extension.js' });
  const states = new Map([[`overleafStudio.project:${root}`, { main: 'main.tex', ui: { bilingual: false, gptzero: false, pangram: false, autoCompile: false } }]]);
  project = new sandbox.module.exports.Project({
    extensionUri: uri(extensionDir), globalStorageUri: uri(path.join(tmp, 'storage')),
    globalState: { get: (k, fallback) => states.get(k) || fallback, update: (k, v) => { states.set(k, v); return Promise.resolve(); } },
  }, root, panel);
  project.pgBalance = () => {};
  project.compile = () => compileSnapshots.push(fs.readFileSync(file, 'utf8'));
  project.reload = () => { reloads++; };
  const nonce = /nonce="([^"]+)"/.exec(panel.webview.html)[1];
  const bootstrap = `<script nonce="${nonce}">window.acquireVsCodeApi=()=>({postMessage:m=>window.hostMessage(JSON.stringify(m)),getState:()=>JSON.parse(localStorage.getItem('state')||'null'),setState:s=>localStorage.setItem('state',JSON.stringify(s))});</script>`;
  const html = path.join(tmp, 'test.html'); fs.writeFileSync(html, panel.webview.html.replace('<body>', '<body>' + bootstrap));
  const browser = spawn(chromePath(), [
    '--remote-debugging-port=0', '--allow-file-access-from-files', '--no-sandbox', '--window-size=1400,1000', `--user-data-dir=${path.join(tmp, 'chrome')}`, 'about:blank',
  ]);
  let browserLog = ''; browser.stderr.on('data', d => { browserLog += d; });
  const until = async (fn, message, timeout = 5000) => {
    const deadline = Date.now() + timeout;
    while (Date.now() < deadline) { if (await fn()) return; await sleep(30); }
    throw new Error('Timed out: ' + message);
  };
  try {
    await until(() => /DevTools listening on/.test(browserLog), 'browser start');
    const endpoint = /DevTools listening on (ws:\/\/[^\s]+)/.exec(browserLog)[1];
    const port = new URL(endpoint).port;
    const targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
    ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
    await new Promise(r => ws.onopen = r);
    let sequence = 0; const pending = new Map();
    send = (method, params = {}) => new Promise((resolve, reject) => {
      const id = ++sequence; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params }));
    });
    ws.onmessage = async e => {
      const m = JSON.parse(e.data);
      if (m.id) { const p = pending.get(m.id); pending.delete(m.id); if (p) m.error ? p.reject(m.error) : p.resolve(m.result); }
      if (m.method === 'Runtime.exceptionThrown') errors.push(m.params.exceptionDetails);
      if (m.method === 'Runtime.bindingCalled') {
        const message = JSON.parse(m.params.payload); sent.push(message);
        if (delaySave && message.type === 'save') held.push(message);
        else await handleMessage(message);
      }
    };
    await send('Runtime.enable'); await send('Runtime.addBinding', { name: 'hostMessage' });
    const evaluate = async expression => {
      const r = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
      if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails));
      return r.result.value;
    };
    const value = () => evaluate('document.querySelector(".CodeMirror")?.CodeMirror?.getValue()');
    const clean = () => evaluate('!document.querySelector("#tabs .dot")');
    const edit = text => evaluate(`document.querySelector('.CodeMirror').CodeMirror.replaceRange(${JSON.stringify(text)}, {line:0,ch:0}, {line:1000,ch:0}, '+input')`);
    await send('Page.navigate', { url: pathToFileURL(html).href });
    await until(async () => (await value()) === 'alpha\nbeta\ngamma\n', 'initial file');
    await edit('alpha!\nbeta\ngamma\n');
    await until(() => fs.readFileSync(file, 'utf8') === 'alpha!\nbeta\ngamma\n', 'immediate save');
    await until(clean, 'saved marker');
    console.log('PASS: actual CodeMirror edits save and await acknowledgement');

    fs.writeFileSync(file, 'EXTERNAL\nbeta\ngamma\n');
    await until(async () => (await value()) === 'EXTERNAL\nbeta\ngamma\n', 'poll sync without watcher');
    assert.equal(await evaluate('document.querySelector(".CodeMirror").CodeMirror.historySize().undo'), 0);
    console.log('PASS: missed watcher events are caught by polling; stale undo cleared');

    clearInterval(project.syncTimer); // Reproduce an external edit with no notification at all.
    fs.writeFileSync(file, 'NEW PARAGRAPH\nbeta\ngamma\n');
    await edit('EXTERNAL\nbeta\ngamma!\n');
    await until(async () => (await value()) === 'NEW PARAGRAPH\nbeta\ngamma!\n', 'three-way merge');
    assert.equal(fs.readFileSync(file, 'utf8'), 'NEW PARAGRAPH\nbeta\ngamma!\n');
    console.log('PASS: stale buffer typing cannot restore an externally replaced paragraph');

    delaySave = true;
    await edit('NEW PARAGRAPH\nbeta\ngamma!!\n');
    await edit('NEW PARAGRAPH\nbeta\ngamma!!!\n');
    await evaluate('document.querySelector("#recompile-main").click()');
    assert.equal(compileSnapshots.length, 0);
    await until(() => held.length === 1, 'held save');
    delaySave = false; await handleMessage(held.shift());
    await until(() => compileSnapshots.length === 1, 'compile after last ack');
    assert.equal(compileSnapshots[0], 'NEW PARAGRAPH\nbeta\ngamma!!!\n');
    console.log('PASS: Recompile waits for all typing, including edits during the first save');

    // Repeat with a genuine overlap: both versions must survive, including later typing.
    delaySave = true;
    await edit('LOCAL DRAFT\nbeta\ngamma!!!\n');
    await edit('LOCAL DRAFT newest\nbeta\ngamma!!!\n');
    fs.writeFileSync(file, 'DISK VERSION\nbeta\ngamma!!!\n');
    await until(() => held.length === 1, 'conflicting save');
    delaySave = false; await handleMessage(held.shift());
    await until(() => !!project.recoveries.get('main.tex') && fs.readFileSync(project.recoveries.get('main.tex'), 'utf8').includes('newest'), 'latest draft recovery');
    await until(async () => await evaluate('document.querySelector("#save-conflict button") !== null'), 'conflict actions');
    assert.equal(fs.readFileSync(file, 'utf8'), 'DISK VERSION\nbeta\ngamma!!!\n');
    assert.equal(await value(), 'LOCAL DRAFT newest\nbeta\ngamma!!!\n');
    assert.equal(await evaluate('document.querySelector(".CodeMirror").CodeMirror.getOption("readOnly")'), true);
    console.log('PASS: overlapping edits preserve disk and the latest draft, with a persistent conflict banner');
    await evaluate('Array.from(document.querySelectorAll("#save-conflict button")).find(b=>b.textContent.includes("Load latest")).click()');
    await until(async () => (await value()) === 'DISK VERSION\nbeta\ngamma!!!\n', 'reload latest');
    await until(clean, 'reset clean');
    console.log('PASS: explicit reload uses fresh disk content and keeps recovery copy');

    await project.openFile('other.tex');
    await until(async () => (await value()) === 'second file\n', 'switch file');
    fs.writeFileSync(file, 'BACKGROUND UPDATE\n'); project.syncOpenFiles();
    await until(() => received.some(m => m.type === 'external' && m.text === 'BACKGROUND UPDATE\n'), 'inactive update');
    await evaluate('Array.from(document.querySelectorAll("#tabs .tab")).find(t=>t.title==="main.tex").click()');
    await until(async () => (await value()) === 'BACKGROUND UPDATE\n', 'inactive document updated');
    console.log('PASS: inactive tabs receive external edits');

    await evaluate('document.querySelector(".CodeMirror").CodeMirror.getInputField().dispatchEvent(new CompositionEvent("compositionstart"))');
    fs.writeFileSync(file, 'IME EXTERNAL UPDATE\n'); project.syncOpenFiles();
    await sleep(80);
    assert.equal(await value(), 'BACKGROUND UPDATE\n');
    await evaluate('document.querySelector(".CodeMirror").CodeMirror.getInputField().dispatchEvent(new CompositionEvent("compositionend"))');
    await until(async () => (await value()) === 'IME EXTERNAL UPDATE\n', 'IME deferred sync');
    console.log('PASS: external refresh waits until Chinese IME composition finishes');

    delaySave = true; await edit('IME EXTERNAL UPDATE 中文草稿\n');
    await until(() => held.length === 1, 'persisted pending draft');
    // Simulate a reload before the host has received the save. Webview state must recover it.
    held = []; delaySave = false;
    await send('Page.reload');
    await until(() => fs.readFileSync(file, 'utf8') === 'IME EXTERNAL UPDATE 中文草稿\n', 'draft restored after reload');
    await until(clean, 'restored draft confirmed');
    console.log('PASS: interrupted save survives webview reload through persisted draft state');

    delaySave = true; await edit('BACKGROUND UPDATE!\n');
    await panel.webview.postMessage({ type: 'flushAndReload' });
    assert.equal(reloads, 0);
    await until(() => held.length === 1, 'reload save barrier');
    delaySave = false; await handleMessage(held.shift());
    await until(() => reloads === 1, 'reload after ack');
    console.log('PASS: panel reload waits for save confirmation');

    fs.writeFileSync(file, 'FORCED DISK VERSION\n');
    const savesBeforeReload = sent.filter(m => m.type === 'save').length;
    await evaluate('document.querySelector("#reload-disk").click()');
    await until(async () => (await value()) === 'FORCED DISK VERSION\n', 'toolbar forces fresh disk read');
    assert.equal(sent.filter(m => m.type === 'save').length, savesBeforeReload);
    assert.equal(await evaluate('document.querySelector(".CodeMirror").CodeMirror.historySize().undo'), 0);
    assert.equal(await clean(), true);
    console.log('PASS: toolbar reload bypasses cached content without sending a save');

    delayAck = true;
    await edit('FIRST LOCAL EDIT\n');
    await until(() => heldAcks.length === 1, 'delayed acknowledgement');
    await edit('LATEST LOCAL DRAFT\n');
    fs.writeFileSync(file, 'LATEST EXTERNAL VERSION\n');
    const savesBeforeForce = sent.filter(m => m.type === 'save').length;
    await evaluate('document.querySelector("#reload-disk").click()');
    await until(async () => (await value()) === 'LATEST EXTERNAL VERSION\n', 'force reload with pending draft');
    assert.equal(fs.readFileSync(project.recoveries.get('main.tex'), 'utf8'), 'LATEST LOCAL DRAFT\n');
    assert.equal(sent.filter(m => m.type === 'save').length, savesBeforeForce);
    delayAck = false;
    await panel.webview.postMessage(heldAcks.shift());
    await sleep(80);
    assert.equal(await value(), 'LATEST EXTERNAL VERSION\n');
    assert.equal(fs.readFileSync(file, 'utf8'), 'LATEST EXTERNAL VERSION\n');
    assert.deepEqual(await evaluate('JSON.parse(localStorage.getItem("state")).drafts'), {});
    await send('Page.reload');
    await until(async () => (await value()) === 'LATEST EXTERNAL VERSION\n', 'force reload survives panel restart');
    console.log('PASS: pending draft is backed up; stale acknowledgement and restored state cannot undo force reload');

    fs.unlinkSync(file);
    await evaluate('document.querySelector("#reload-disk").click()');
    await until(async () => await evaluate('document.querySelector("#save-conflict").textContent.includes("Reload from disk failed")'), 'missing file reload error');
    assert.equal(await value(), 'LATEST EXTERNAL VERSION\n');
    assert.equal(fs.existsSync(file), false);
    fs.writeFileSync(file, 'RESTORED DISK FILE\n');
    await evaluate('document.querySelector("#reload-disk").click()');
    await until(async () => (await value()) === 'RESTORED DISK FILE\n', 'retry after missing file');
    await edit('BACKGROUND UPDATE!\n');
    await until(clean, 'editing after reload');
    assert.equal(fs.readFileSync(file, 'utf8'), 'BACKGROUND UPDATE!\n');
    console.log('PASS: failed reload retains text, never recreates missing file, and supports retry');

    delayAck = true;
    await edit('DRAFT THAT MUST SURVIVE\n');
    await until(() => heldAcks.length === 1, 'backup failure draft');
    fs.writeFileSync(file, 'DISK DURING BACKUP FAILURE\n');
    const preserveDraft = project.preserveDraft;
    project.preserveDraft = () => { throw new Error('Recovery storage unavailable'); };
    await evaluate('document.querySelector("#reload-disk").click()');
    await until(async () => await evaluate('document.querySelector("#save-conflict").textContent.includes("Could not write recovery copy")'), 'backup failure reported');
    assert.equal(await value(), 'DRAFT THAT MUST SURVIVE\n');
    assert.equal(fs.readFileSync(file, 'utf8'), 'DISK DURING BACKUP FAILURE\n');
    project.preserveDraft = preserveDraft;
    delayAck = false; await panel.webview.postMessage(heldAcks.shift());
    await evaluate('document.querySelector("#reload-disk").click()');
    await until(async () => (await value()) === 'DISK DURING BACKUP FAILURE\n', 'retry after backup failure');
    assert.equal(fs.readFileSync(project.recoveries.get('main.tex'), 'utf8'), 'DRAFT THAT MUST SURVIVE\n');
    await edit('BACKGROUND UPDATE!\n');
    await until(clean, 'save after backup retry');
    console.log('PASS: recovery failure cancels replacement and preserves both versions for retry');

    await project.onMessage({ type: 'save', path: 'main.tex', text: 'STALE LEGACY BUFFER', id: 'legacy' });
    assert.equal(fs.readFileSync(file, 'utf8'), 'BACKGROUND UPDATE!\n');
    await panel.webview.postMessage({ type: 'init', name: 'old backend', root, files: [], main: 'main.tex', ui: {}, keys: {} });
    await until(async () => await evaluate('document.querySelector(".CodeMirror").CodeMirror.getOption("readOnly") === true'), 'protocol mismatch guard');
    const reloadRequests = sent.filter(m => m.type === 'reloadFromDisk').length;
    await evaluate('document.querySelector("#reload-disk").click()');
    await sleep(60);
    assert.equal(sent.filter(m => m.type === 'reloadFromDisk').length, reloadRequests);
    console.log('PASS: mixed old/new extension versions refuse unsafe saves');
    assert.deepEqual(errors, []);
    console.log('PASS: no webview JavaScript errors');
  } finally {
    project.dispose(); if (ws) ws.close(); browser.kill();
    await new Promise(r => browser.once('exit', r));
    fs.rmSync(tmp, { recursive: true, force: true });
  }
})().catch(e => { console.error(e); process.exitCode = 1; });