Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import type { Route } from '@playwright/test'

import { expect, mergeTests } from '@playwright/test'
import { test as editorTest } from '../../support/fixtures/editor.ts'
import { test as uploadFileTest } from '../../support/fixtures/upload-file.ts'

const test = mergeTests(editorTest, uploadFileTest)

const PUSH = /\/apps\/text\/session\/\d+\/push$/
const SESSION_REQUESTS = /\/apps\/text\/session\/\d+\/(sync|push)$/

test.beforeEach(async ({ open }) => {
await open()
})

test('stays read-only when the session is rejected after a connection issue', async ({
editor,
page,
}) => {
test.slow()
await page.clock.install()
const status = page.locator('.document-status')
const content = editor.el.locator('.ProseMirror')
await expect(content).toHaveAttribute('contenteditable', 'true')

// One handler for the whole test, so no request slips through while switching.
let network: 'online' | 'offline' | 'rejected' = 'online'
let releaseSyncs = () => {}
const syncsReleased = new Promise<void>((resolve) => {
releaseSyncs = resolve
})
await page.route(SESSION_REQUESTS, async (route: Route) => {
if (network === 'online') {
return route.continue()
}
if (network === 'offline') {
return route.abort('internetdisconnected')
}
if (PUSH.test(route.request().url())) {
// Answer like SessionMiddleware does for a session it no longer knows.
return route.fulfill({ status: 403, contentType: 'application/json', body: '[]' })
}
// Hold the syncs so that only the rejected push changes the state.
await syncsReleased
return route.abort('internetdisconnected')
})

network = 'offline'
const failedPush = page.waitForEvent('requestfailed', (request) => PUSH.test(request.url()))
await editor.type('Hello')
// The connection issue only starts counting once the push failed.
await failedPush
const delay = await page.evaluate(() => window.OCP.InitialState.loadState('text', 'offline_readonly_delay') as number)
await page.clock.fastForward(delay * 1000 + 1000)
await expect(status).toContainText('The document could not be loaded.')
await expect(content).toHaveAttribute('contenteditable', 'false')

network = 'rejected'
// The autosave retries the push, which is rejected.
await page.clock.fastForward(60_000)
await expect(status).toContainText("You've been disconnected from the server.")
// Clearing the connection issue takes effect after 200 ms.
await page.waitForTimeout(1000)
await expect(content).toHaveAttribute('contenteditable', 'false')

network = 'online'
releaseSyncs()
await status.getByRole('button', { name: 'Reconnect' }).click()
await expect(status).not.toContainText("You've been disconnected from the server.")
await expect(content).toHaveAttribute('contenteditable', 'true')
await expect(editor.content).toContainText('Hello')
})
8 changes: 6 additions & 2 deletions src/components/CollaborativeEditor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ export default defineComponent({
if (val) {
this.$emit('syncService:error')
}
this.setEditable(!val) // TODO: can we remove this now with indexed DB?
this.setEditable(!val && this.editMode) // TODO: can we remove this now with indexed DB?
},

async hasOutdatedDocument(val) {
Expand Down Expand Up @@ -551,6 +551,8 @@ export default defineComponent({
const timeout = new Promise((resolve) => setTimeout(resolve, 2000))
await Promise.any([timeout, this.saveWhenDirty()])
await this.close()
// The dirty watcher that removes it no longer runs after unmounting
window.removeEventListener('beforeunload', this.saveBeforeUnload)
removeFromDebugging(this)
},

Expand Down Expand Up @@ -739,7 +741,7 @@ export default defineComponent({
// Server rejected the session. Behave like an idle disconnect:
// read-only editor with a permanent status card offering to reconnect.
this.idle = true
this.hasConnectionIssues = false
this.hasConnectionIssue = false
Comment thread
mejo- marked this conversation as resolved.
Resolved
Comment thread
mejo- marked this conversation as resolved.
Resolved
Comment thread
mejo- marked this conversation as resolved.
Resolved
Comment thread
mejo- marked this conversation as resolved.
Resolved
this.readOnly = true
this.editMode = false
this.setEditable(this.editMode)
Expand Down Expand Up @@ -847,6 +849,8 @@ export default defineComponent({
logger.warn('Failed to destroy editor', { error })
}
}
// Also close the IndexedDB connection and stop the awareness interval
this.ydoc.destroy()
Comment thread
mejo- marked this conversation as resolved.
Resolved
Comment thread
mejo- marked this conversation as resolved.
Resolved
Comment thread
mejo- marked this conversation as resolved.
Resolved

// Update the file in Files with the latest size, mtime, the lock state
if (this.fileNode) {
Expand Down
2 changes: 1 addition & 1 deletion src/components/Editor/DocumentStatus.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<template>
<div class="document-status" :class="{ mobile: isMobile }">
<div class="status-wrapper">
<div class="status-wrapper" role="status">
<SyncStatus
:idle="idle"
:syncError="syncError"
Expand Down
16 changes: 8 additions & 8 deletions src/components/Editor/DocumentStatus/SyncStatus.vue
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ export default {
),
}
}
if (this.idle) {
return {
type: 'info',
message: t('text', "You've been disconnected from the server."),
action: this.reconnect,
actionLabel: t('text', 'Reconnect'),
}
}
if (this.hasConnectionIssue) {
return {
message: t(
Expand All @@ -86,14 +94,6 @@ export default {
actionLabel: t('text', 'Reconnect'),
}
}
if (this.idle) {
return {
type: 'info',
message: t('text', "You've been disconnected from the server."),
action: this.reconnect,
actionLabel: t('text', 'Reconnect'),
}
}
return {}
},

Expand Down
14 changes: 8 additions & 6 deletions src/composables/useIndexedDbProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@ export function useIndexedDbProvider(
const name = `text-${props.context.type}-${props.context.id}`
const indexedDbProvider = new IndexeddbPersistence(name, ydoc)
const dirty = ref(false)
let isDestroyed = false
let isCleared = false
// The provider also closes its database when the ydoc is destroyed
const isClosed = () => isCleared || ydoc.isDestroyed
const whenSynced: Promise<void> = indexedDbProvider.whenSynced.then(async () => {
const val = await indexedDbProvider.get('dirty')
dirty.value = Boolean(val)
logger.info('synced from indexeddb', {
dirty: val,
baseVersionEtag: await indexedDbProvider.get('baseVersionEtag'),
baseVersionEtag: await getBaseVersionEtag(),
})
})

Expand All @@ -43,7 +45,7 @@ export function useIndexedDbProvider(
*/
function setDirty(val: boolean) {
dirty.value = Boolean(val)
if (isDestroyed) {
if (isClosed()) {
logger.debug('IndexedDB already destroyed, skipping setDirty')
return Promise.resolve()
}
Expand All @@ -54,7 +56,7 @@ export function useIndexedDbProvider(
* Get the base version etag the document had when it was edited last.
*/
function getBaseVersionEtag(): Promise<string | undefined> {
if (isDestroyed) {
if (isClosed()) {
logger.debug('IndexedDB already destroyed, skipping getBaseVersionEtag')
return Promise.resolve(undefined)
}
Expand All @@ -67,7 +69,7 @@ export function useIndexedDbProvider(
* @param val the base version etag as returned by open.
*/
function setBaseVersionEtag(val: string) {
if (isDestroyed) {
if (isClosed()) {
logger.debug('IndexedDB already destroyed, skipping setBaseVersionEtag')
return Promise.resolve(undefined)
}
Expand All @@ -80,7 +82,7 @@ export function useIndexedDbProvider(
*/
function clearIndexedDb() {
logger.info('clearing indexeddb')
isDestroyed = true
isCleared = true
return indexedDbProvider.clearData()
}

Expand Down
18 changes: 14 additions & 4 deletions src/composables/useSaveService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,17 @@ export function provideSaveService(
})

const versionWithChanges = ref<number>(0)

/**
* Schedule an autosave unless all pushed changes are saved.
* Retried pushes and pushes during a save are not followed by an editor update that triggers it.
*/
function autosaveUnsavedChanges() {
if ((document.value?.lastSavedVersion ?? 0) < versionWithChanges.value && !saveService.autosave.isPending) {
saveService.autosave()
}
}

/**
* Update the tracked version based on the one in the event
*
Expand All @@ -101,14 +112,13 @@ export function provideSaveService(
*/
function updateVersionWithChanges(event: { version: number }) {
versionWithChanges.value = Math.max(event.version, versionWithChanges.value)
// Retried pushes are not preceded by an editor update that triggers the autosave
if ((document.value?.lastSavedVersion ?? 0) < event.version && !saveService.autosave.isPending) {
saveService.autosave()
}
autosaveUnsavedChanges()
}
syncService.bus.on('changesPushed', updateVersionWithChanges)
saveService.bus.on('save', autosaveUnsavedChanges)
onUnmounted(() => {
syncService.bus.off('changesPushed', updateVersionWithChanges)
saveService.bus.off('save', autosaveUnsavedChanges)
})

const hasPendingChanges = ref(false)
Expand Down
13 changes: 9 additions & 4 deletions src/services/SaveService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,13 @@ class SaveService {
*/
async save({ force = false, manualSave = true } = {}) {
logger.debug('[SaveService] saving', { force, manualSave })
// Save the version that includes the local changes
await this.pushChanges()
// Pushing may have invalidated the session
if (!this.connection.value) {
logger.warn('Could not save due to missing connection')
return
}
// Save the version that includes the local changes
await this.pushChanges()
const data = this.getSaveData()
try {
this.lastSaveAttempt = Date.now()
Expand All @@ -81,14 +82,18 @@ class SaveService {
force,
manualSave,
})
const saved = response.data.document.lastSavedVersion >= data.version
// Before emitting, so listeners can schedule an autosave for newer changes
if (saved) {
this.clearAutosave()
}
// update the document - even if the save was throttled
this.bus.emit('save', response.data)
if (response.data.document.lastSavedVersion < data.version) {
if (!saved) {
logger.debug('[SaveService] Server throttled save request.', { response })
return false
}
logger.debug('[SaveService] saved', { response })
this.clearAutosave()
return true
} catch (e) {
logger.error('Failed to save document.', { error: e })
Expand Down
29 changes: 22 additions & 7 deletions src/services/SyncService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ class SyncService {
bus = mitt<EventTypes>()
#openConnection: () => Promise<OpenData>
#lastStepPush = Date.now()
#sending = false
#pushing?: Promise<void>

constructor({
connection,
Expand Down Expand Up @@ -173,19 +173,34 @@ class SyncService {
return
}
this.#sendIntervalId = setInterval(() => {
if (this.connection.value && !this.#sending) {
if (!this.connection.value) {
// Closed or rejected: the next step after reconnecting starts a new interval
clearInterval(this.#sendIntervalId)
this.#sendIntervalId = undefined
return
}
if (!this.#pushing) {
this.sendStepsNow().catch((err) => logger.error(err))
}
}, 200)
}

async sendStepsNow() {
this.#sending = true
/**
* Push the outbox to the server.
* Joins a push that is still in flight, as it would otherwise send the same steps twice.
*/
sendStepsNow(): Promise<void> {
this.#pushing ??= this.#push().finally(() => {
this.#pushing = undefined
})
return this.#pushing
}

async #push() {
clearInterval(this.#sendIntervalId)
this.#sendIntervalId = undefined
const hadUpdate = this.#outbox.hasUpdate
if (!this.hasActiveConnection()) {
this.#sending = false
return
}
const sendable = this.#outbox.getDataToSend()
Expand All @@ -204,7 +219,6 @@ class SyncService {
this.#emitDocumentStateStep(documentState, version)
}
this.pushError = 0
this.#sending = false
if (steps?.length > 0) {
this.receiveSteps({ steps })
if (hadUpdate) {
Expand All @@ -216,7 +230,6 @@ class SyncService {
})
.catch((err) => {
const { response, code } = err
this.#sending = false
this.pushError++
logger.error('Failed to push the steps to the server', err)
if (!response || code === 'ECONNABORTED') {
Expand Down Expand Up @@ -279,6 +292,8 @@ class SyncService {
}

async sendRemainingSteps() {
// A push in flight may fail or miss steps added since it started
await this.#pushing?.catch(() => {})
if (!this.#outbox.hasUpdate) {
return
}
Expand Down
7 changes: 7 additions & 0 deletions src/tests/components/SyncStatus.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ FLAGS.forEach((flag) => {
})
})

test('shows the disconnected state despite a connection issue', () => {
const wrapper = shallowMount(SyncStatus, {
propsData: { idle: true, hasConnectionIssue: true },
})
expect(wrapper.text()).toContain("You've been disconnected from the server.")
})

Object.values(ERROR_TYPE).forEach((type) => {
test(`renders sync error ${type}`, () => {
const data = {
Expand Down
Loading
Loading