diff --git a/lib/Listeners/LoadViewerListener.php b/lib/Listeners/LoadViewerListener.php
index 4a9fe962f3a..3ec71beba71 100644
--- a/lib/Listeners/LoadViewerListener.php
+++ b/lib/Listeners/LoadViewerListener.php
@@ -8,14 +8,24 @@
namespace OCA\Text\Listeners;
+use OCA\Text\Service\ConfigService;
use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent;
use OCP\AppFramework\Http\TemplateResponse;
+use OCP\AppFramework\Services\IInitialState;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
+use OCP\IUserSession;
use OCP\Util;
/** @implements IEventListener */
class LoadViewerListener implements IEventListener {
+ public function __construct(
+ private readonly IInitialState $initialState,
+ private readonly IUserSession $userSession,
+ private readonly ConfigService $configService,
+ ) {
+ }
+
public function handle(Event $event): void {
if (!($event instanceof BeforeTemplateRenderedEvent)) {
return;
@@ -27,5 +37,10 @@ public function handle(Event $event): void {
// Only registers the handler: the editor loads when a text file opens
Util::addInitScript('text', 'text-viewer');
+ // Whether comparisons offer summaries, known without a request
+ $this->initialState->provideLazyInitialState(
+ 'version_summaries',
+ fn () => $this->configService->isVersionSummariesAvailableFor($this->userSession->getUser()),
+ );
}
}
diff --git a/playwright/e2e/version-summaries.spec.ts b/playwright/e2e/version-summaries.spec.ts
new file mode 100644
index 00000000000..5794f40c920
--- /dev/null
+++ b/playwright/e2e/version-summaries.spec.ts
@@ -0,0 +1,421 @@
+/**
+ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import type { Page, Request } from '@playwright/test'
+import type { ViewerSection } from '../support/sections/ViewerSection.ts'
+
+import { runOcc } from '@nextcloud/e2e-test-server/docker'
+import { createRandomUser, login } from '@nextcloud/e2e-test-server/playwright'
+import { expect, mergeTests, request } from '@playwright/test'
+import { test as randomUserTest } from '../support/fixtures/random-user.ts'
+import { test as uploadFileTest } from '../support/fixtures/upload-file.ts'
+
+const test = mergeTests(randomUserTest, uploadFileTest)
+
+// Core's testing provider answers with this, then the input it got
+const SUMMARY = /^This is a fake response message:/
+const now = Math.floor(Date.now() / 1000)
+
+async function providerFails(fail: boolean) {
+ await runOcc(['config:app:set', 'testing', 'fail-testing-text2textchat', '--type=boolean', `--value=${fail}`])
+}
+
+// As an admin does, so the web server sees it at once
+async function turnSummaries(enabled: boolean) {
+ const admin = await request.newContext({
+ baseURL: process.env.baseURL ?? 'http://localhost:8089/index.php/',
+ extraHTTPHeaders: { 'OCS-APIRequest': 'true', Authorization: 'Basic ' + btoa('admin:admin') },
+ })
+ await admin.put('../ocs/v2.php/apps/text/settings/version-summaries', { data: { enabled }, failOnStatusCode: true })
+ await admin.dispose()
+}
+
+async function processTasks() {
+ await runOcc(['taskprocessing:worker', '--timeout=4', '--interval=1'])
+}
+
+function countSummaryRequests(page: Page) {
+ const requests: string[] = []
+ page.on('request', (request: Request) => {
+ if (request.url().includes('/apps/text/version-summaries/')) {
+ requests.push(request.method())
+ }
+ })
+ return {
+ lookups: () => requests.filter((method) => method === 'GET').length,
+ starts: () => requests.filter((method) => method === 'POST').length,
+ }
+}
+
+async function compareToCurrent(page: Page, viewer: ViewerSection, index = 1) {
+ const versions = await viewer.openSidebarTab('Versions')
+ await versions.getByRole('button').nth(index).click()
+ await page.getByRole('menuitem', { name: 'Compare to current version' }).click()
+ await expect(page.locator('[data-text-version-summary]')).toBeAttached()
+}
+
+const summarize = (page: Page) => page.getByRole('button', { name: 'Summarize changes' })
+const summaryText = (page: Page) => page.locator('[data-text-version-summary-text]')
+// Beside the button in the header, or below it where the header has no room
+const disclosure = (page: Page) => page.getByText('Both complete versions are sent to the AI provider of this Nextcloud.').filter({ visible: true })
+const underWay = (page: Page) => page.locator('.text-version-summary__title', { hasText: 'Summarizing changes…' })
+
+// What the suite changes, as it was before, to put back afterwards
+const CHANGED = [['text', 'version_summaries_hourly_limit'], ['text', 'version_summaries_user_hourly_limit'], ['core', 'ai.taskprocessing_provider_preferences']] as const
+const before: { testing: boolean, enabled: boolean, values: (string | null)[] } = { testing: false, enabled: false, values: [] }
+
+test.beforeAll(async () => {
+ const { stdout: apps } = await runOcc(['app:list', '--enabled', '--output=json'])
+ before.testing = 'testing' in (JSON.parse(apps).enabled ?? {})
+ const enabled = await runOcc(['config:app:get', 'text', 'version_summaries_enabled'], { failOnError: false })
+ before.enabled = enabled.exitCode === 0 && ['1', 'true'].includes(enabled.stdout.trim())
+ before.values = await Promise.all(CHANGED.map(async ([app, key]) => {
+ const value = await runOcc(['config:app:get', app, key], { failOnError: false })
+ return value.exitCode === 0 ? value.stdout.trim() : null
+ }))
+
+ // Only here: its providers add the assistant to every editor's menu
+ await runOcc(['app:enable', 'testing'])
+ // More summaries start here in an hour than the default allows
+ await runOcc(['config:app:set', 'text', 'version_summaries_hourly_limit', '--type=integer', '--value=1000'])
+ await runOcc(['config:app:set', 'text', 'version_summaries_user_hourly_limit', '--type=integer', '--value=1000'])
+ await turnSummaries(true)
+ await runOcc(['config:app:set', 'core', 'ai.taskprocessing_provider_preferences', '--value={"core:text2text:chat":"testing-text2textchat"}'])
+})
+
+test.afterAll(async () => {
+ // Every step on its own, so one that fails leaves none of the others as the suite set them
+ const steps = [
+ () => turnSummaries(before.enabled),
+ ...CHANGED.map(([app, key], index) => () => before.values[index] === null
+ ? runOcc(['config:app:delete', app, key])
+ : runOcc(['config:app:set', app, key, `--value=${before.values[index]}`])),
+ () => (before.testing ? Promise.resolve() : runOcc(['app:disable', 'testing'])),
+ ]
+ const failures: unknown[] = []
+ for (const step of steps) {
+ await step().catch((error: unknown) => failures.push(error))
+ }
+ if (failures.length > 0) {
+ throw failures[0]
+ }
+})
+
+test.beforeEach(async () => {
+ await providerFails(false)
+ await processTasks()
+})
+
+test.describe('Summaries of changes in Files', () => {
+ test.use({
+ fileName: 'plan.md',
+ fileContent: '# Plan\n\nThe pilot runs 3 weeks.',
+ oldVersions: [[{ content: '# Plan\n\nThe pilot runs 2 weeks.', mtime: now - 7200 }], { scope: 'test' }],
+ })
+
+ test('summarizes the compared versions on request, once', async ({ open, page, viewer }) => {
+ const count = countSummaryRequests(page)
+ await open()
+ await compareToCurrent(page, viewer)
+ await expect(summarize(page)).toBeEnabled()
+ await expect(disclosure(page)).toBeVisible()
+ // Opening asks once and starts nothing
+ expect([count.lookups(), count.starts()]).toEqual([1, 0])
+
+ await summarize(page).click()
+ await expect(underWay(page)).toBeVisible()
+ await expect(summarize(page)).toHaveCount(0)
+ await processTasks()
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+ await expect(page.getByText('AI-generated, may omit or misstate changes')).toBeVisible()
+ expect(count.starts()).toBe(1)
+
+ // Switching the view and the filter asks for nothing
+ const lookups = count.lookups()
+ await page.keyboard.press('d')
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+ await page.keyboard.press('d')
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+ await page.waitForTimeout(500)
+ expect([count.lookups(), count.starts()]).toEqual([lookups, 1])
+ })
+
+ test('collapses the summary and copies it with its label', async ({ open, page, viewer }) => {
+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
+ await open()
+ await compareToCurrent(page, viewer)
+ await summarize(page).click()
+ await processTasks()
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+
+ await page.getByRole('button', { name: 'Copy summary' }).click()
+ await expect(page.getByRole('button', { name: 'Copied' })).toBeVisible()
+ const copied = await page.evaluate(() => navigator.clipboard.readText())
+ expect(copied).toMatch(/^AI summary of changes in plan\.md, From .* to the current version \(.*\) \(AI-generated, may omit or misstate changes\):\n\nThis is a fake response message/)
+
+ const toggle = page.locator('.text-version-summary__actions button[aria-expanded]')
+ await toggle.focus()
+ await page.keyboard.press('Enter')
+ await expect(toggle).toHaveAttribute('aria-expanded', 'false')
+ await expect(summaryText(page)).toBeHidden()
+ await page.keyboard.press('Space')
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true')
+ })
+
+ test('keeps a summary under way when the comparison closes and opens again', async ({ open, page, viewer }) => {
+ const count = countSummaryRequests(page)
+ await open()
+ await compareToCurrent(page, viewer)
+ await summarize(page).click()
+ await expect(underWay(page)).toBeVisible()
+ await page.locator('.viewer__comparison').locator('xpath=ancestor::*[@role="dialog"][1]').getByRole('button', { name: 'Close', exact: true }).first().click()
+
+ await page.reload()
+ await open()
+ await compareToCurrent(page, viewer)
+ await expect(underWay(page)).toBeVisible()
+ await processTasks()
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+ expect(count.starts()).toBe(1)
+ })
+
+ test('says what failed, and tries again on request', async ({ open, page, viewer }) => {
+ await providerFails(true)
+ await open()
+ await compareToCurrent(page, viewer)
+ await summarize(page).click()
+ await processTasks()
+ await expect(page.locator('.text-version-summary__note')).toContainText('The summary could not be created.')
+ const tryAgain = page.getByRole('button', { name: 'Try again' })
+ await expect(tryAgain).toBeFocused()
+
+ await providerFails(false)
+ await tryAgain.click()
+ await processTasks()
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+ })
+
+ test('refuses texts that changed after the comparison opened, and reloads them', async ({ open, page, user, viewer }) => {
+ await open()
+ await compareToCurrent(page, viewer)
+ await user.uploadFile({ name: 'plan.md', content: '# Plan\n\nThe pilot runs 4 weeks.', mtime: now + 10 })
+
+ await summarize(page).click()
+ await expect(page.locator('.text-version-summary__note')).toContainText('This file changed after you opened the comparison.')
+ await page.getByRole('button', { name: 'Reload comparison' }).click()
+ await expect(page.getByRole('article', { name: 'After' }).getByText('4 weeks')).toBeVisible()
+ await expect(summarize(page)).toBeEnabled()
+ })
+
+ test('shows a stored summary to everyone who can open both versions, at once', async ({ browser, baseURL, open, page, viewer }) => {
+ await open()
+ await compareToCurrent(page, viewer)
+ await summarize(page).click()
+ await processTasks()
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+
+ const reader = await createRandomUser()
+ await page.request.post('/ocs/v2.php/apps/files_sharing/api/v1/shares', {
+ data: { path: '/plan.md', shareType: 0, shareWith: reader.userId, permissions: 1 },
+ headers: { Accept: 'application/json', 'OCS-APIRequest': 'true' },
+ failOnStatusCode: true,
+ })
+ const readerPage = await browser.newPage({ storageState: undefined, baseURL })
+ await login(readerPage.request, reader)
+ const count = countSummaryRequests(readerPage)
+ await readerPage.goto('apps/files')
+ await readerPage.locator('[data-cy-files-list-row-name="plan.md"]').click({ button: 'right' })
+ await readerPage.getByRole('menuitem', { name: 'Details' }).click()
+ await readerPage.getByRole('tab', { name: 'Versions' }).click()
+ await readerPage.getByRole('tabpanel', { name: 'Versions' }).getByRole('button').nth(1).click()
+ await readerPage.getByRole('menuitem', { name: 'Compare to current version' }).click()
+
+ await expect(summaryText(readerPage)).toHaveText(SUMMARY)
+ expect([count.lookups(), count.starts()]).toEqual([1, 0])
+ await readerPage.close()
+ })
+})
+
+test.describe('A file written by another app', () => {
+ test.use({
+ fileName: 'elsewhere.md',
+ // Text saves it without the final line break when its editor closes
+ fileContent: '# Plan\n\nThe pilot runs 3 weeks.\n',
+ oldVersions: [[{ content: '# Plan\n\nThe pilot runs 2 weeks.\n', mtime: now - 7200 }], { scope: 'test' }],
+ })
+
+ test('compares the file as the closing editor saved it', async ({ open, page, viewer }) => {
+ await open()
+ await expect(viewer.el.locator('.ProseMirror')).toContainText('The pilot runs 3 weeks')
+ await compareToCurrent(page, viewer)
+
+ await expect(summarize(page)).toBeEnabled()
+ await expect(page.getByText('This file changed after you opened the comparison.')).toHaveCount(0)
+ })
+})
+
+test.describe('The setting', () => {
+ test('cannot be changed by someone who is not an administrator', async ({ page }) => {
+ const response = await page.request.put('../ocs/v2.php/apps/text/settings/version-summaries', {
+ data: { enabled: false },
+ headers: { 'OCS-APIRequest': 'true' },
+ })
+
+ expect(response.status()).toBe(403)
+ const enabled = await runOcc(['config:app:get', 'text', 'version_summaries_enabled'])
+ expect(['1', 'true']).toContain(enabled.stdout.trim())
+ })
+})
+
+test.describe('Versions that look the same', () => {
+ test.use({
+ fileName: 'spacing.md',
+ fileContent: '# Plan\n\nThe pilot runs 3 weeks.',
+ oldVersions: [[{ content: '# Plan\n\n\nThe pilot runs 3 weeks.\n', mtime: now - 7200 }], { scope: 'test' }],
+ })
+
+ test('offers no summary', async ({ open, page, viewer }) => {
+ await open()
+ await compareToCurrent(page, viewer)
+
+ await expect(page.locator('.text-version-summary-start__note')).toHaveText('The two versions look the same. Only their Markdown source differs.')
+ await expect(summarize(page)).toHaveCount(0)
+ })
+})
+
+test.describe('Summaries of each step', () => {
+ test.use({
+ fileName: 'steps.md',
+ fileContent: '# Plan\n\nThe pilot runs 4 weeks.',
+ oldVersions: [[
+ { content: '# Plan\n\nThe pilot runs 2 weeks.', mtime: now - 7200 },
+ { content: '# Plan\n\nThe pilot runs 3 weeks.', mtime: now - 1800 },
+ ], { scope: 'test' }],
+ })
+
+ test('summarizes another pair after changing an end', async ({ open, page, viewer }) => {
+ const count = countSummaryRequests(page)
+ await open()
+ await compareToCurrent(page, viewer, 2)
+ await summarize(page).click()
+ await processTasks()
+ // Core's testing provider answers with the texts it got
+ await expect(summaryText(page)).toContainText('The pilot runs 2 weeks.')
+
+ // Changing the pair asks about the new pair and starts nothing
+ await page.locator('[data-comparison-picker="from"]').getByRole('button').click()
+ await page.getByRole('menuitemradio').nth(1).click()
+ await expect(summarize(page)).toBeEnabled()
+ expect(count.starts()).toBe(1)
+ await summarize(page).click()
+ await processTasks()
+ await expect(summaryText(page)).toContainText('The pilot runs 3 weeks.')
+ await expect(summaryText(page)).not.toContainText('The pilot runs 2 weeks.')
+ expect(count.starts()).toBe(2)
+ })
+
+ test('summarizes the recent changes from the Files sidebar', async ({ open, page, viewer }) => {
+ const count = countSummaryRequests(page)
+ await open()
+ await viewer.openSidebarTab('Versions')
+ await page.locator('.app-sidebar-header').getByRole('button', { name: 'Actions' }).click()
+ await page.getByRole('menuitem', { name: 'Summarize recent changes' }).click()
+
+ // From the newest version at least an hour older: the one of two hours ago
+ await expect(page.locator('[data-comparison-select]')).toHaveCount(1)
+ await expect(page.locator('[data-comparison-select] del')).toHaveText('2')
+ await expect(page.locator('[data-comparison-picker="from"]')).toBeVisible()
+ // Nothing is sent before the user saw what is sent
+ await expect(disclosure(page)).toBeVisible()
+ expect(count.starts()).toBe(0)
+ await summarize(page).click()
+ await processTasks()
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+ expect(count.starts()).toBe(1)
+ })
+})
+
+test.describe('A file without older versions', () => {
+ test.use({ fileName: 'new.md', fileContent: '# New' })
+
+ test('says there is nothing to summarize yet', async ({ open, page, viewer }) => {
+ await open()
+ await viewer.openSidebarTab('Versions')
+ await page.locator('.app-sidebar-header').getByRole('button', { name: 'Actions' }).click()
+ await page.getByRole('menuitem', { name: 'Summarize recent changes' }).click()
+
+ await expect(page.getByText('This file has no earlier versions yet.').first()).toBeVisible()
+ })
+})
+
+test.describe('On a phone', () => {
+ test.use({
+ viewport: { width: 390, height: 844 },
+ fileName: 'phone.md',
+ fileContent: '# Plan\n\nThe pilot runs 3 weeks.',
+ oldVersions: [[{ content: '# Plan\n\nThe pilot runs 2 weeks.', mtime: now - 7200 }], { scope: 'test' }],
+ })
+
+ test('summarizes the recent changes from the Files sidebar', async ({ file, page }) => {
+ await page.goto('apps/files')
+ await page.locator(`[data-cy-files-list-row-name="${file.name}"]`).getByRole('button', { name: 'Actions' }).click()
+ await page.getByRole('menuitem', { name: 'Details' }).click()
+ await page.locator('.app-sidebar-header').getByRole('button', { name: 'Actions' }).click()
+ await page.getByRole('menuitem', { name: 'Summarize recent changes' }).click()
+
+ await expect(page.locator('[data-comparison-picker]')).toHaveCount(2)
+ await summarize(page).click()
+ await processTasks()
+ await expect(summaryText(page)).toHaveText(SUMMARY)
+ await expect(summaryText(page)).toBeInViewport()
+ })
+})
+
+test.describe('Without a chat provider', () => {
+ test.use({
+ fileName: 'plan.md',
+ fileContent: '# Plan\n\nThe pilot runs 3 weeks.',
+ oldVersions: [[{ content: '# Plan\n\nThe pilot runs 2 weeks.', mtime: now - 7200 }], { scope: 'test' }],
+ })
+ test.afterEach(async () => {
+ await runOcc(['app:enable', 'testing'])
+ })
+
+ test('says why summaries cannot be made', async ({ open, page, viewer }) => {
+ await runOcc(['app:disable', 'testing'])
+ await open()
+ await compareToCurrent(page, viewer)
+ await expect(summarize(page)).toBeDisabled()
+ await expect(page.locator('.text-version-summary-start__note')).toHaveText('Summaries are not available: no AI provider is set up. Ask your administrator.')
+ })
+})
+
+test.describe('With summaries turned off', () => {
+ test.use({
+ fileName: 'off.md',
+ fileContent: '# Plan\n\nThe pilot runs 3 weeks.',
+ oldVersions: [[{ content: '# Plan\n\nThe pilot runs 2 weeks.', mtime: now - 7200 }], { scope: 'test' }],
+ })
+
+ test.afterEach(async () => {
+ await turnSummaries(true)
+ })
+
+ test('loads and asks for nothing', async ({ open, page, viewer }) => {
+ await turnSummaries(false)
+ const loaded: string[] = []
+ page.on('request', (request) => loaded.push(request.url()))
+ await open()
+ const versions = await viewer.openSidebarTab('Versions')
+ await versions.getByRole('button').nth(1).click()
+ await page.getByRole('menuitem', { name: 'Compare to current version' }).click()
+ await expect(page.getByRole('article', { name: 'After' })).toBeVisible()
+
+ expect(loaded.filter((url) => url.includes('VersionSummary') || url.includes('version-summaries')).map((url) => url.split('/').pop())).toEqual([])
+ await expect(page.locator('[data-text-version-summary]')).toHaveCount(0)
+ await page.locator('.app-sidebar-header').getByRole('button', { name: 'Actions' }).click()
+ await expect(page.getByRole('menuitem', { name: 'Summarize recent changes' })).toHaveCount(0)
+ })
+})
diff --git a/src/comparison/decode.ts b/src/comparison/decode.ts
new file mode 100644
index 00000000000..ee316d07469
--- /dev/null
+++ b/src/comparison/decode.ts
@@ -0,0 +1,74 @@
+/**
+ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import { toHexString } from 'lib0/buffer'
+import { digest } from 'lib0/hash/sha256'
+
+/** What the comparison knows of one end beyond its text */
+export interface LoadedText {
+ text: string
+ /** Hex SHA-256 of the raw bytes, as the server computes it */
+ sha256: string
+ /** Whether the bytes are valid UTF-8, the only encoding summaries take */
+ utf8: boolean
+ /** When the server last changed it, in seconds, if it said */
+ modified?: number
+}
+
+/**
+ * Read a fetched file the way a browser reads a text response: a byte order
+ * mark decides the encoding, then the charset of the response, then UTF-8.
+ *
+ * @param bytes The raw bytes.
+ * @param contentType The `Content-Type` of the response.
+ */
+export function decodeText(bytes: Uint8Array, contentType?: string): string {
+ const boms: [number[], string][] = [[[0xEF, 0xBB, 0xBF], 'utf-8'], [[0xFE, 0xFF], 'utf-16be'], [[0xFF, 0xFE], 'utf-16le']]
+ for (const [bom, encoding] of boms) {
+ if (bom.every((byte, i) => bytes[i] === byte)) {
+ return new TextDecoder(encoding, { ignoreBOM: true }).decode(bytes.subarray(bom.length))
+ }
+ }
+ const charset = contentType?.match(/charset=["']?([^;"'\s]+)/i)?.[1]
+ try {
+ return new TextDecoder(charset ?? 'utf-8', { ignoreBOM: true }).decode(bytes)
+ } catch {
+ // An unknown label
+ return new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes)
+ }
+}
+
+/**
+ * The text of a fetched file and what identifies it.
+ *
+ * @param buffer The raw response.
+ * @param headers The response headers.
+ */
+export function loadText(buffer: ArrayBuffer, headers: Record = {}): LoadedText {
+ const bytes = new Uint8Array(buffer)
+ const lastModified = Date.parse(String(headers['last-modified'] ?? ''))
+ // Worked out only for a summary, which most comparisons never ask for
+ let sha256: string | undefined
+ let utf8: boolean | undefined
+ return {
+ text: decodeText(bytes, headers['content-type'] as string | undefined),
+ get sha256() {
+ sha256 ??= toHexString(digest(bytes))
+ return sha256
+ },
+ get utf8() {
+ if (utf8 === undefined) {
+ try {
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes)
+ utf8 = true
+ } catch {
+ utf8 = false
+ }
+ }
+ return utf8
+ },
+ modified: Number.isNaN(lastModified) ? undefined : lastModified / 1000,
+ }
+}
diff --git a/src/comparison/session.ts b/src/comparison/session.ts
index 889ec58b53f..016a2bb18e0 100644
--- a/src/comparison/session.ts
+++ b/src/comparison/session.ts
@@ -278,6 +278,7 @@ export function createComparisonSession(beforeContent: string, afterContent: str
editors,
labels,
legends,
+ changeCount: changes.length,
formattingCount: changes.filter(({ category }) => category === 'formatting').length,
...state,
select,
diff --git a/src/comparison/sharedComparison.ts b/src/comparison/sharedComparison.ts
index ab4aa987164..094b9d83d26 100644
--- a/src/comparison/sharedComparison.ts
+++ b/src/comparison/sharedComparison.ts
@@ -5,23 +5,18 @@
import type { IFile } from '@nextcloud/files'
import type { Ref, ShallowRef } from 'vue'
+import type { LoadedText } from './decode.ts'
import type { ComparisonSession } from './session.ts'
import axios from '@nextcloud/axios'
import { nextTick, onScopeDispose, ref, shallowRef } from 'vue'
import { closingSaveOf } from '../helpers/closingSaves.ts'
import { logger } from '../helpers/logger.ts'
+import { loadText } from './decode.ts'
import { createComparisonSession } from './session.ts'
import { comparedEnds, endOf, isCurrent } from './versionEnds.ts'
import { useFileVersions } from './versions.ts'
-/** A file as it was loaded */
-interface LoadedText {
- text: string
- /** When the server last changed it, in seconds, if it said */
- modified?: number
-}
-
/** Both texts compared, as they were loaded */
export interface ComparedTexts {
before: LoadedText
@@ -39,6 +34,10 @@ interface SharedComparison {
error: Ref
/** Whether the error is that the editor it replaces could not save */
unsaved: Ref
+ /** Height of the summary in one pane, which the other pane leaves free so both documents start level */
+ summaryHeight: Ref
+ /** The newer document's pane side by side, which the summary spans too */
+ afterPane: ShallowRef
/** Etag of the newer file as loaded */
etag?: string
}
@@ -70,7 +69,7 @@ export function useSharedComparison(base: IFile, file: IFile) {
comparison = undefined
}
if (!comparison) {
- comparison = { users: 0, loads: 0, session: shallowRef(), texts: shallowRef(), path: ref(), error: ref(false), unsaved: ref(false) }
+ comparison = { users: 0, loads: 0, session: shallowRef(), texts: shallowRef(), path: ref(), error: ref(false), unsaved: ref(false), summaryHeight: ref(0), afterPane: shallowRef() }
comparisons.set(key, comparison)
load(key, comparison, base, file)
}
@@ -105,7 +104,7 @@ export function useSharedComparison(base: IFile, file: IFile) {
load(key, shared, base, file)
}
- return { session: shared.session, texts: shared.texts, path: shared.path, error: shared.error, unsaved: shared.unsaved, reload }
+ return { session: shared.session, texts: shared.texts, path: shared.path, error: shared.error, unsaved: shared.unsaved, summaryHeight: shared.summaryHeight, afterPane: shared.afterPane, reload }
}
/**
@@ -134,16 +133,19 @@ async function load(key: string, comparison: SharedComparison, base: IFile, file
return
}
// Files are served without caching rules, so browsers may reuse an old copy
- const options = { responseType: 'text', headers: { 'Cache-Control': 'no-cache' }, timeout: 120_000 } as const
+ const options = { responseType: 'arraybuffer', headers: { 'Cache-Control': 'no-cache' }, timeout: 120_000 } as const
const [before, after, path] = await Promise.all([
- axios.get(base.encodedSource, options),
- axios.get(file.encodedSource, options),
+ axios.get(base.encodedSource, options),
+ axios.get(file.encodedSource, options),
documentPath(base, file),
])
if (stale()) {
return
}
- const texts = { before: loaded(before), after: loaded(after) }
+ const texts = {
+ before: loadText(before.data, before.headers),
+ after: loadText(after.data, after.headers),
+ }
comparison.path.value = path
comparison.texts.value = texts
comparison.etag = etagOf(after.headers.etag)
@@ -157,11 +159,6 @@ async function load(key: string, comparison: SharedComparison, base: IFile, file
}
}
-function loaded(response: { data: string, headers: Record }): LoadedText {
- const modified = Date.parse(String(response.headers['last-modified'] ?? ''))
- return { text: response.data, modified: Number.isNaN(modified) ? undefined : modified / 1000 }
-}
-
/**
* Path of the file compared, as the current file has it: the node of an old
* version has only its revision for a path.
diff --git a/src/comparison/versions.ts b/src/comparison/versions.ts
index 1e31c02d0f2..20eaf496e7a 100644
--- a/src/comparison/versions.ts
+++ b/src/comparison/versions.ts
@@ -17,6 +17,8 @@ export interface FileVersions {
versions: Ref
/** Path of the file in the user's files */
path: Ref
+ /** Whether this Nextcloud keeps versions at all */
+ available: Ref
failed: Ref
/** Fetch them, unless they are here; resolves once they are, or the fetch failed */
load: () => Promise
@@ -67,6 +69,7 @@ export function invalidateFileVersions(fileId: number) {
function createFileVersions(fileId: number): CachedVersions {
const versions = ref()
const path = ref()
+ const available = ref(true)
const failed = ref(false)
/** Counts invalidations: a fetch started before one is stale */
let generation = 0
@@ -89,6 +92,7 @@ function createFileVersions(fileId: number): CachedVersions {
if (started === generation) {
versions.value = data.ocs.data.versions
path.value = data.ocs.data.path
+ available.value = data.ocs.data.versionsAvailable
}
} catch (exception) {
if (started === generation) {
@@ -114,5 +118,5 @@ function createFileVersions(fileId: number): CachedVersions {
return load()
}
- return { versions, path, failed, load, refresh, invalidate }
+ return { versions, path, available, failed, load, refresh, invalidate }
}
diff --git a/src/components/VersionSummary.vue b/src/components/VersionSummary.vue
new file mode 100644
index 00000000000..de2ee5f1904
--- /dev/null
+++ b/src/components/VersionSummary.vue
@@ -0,0 +1,467 @@
+
+
+
+
+
+ {{ announcement }}
+
+
+
+
+
+
+
+ {{ view.kind === 'done' ? t('text', 'Summary of changes') : t('text', 'Summarizing changes…') }}
+
+ {{ firstLine }}
+ {{ queueText }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ range }} · {{ t('text', 'AI-generated, may omit or misstate changes') }}
+
+
+
+
+
+ {{ line }}
+
+
+
+
+ {{ group.label }}
+
+
+ {{ paragraph }}
+
+
+
+
+
+
+
+
+
+
+
+
{{ note.text }}
+
+ {{ note.next.label }}
+
+
+
+
+
+
+
+
+
+
{{ t('text', 'No answer from the server. Trying again…') }}
+
+ {{ t('text', 'Retry now') }}
+
+
+
+
+
+
+
+
+
diff --git a/src/components/VersionSummaryStart.vue b/src/components/VersionSummaryStart.vue
new file mode 100644
index 00000000000..d1eecf0f9de
--- /dev/null
+++ b/src/components/VersionSummaryStart.vue
@@ -0,0 +1,101 @@
+
+
+
+
+
+
+ {{ start.text }}
+
+
+
+
+
+
+
diff --git a/src/components/ViewerVersionComparison.vue b/src/components/ViewerVersionComparison.vue
index 875c9fa6f84..d50f2bfdbc7 100644
--- a/src/components/ViewerVersionComparison.vue
+++ b/src/components/ViewerVersionComparison.vue
@@ -5,9 +5,11 @@
+
+
+
+
+
-
+
-
+
@@ -92,10 +107,7 @@
-
+
@@ -107,8 +119,10 @@
import type { IFile } from '@nextcloud/files'
import type { ComparisonSide } from '../comparison/decorations.ts'
+import { loadState } from '@nextcloud/initial-state'
import { t } from '@nextcloud/l10n'
-import { computed, ref, watch } from 'vue'
+import { useResizeObserver } from '@vueuse/core'
+import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, ref, useTemplateRef, watch } from 'vue'
import NcButton from '@nextcloud/vue/components/NcButton'
import NcEmptyContent from '@nextcloud/vue/components/NcEmptyContent'
import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon'
@@ -120,7 +134,7 @@ import ComparisonVersionPicker from './ComparisonVersionPicker.vue'
import MarkdownSourceFallback from './MarkdownSourceFallback.vue'
import { takeAnnouncement } from '../comparison/focus.ts'
import { useSharedComparison } from '../comparison/sharedComparison.ts'
-import { comparedPair } from '../comparison/versionEnds.ts'
+import { comparedPair, isCurrent } from '../comparison/versionEnds.ts'
import { invalidateFileVersions } from '../comparison/versions.ts'
import { useComparisonAttachments } from '../composables/useComparisonAttachments.ts'
@@ -138,21 +152,87 @@ const emit = defineEmits<{
select: [id: string]
}>()
-const { session, texts, path, error, unsaved, reload } = useSharedComparison(props.base, props.file)
+// Whether summaries are on for this user, known without a request
+const summariesAvailable = loadState('text', 'version_summaries', false)
+
+const { session, texts, path, error, unsaved, summaryHeight, afterPane, reload } = useSharedComparison(props.base, props.file)
useComparisonAttachments({ fileId: props.file.fileid, filePath: path })
// Two versions of one file, whose ends can be changed: nothing where versions cannot be listed
const pair = computed(() => comparedPair(props.base, props.file, texts.value))
+// Loaded only for a comparison that can show a summary
+const VersionSummary = defineAsyncComponent(() => import('./VersionSummary.vue'))
+const VersionSummaryStart = defineAsyncComponent(() => import('./VersionSummaryStart.vue'))
+const summaryArea = useTemplateRef('summaryArea')
+const root = useTemplateRef('root')
+
+// Side by side, the summary spans both documents: from the older one's pane
+// to the far edge of the newer one's, whichever side each is on
+const summarySpan = ref()
+if (props.part === 'before') {
+ useResizeObserver(summaryArea, ([entry]) => {
+ summaryHeight.value = entry?.borderBoxSize[0]?.blockSize ?? 0
+ })
+ useResizeObserver([root, afterPane], () => {
+ const own = root.value?.getBoundingClientRect()
+ const other = afterPane.value?.getBoundingClientRect()
+ summarySpan.value = own && other ? Math.max(own.right, other.right) - Math.min(own.left, other.left) : undefined
+ })
+ onBeforeUnmount(() => {
+ summaryHeight.value = 0
+ })
+}
+if (props.part === 'after') {
+ watch(root, (element) => {
+ afterPane.value = element ?? undefined
+ }, { immediate: true })
+ onBeforeUnmount(() => {
+ if (afterPane.value === root.value) {
+ afterPane.value = undefined
+ }
+ })
+}
+
+/**
+ * Give the keyboard to the summary once the button it was on goes away.
+ *
+ * @param hadFocus Whether the keyboard was on the button.
+ */
+function focusSummary(hadFocus: boolean) {
+ if (hadFocus) {
+ nextTick(() => summaryArea.value?.querySelector('[data-text-version-summary]')?.focus())
+ }
+}
+
/** Load both files again, and their versions, after the file changed */
function reloadComparison() {
if (pair.value) {
invalidateFileVersions(pair.value.fileId)
}
+ // The button goes away while loading: the keyboard comes back to the comparison
+ if (root.value?.contains(document.activeElement)) {
+ const stop = watch([session, error], ([loaded, failed]) => {
+ if (loaded || failed) {
+ stop()
+ nextTick(() => root.value?.focus())
+ }
+ })
+ }
reload()
}
+const summaryTexts = computed(() => {
+ // Nothing is newer than the current file, which Collectives may pass as the older end after a restore
+ if (!summariesAvailable || !pair.value || isCurrent(pair.value.from) || !texts.value || !session.value) {
+ return undefined
+ }
+ const { before, after } = texts.value
+ const looksSame = !session.value.failed && session.value.changeCount === 0
+ return { fromHash: before.sha256, toHash: after.sha256, utf8: before.utf8 && after.utf8, looksSame }
+})
+
// Said once the new pair is on screen, after a picker changed it. Set a
// moment after the live region appears, or screen readers miss it.
const announcement = ref('')
@@ -203,7 +283,7 @@ function selectChange(id: string) {
min-block-size: calc(var(--default-clickable-area) + 2 * var(--default-grid-baseline));
}
- // Side by side, on one line
+ // Side by side, on one line, so both headers keep one height: the summary's note gives way first
&--before .text-comparison__header,
&--after .text-comparison__header {
flex-wrap: nowrap;
@@ -228,5 +308,24 @@ function selectChange(id: string) {
align-items: center;
gap: calc(2 * var(--default-grid-baseline));
}
+
+ .text-comparison__summary-room {
+ flex-shrink: 0;
+ }
+
+ .text-comparison__end {
+ margin-inline-start: auto;
+ }
+
+ // The summary reaches over the newer document's pane, and is drawn above it
+ &--spanning {
+ position: relative;
+ z-index: 1;
+ overflow: visible clip;
+
+ .text-comparison__summary {
+ flex-shrink: 0;
+ }
+ }
}
diff --git a/src/init.js b/src/init.js
index 8bc32b638e0..d17ecad0ac1 100644
--- a/src/init.js
+++ b/src/init.js
@@ -7,6 +7,7 @@ import { registerFileListHeader } from '@nextcloud/files'
import { registerDavProperty } from '@nextcloud/files/dav'
import { loadState } from '@nextcloud/initial-state'
import { addMenuRichWorkspace, FilesWorkspaceHeader } from './helpers/files.js'
+import { registerSummarizeRecentChanges } from './versionSummary/sidebarEntry.ts'
import 'vite/modulepreload-polyfill'
@@ -19,3 +20,5 @@ if (workspaceAvailable) {
addMenuRichWorkspace()
registerFileListHeader(FilesWorkspaceHeader)
}
+
+registerSummarizeRecentChanges()
diff --git a/src/tests/comparison/decode.spec.ts b/src/tests/comparison/decode.spec.ts
new file mode 100644
index 00000000000..90f2f88fed3
--- /dev/null
+++ b/src/tests/comparison/decode.spec.ts
@@ -0,0 +1,73 @@
+/**
+ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import { digest } from 'lib0/hash/sha256'
+import { createHash } from 'node:crypto'
+import { describe, expect, it, vi } from 'vitest'
+import { decodeText, loadText } from '../../comparison/decode.ts'
+
+vi.mock('lib0/hash/sha256', async (importOriginal) => {
+ const original = await importOriginal<{ digest: (data: Uint8Array) => Uint8Array }>()
+ return { ...original, digest: vi.fn(original.digest) }
+})
+
+const bytes = (...values: number[]) => new Uint8Array(values)
+const utf8 = (text: string) => new TextEncoder().encode(text)
+
+describe('decodeText', () => {
+ // What a browser makes of a `responseType: 'text'` response, which the
+ // comparison used before it kept the bytes
+ it('reads UTF-8', () => {
+ expect(decodeText(utf8('# Café ✓'), 'text/markdown;charset=UTF-8')).toBe('# Café ✓')
+ expect(decodeText(utf8('# Café'))).toBe('# Café')
+ })
+
+ it('drops a UTF-8 byte order mark', () => {
+ expect(decodeText(bytes(0xEF, 0xBB, 0xBF, ...utf8('# A')), 'text/markdown;charset=UTF-8')).toBe('# A')
+ })
+
+ it('lets a UTF-16 byte order mark win over the charset', () => {
+ expect(decodeText(bytes(0xFF, 0xFE, 0x23, 0x00, 0x20, 0x00, 0x41, 0x00), 'text/markdown;charset=UTF-8')).toBe('# A')
+ expect(decodeText(bytes(0xFE, 0xFF, 0x00, 0x23, 0x00, 0x20, 0x00, 0x41))).toBe('# A')
+ })
+
+ it('replaces what is not UTF-8', () => {
+ expect(decodeText(bytes(0x23, 0x20, 0x63, 0x61, 0x66, 0xE9), 'text/markdown;charset=UTF-8')).toBe('# caf�')
+ })
+
+ it('follows another charset, and falls back on an unknown one', () => {
+ expect(decodeText(bytes(0x63, 0x61, 0x66, 0xE9), 'text/plain; charset=windows-1252')).toBe('café')
+ expect(decodeText(utf8('é'), 'text/plain; charset=nonsense')).toBe('é')
+ })
+})
+
+describe('loadText', () => {
+ it('fingerprints the bytes as the server does', () => {
+ const content = utf8('# Plan\n\nThe pilot runs 2 weeks.\n')
+ const loaded = loadText(content.buffer, { 'content-type': 'text/markdown;charset=UTF-8', 'last-modified': 'Mon, 07 Aug 2023 15:01:41 GMT' })
+
+ expect(loaded.sha256).toBe(createHash('sha256').update(content).digest('hex'))
+ expect(loaded.text).toBe('# Plan\n\nThe pilot runs 2 weeks.\n')
+ expect(loaded.utf8).toBe(true)
+ expect(loaded.modified).toBe(1691420501)
+ })
+
+ it('knows when the bytes are not UTF-8', () => {
+ expect(loadText(bytes(0x63, 0x61, 0x66, 0xE9).buffer).utf8).toBe(false)
+ expect(loadText(bytes(0xFF, 0xFE, 0x23, 0x00).buffer).utf8).toBe(false)
+ expect(loadText(bytes().buffer).modified).toBeUndefined()
+ })
+
+ it('fingerprints a file only for a summary that asks', () => {
+ vi.mocked(digest).mockClear()
+ const loaded = loadText(utf8('# Plan').buffer as ArrayBuffer)
+ expect(loaded.text).toBe('# Plan')
+ expect(digest).not.toHaveBeenCalled()
+
+ expect(loaded.sha256).toBe(createHash('sha256').update('# Plan').digest('hex'))
+ expect(loaded.sha256).toHaveLength(64)
+ expect(digest).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/tests/comparison/sharedComparison.spec.ts b/src/tests/comparison/sharedComparison.spec.ts
index fb3c816b9e3..d7d9c4756b0 100644
--- a/src/tests/comparison/sharedComparison.spec.ts
+++ b/src/tests/comparison/sharedComparison.spec.ts
@@ -27,7 +27,7 @@ const file = { source: 'https://cloud.example/f/plan.md', encodedSource: 'https:
function deferred() {
let settle!: (text: string) => void
const promise = new Promise((resolve) => {
- settle = (text) => resolve({ data: text, headers: {} })
+ settle = (text) => resolve({ data: new TextEncoder().encode(text).buffer, headers: {} })
})
return { promise, settle }
}
@@ -47,19 +47,19 @@ afterEach(() => {
describe('useSharedComparison', () => {
it('shows only the latest of overlapping reloads', async () => {
const get = vi.spyOn(axios, 'get')
- get.mockResolvedValueOnce({ data: 'old', headers: {} })
- get.mockResolvedValueOnce({ data: 'first', headers: {} })
+ get.mockResolvedValueOnce({ data: new TextEncoder().encode('old').buffer, headers: {} })
+ get.mockResolvedValueOnce({ data: new TextEncoder().encode('first').buffer, headers: {} })
const scope = effectScope()
const comparison = scope.run(() => useSharedComparison(base, file))!
await settle()
const late = deferred()
get.mockReturnValueOnce(late.promise as never)
- get.mockReturnValueOnce(Promise.resolve({ data: 'new', headers: {} }) as never)
+ get.mockReturnValueOnce(Promise.resolve({ data: new TextEncoder().encode('new').buffer, headers: {} }) as never)
comparison.reload()
await settle()
- get.mockResolvedValueOnce({ data: 'old', headers: {} })
- get.mockResolvedValueOnce({ data: 'newest', headers: {} })
+ get.mockResolvedValueOnce({ data: new TextEncoder().encode('old').buffer, headers: {} })
+ get.mockResolvedValueOnce({ data: new TextEncoder().encode('newest').buffer, headers: {} })
comparison.reload()
await settle()
late.settle('stale')
@@ -80,7 +80,7 @@ describe('useSharedComparison', () => {
}
vi.spyOn(axios, 'get').mockImplementation(async (url: string) => url.includes('/ocs/v2.php/apps/text/versions/7')
? { data: { ocs: { data: { path: '/Notes/plan.md', versions: [], versionsAvailable: true } } } }
- : { data: url.endsWith('/100') ? 'older' : 'newer', headers: {} })
+ : { data: new TextEncoder().encode(url.endsWith('/100') ? 'older' : 'newer').buffer, headers: {} })
const scope = effectScope()
const comparison = scope.run(() => useSharedComparison(version(100), version(200)))!
await settle()
@@ -91,7 +91,7 @@ describe('useSharedComparison', () => {
})
it('takes the folder from the current file without asking for the versions', async () => {
- const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'text', headers: {} })
+ const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: new TextEncoder().encode('text').buffer, headers: {} })
const source = 'https://cloud.example/remote.php/dav/files/alice/Notes/plan.md'
const current = { source, encodedSource: source, path: '/Notes/plan.md', fileid: 7 } as unknown as IFile
const scope = effectScope()
@@ -142,7 +142,7 @@ describe('useSharedComparison', () => {
})
it('loads the newer file once the editor it replaces has saved it', async () => {
- const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'saved', headers: {} })
+ const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: new TextEncoder().encode('saved').buffer, headers: {} })
const edited = { ...file, source: 'https://cloud.example/f/edited.md', encodedSource: 'https://cloud.example/f/edited.md', fileid: 7 } as unknown as IFile
let saved!: () => void
const scope = effectScope()
@@ -210,7 +210,7 @@ describe('useSharedComparison', () => {
})
it('loads the file as the server has it once it showed that the closing save failed', async () => {
- const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'server', headers: {} })
+ const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: new TextEncoder().encode('server').buffer, headers: {} })
const edited = { ...file, source: 'https://cloud.example/f/again.md', encodedSource: 'https://cloud.example/f/again.md', fileid: 11 } as unknown as IFile
trackClosingSave(11, Promise.resolve(false))
const scope = effectScope()
@@ -237,7 +237,7 @@ describe('useSharedComparison', () => {
trackClosingSave(12, new Promise(() => {}))
vi.spyOn(axios, 'get').mockImplementation(async (url: string) => url.includes('/ocs/')
? { data: { ocs: { data: { path: '/plan.md', versions: [], versionsAvailable: true } } } }
- : { data: 'old', headers: {} })
+ : { data: new TextEncoder().encode('old').buffer, headers: {} })
const scope = effectScope()
const comparison = scope.run(() => useSharedComparison(version(100), version(200)))!
await settle()
diff --git a/src/tests/components/VersionSummary.spec.ts b/src/tests/components/VersionSummary.spec.ts
new file mode 100644
index 00000000000..cf11cdc69c3
--- /dev/null
+++ b/src/tests/components/VersionSummary.spec.ts
@@ -0,0 +1,113 @@
+/**
+ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import type { SummaryView } from '../../versionSummary/states.ts'
+
+import { mount } from '@vue/test-utils'
+import { describe, expect, it, vi } from 'vitest'
+import { ref, shallowRef } from 'vue'
+import VersionSummary from '../../components/VersionSummary.vue'
+
+const view = shallowRef({ kind: 'loading' })
+const ends = shallowRef({
+ from: { id: '1000', mtime: 1000, author: null as { id: string, displayName: string } | null, label: '' },
+ to: { id: 'current', mtime: 2000, author: null as { id: string, displayName: string } | null, label: '' },
+})
+vi.mock('../../versionSummary/summaries.ts', () => ({
+ useVersionSummary: () => ({
+ view,
+ ends,
+ fileName: ref('plan.md'),
+ connectionLost: ref(false),
+ collapsed: ref(false),
+ userStarted: ref(true),
+ generate: vi.fn(),
+ retryNow: vi.fn(),
+ }),
+}))
+
+const props = {
+ ends: { fileId: 7, from: '1000', to: 'current' },
+ texts: { fromHash: 'a'.repeat(64), toHash: 'b'.repeat(64), utf8: true, looksSame: false },
+ reload: vi.fn(),
+}
+
+describe('VersionSummary', () => {
+ it('lets the keyboard reach and scroll a long summary', () => {
+ view.value = { kind: 'done', summary: 'The pilot runs 3 weeks.' }
+ const wrapper = mount(VersionSummary, { props })
+
+ expect(wrapper.find('[data-text-version-summary-text]').attributes('tabindex')).toBe('0')
+ wrapper.unmount()
+ })
+
+ it('says when starts can be asked for again after many in a short time, without a button that fails meanwhile', () => {
+ view.value = { kind: 'rateLimited', retryAfter: 1_000_120 }
+ const wrapper = mount(VersionSummary, { props })
+
+ const note = wrapper.find('.text-version-summary__note')
+ expect(note.text()).toContain('You asked for several summaries in a short time. Try again after')
+ expect(note.find('button').exists()).toBe(false)
+ wrapper.unmount()
+ })
+
+ it('reloads the comparison from the note that says the file changed', async () => {
+ view.value = { kind: 'changed', whileRunning: false }
+ const reload = vi.fn()
+ const wrapper = mount(VersionSummary, { props: { ...props, reload } })
+
+ await wrapper.find('.text-version-summary__note button').trigger('click')
+
+ expect(reload).toHaveBeenCalledOnce()
+ wrapper.unmount()
+ })
+
+ it('names the versions as their labels and authors are written', () => {
+ ends.value = {
+ from: { id: '1000', mtime: 1000, author: { id: 'ann', displayName: 'Ann & Bob ' }, label: '' },
+ to: { id: 'current', mtime: 2000, author: null, label: 'Draft & final' },
+ }
+ view.value = { kind: 'done', summary: 'The pilot runs 3 weeks.' }
+ const wrapper = mount(VersionSummary, { props })
+
+ const notice = wrapper.find('.text-version-summary__notice').text()
+ expect(notice).toContain('Ann & Bob ')
+ expect(notice).toContain('"Draft & final"')
+ wrapper.unmount()
+ })
+
+ it('announces a summary under way once, not every move in the queue', async () => {
+ view.value = { kind: 'queued', position: 3 }
+ const wrapper = mount(VersionSummary, { props })
+ const status = () => wrapper.find('[role="status"]').text()
+ const first = status()
+ expect(wrapper.text()).toContain('Position 3 in the queue')
+
+ view.value = { kind: 'queued', position: 2 }
+ await wrapper.vm.$nextTick()
+
+ expect(wrapper.text()).toContain('Position 2 in the queue')
+ expect(status()).toBe(first)
+ expect(first).not.toContain('Position')
+ wrapper.unmount()
+ })
+
+ it('fades the end of a summary that scrolls, until it is read to the end', async () => {
+ view.value = { kind: 'done', summary: 'The pilot runs 3 weeks.\n\nPlan\n- One\n- Two' }
+ const wrapper = mount(VersionSummary, { props })
+ const text = wrapper.find('[data-text-version-summary-text]')
+ const box = text.element as HTMLElement
+ Object.defineProperties(box, { scrollHeight: { value: 500, configurable: true }, clientHeight: { value: 200, configurable: true } })
+
+ box.scrollTop = 0
+ await text.trigger('scroll')
+ expect(text.classes()).toContain('text-version-summary__text--more')
+
+ box.scrollTop = 300
+ await text.trigger('scroll')
+ expect(text.classes()).not.toContain('text-version-summary__text--more')
+ wrapper.unmount()
+ })
+})
diff --git a/src/tests/components/VersionSummaryStart.spec.ts b/src/tests/components/VersionSummaryStart.spec.ts
new file mode 100644
index 00000000000..1258a8a6f87
--- /dev/null
+++ b/src/tests/components/VersionSummaryStart.spec.ts
@@ -0,0 +1,53 @@
+/**
+ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import type { SummaryView } from '../../versionSummary/states.ts'
+
+import { flushPromises, mount } from '@vue/test-utils'
+import { describe, expect, it, vi } from 'vitest'
+import { shallowRef } from 'vue'
+import VersionSummaryStart from '../../components/VersionSummaryStart.vue'
+
+const view = shallowRef({ kind: 'ready' })
+const generate = vi.fn()
+vi.mock('../../versionSummary/summaries.ts', () => ({ useVersionSummary: () => ({ view, generate }) }))
+
+const props = {
+ ends: { fileId: 7, from: '1000', to: 'current' },
+ texts: { fromHash: 'a'.repeat(64), toHash: 'b'.repeat(64), utf8: true, looksSame: false },
+}
+
+describe('VersionSummaryStart', () => {
+ it('tells screen readers what the button sends, or why it is off', async () => {
+ view.value = { kind: 'ready' }
+ const wrapper = mount(VersionSummaryStart, { props, attachTo: document.body })
+ await flushPromises()
+
+ const button = wrapper.find('button')
+ const note = wrapper.find('.text-version-summary-start__note')
+ expect(note.text()).toBe('Both complete versions are sent to the AI provider of this Nextcloud.')
+ expect(button.attributes('aria-describedby')).toBe(note.attributes('id'))
+
+ view.value = { kind: 'unavailable', reason: 'user_cap', retryAfter: null }
+ await flushPromises()
+ expect(wrapper.find('button').attributes('disabled')).toBeDefined()
+ expect(wrapper.find('button').attributes('aria-describedby')).toBe(wrapper.find('.text-version-summary-start__note').attributes('id'))
+ wrapper.unmount()
+ })
+
+ it('starts a summary and says whether the keyboard was on the button', async () => {
+ view.value = { kind: 'ready' }
+ const wrapper = mount(VersionSummaryStart, { props, attachTo: document.body })
+ await flushPromises()
+ const button = wrapper.find('button')
+ ;(button.element as HTMLElement).focus()
+
+ await button.trigger('click')
+
+ expect(generate).toHaveBeenCalledOnce()
+ expect(wrapper.emitted('started')).toEqual([[true]])
+ wrapper.unmount()
+ })
+})
diff --git a/src/tests/components/ViewerVersionComparison.spec.ts b/src/tests/components/ViewerVersionComparison.spec.ts
index 30d75523dd0..30037228116 100644
--- a/src/tests/components/ViewerVersionComparison.spec.ts
+++ b/src/tests/components/ViewerVersionComparison.spec.ts
@@ -15,6 +15,8 @@ import { logger } from '../../helpers/logger.ts'
const viewer = vi.hoisted(() => new EventTarget())
vi.mock('@nextcloud/viewer', () => ({ getViewer: () => viewer }))
+const summaries = vi.hoisted(() => ({ on: false }))
+vi.mock('@nextcloud/initial-state', () => ({ loadState: (app: string, key: string, fallback: unknown) => key === 'version_summaries' ? summaries.on : fallback }))
const baseSource = 'https://cloud.example/remote.php/dav/versions/alice/versions/7/1691420501'
const fileSource = 'https://cloud.example/remote.php/dav/files/alice/notes.md'
@@ -23,8 +25,9 @@ const contents: Record = {
[fileSource]: '# New title\n\n**Plain** text',
}
+// The bytes of a file, as DAV serves Markdown
function response(text: string) {
- return { data: text, headers: {} }
+ return { data: new TextEncoder().encode(text).buffer, headers: { 'content-type': 'text/markdown;charset=UTF-8' } }
}
/**
@@ -66,6 +69,9 @@ beforeEach(() => {
afterEach(async () => {
viewer.dispatchEvent(new CustomEvent('close'))
vi.restoreAllMocks()
+ // Also when a test failed before undoing them
+ vi.unstubAllGlobals()
+ summaries.on = false
// Let unmounted parts release their comparison
await new Promise((resolve) => setTimeout(resolve))
})
@@ -100,6 +106,40 @@ describe('ViewerVersionComparison', () => {
after.unmount()
})
+ it('offers a summary on the row of the navigation, and spans it over both documents', async () => {
+ summaries.on = true
+ // Every pane is 500 pixels wide, side by side with a gap of 8
+ vi.stubGlobal('ResizeObserver', class {
+ constructor(private callback: ResizeObserverCallback) {}
+ observe(target: Element) {
+ this.callback([{ target, borderBoxSize: [{ blockSize: 120, inlineSize: 500 }] } as unknown as ResizeObserverEntry], this as unknown as ResizeObserver)
+ }
+
+ unobserve() {}
+ disconnect() {}
+ })
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function(this: HTMLElement) {
+ const left = this.classList.contains('text-version-comparison--after') ? 508 : 0
+ return { left, right: left + 500, x: left, y: 0, top: 0, bottom: 0, width: 500, height: 0 } as DOMRect
+ })
+ const end = { mtime: 1000, size: 10, label: '', author: null }
+ get.mockImplementation(async (url: string) => url.includes('/version-summaries/')
+ ? { data: { ocs: { data: { state: 'absent', summary: null, error: null, queuePosition: null, progress: null, ends: { from: { ...end, id: '1691420501' }, to: { ...end, id: 'current' } }, fileName: 'notes.md', generation: { available: true, reason: null, retryAfter: null } } } } }
+ : response(contents[url]!))
+
+ const before = mountPart('before')
+ const after = mountPart('after')
+ await loaded()
+
+ await vi.waitFor(() => expect(before.find('.text-comparison__header').text()).toContain('Summarize changes'))
+ expect(after.find('.text-comparison__header').text()).toContain('Change 1 of 2')
+ expect(before.classes()).toContain('text-version-comparison--spanning')
+ expect(before.find('.text-comparison__summary').attributes('style')).toContain('inline-size: 1008px')
+
+ before.unmount()
+ after.unmount()
+ })
+
it('lists the changes with the filter, and makes a picked one current', async () => {
const changes = mountPart('changes')
await loaded()
@@ -192,6 +232,34 @@ describe('ViewerVersionComparison', () => {
after.unmount()
})
+ it('gives the keyboard back to the comparison after trying again', async () => {
+ vi.spyOn(logger, 'error').mockImplementation(() => {})
+ get.mockRejectedValue(new Error('gone'))
+ const after = mountPart('after')
+ await loaded()
+ const tryAgain = after.findAll('button').find((button) => button.text() === 'Try again')!
+ ;(tryAgain.element as HTMLElement).focus()
+
+ get.mockImplementation(async (url: string) => response(contents[url]!))
+ await tryAgain.trigger('click')
+ await loaded()
+
+ expect(after.element.contains(document.activeElement)).toBe(true)
+ after.unmount()
+ })
+
+ it('offers no summary of a pair whose older end is the current file', async () => {
+ summaries.on = true
+ // Collectives orders by time, and a restore sets the current file back to an older one's
+ const changes = mount(ViewerVersionComparison, { props: { base: file, file: base, part: 'changes' }, attachTo: document.body })
+ await loaded()
+ await new Promise((resolve) => setTimeout(resolve, 20))
+
+ expect(changes.text()).not.toContain('Summarize changes')
+ expect(get.mock.calls.some(([url]) => String(url).includes('/version-summaries/'))).toBe(false)
+ changes.unmount()
+ })
+
it('names the versions in the complete source too', async () => {
get.mockImplementation(async (url: string) => response(contents[url] + 'x'.repeat(600_000)))
const before = mountPart('before')
diff --git a/src/tests/versionSummary/copy.spec.ts b/src/tests/versionSummary/copy.spec.ts
new file mode 100644
index 00000000000..14c91d4f091
--- /dev/null
+++ b/src/tests/versionSummary/copy.spec.ts
@@ -0,0 +1,38 @@
+/**
+ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { copyText } from '../../versionSummary/copy.ts'
+
+describe('copyText', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('says when the browser refused to copy the old way', async () => {
+ vi.stubGlobal('navigator', { clipboard: undefined })
+ document.execCommand = vi.fn(() => false)
+
+ expect(await copyText('summary')).toBe(false)
+ expect(document.querySelector('textarea')).toBeNull()
+ vi.unstubAllGlobals()
+ })
+
+ it('selects the text the old way inside the element given, where a dialog keeps the focus', async () => {
+ vi.stubGlobal('navigator', { clipboard: undefined })
+ const dialog = document.createElement('div')
+ document.body.appendChild(dialog)
+ let parent: Node | null = null
+ document.execCommand = vi.fn(() => {
+ parent = document.querySelector('textarea')?.parentNode ?? null
+ return true
+ })
+
+ expect(await copyText('summary', dialog)).toBe(true)
+ expect(parent).toBe(dialog)
+ dialog.remove()
+ vi.unstubAllGlobals()
+ })
+})
diff --git a/src/tests/versionSummary/format.spec.ts b/src/tests/versionSummary/format.spec.ts
new file mode 100644
index 00000000000..2b77f226da2
--- /dev/null
+++ b/src/tests/versionSummary/format.spec.ts
@@ -0,0 +1,56 @@
+/**
+ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import { describe, expect, it } from 'vitest'
+import { parseSummary } from '../../versionSummary/format.ts'
+
+describe('parseSummary', () => {
+ it('splits the gist from the changes grouped under their names', () => {
+ const summary = 'The launch moves two weeks later, from 12 to 26 March.\n\nTimeline\n- Build ends 12 March instead of 26 February.\n\nBudget:\n- 48,000 EUR to 55,000 EUR.\n- 4,000 EUR for the agency.'
+
+ expect(parseSummary(summary)).toEqual({
+ gist: ['The launch moves two weeks later, from 12 to 26 March.'],
+ groups: [
+ { label: 'Timeline', paragraphs: [], items: ['Build ends 12 March instead of 26 February.'] },
+ { label: 'Budget', paragraphs: [], items: ['48,000 EUR to 55,000 EUR.', '4,000 EUR for the agency.'] },
+ ],
+ })
+ })
+
+ it('keeps a gist alone, and the changes right under it without a name', () => {
+ expect(parseSummary('Only spelling fixes.')).toEqual({ gist: ['Only spelling fixes.'], groups: [] })
+ expect(parseSummary('Locks no longer expire.\n- Locks expired after 30 minutes; now an admin removes them.').groups)
+ .toEqual([{ paragraphs: [], items: ['Locks expired after 30 minutes; now an admin removes them.'] }])
+ })
+
+ it('shows a list without a gist as one group', () => {
+ expect(parseSummary('- The pilot runs 3 weeks.\n* Lunch is at 12:30.')).toEqual({
+ gist: [],
+ groups: [{ paragraphs: [], items: ['The pilot runs 3 weeks.', 'Lunch is at 12:30.'] }],
+ })
+ })
+
+ it('drops Markdown the answer should not have, and keeps a closing line', () => {
+ expect(parseSummary('**Rent goes up.**\n\n## Rent\n- From **850 EUR** to 920 EUR.\nAlso: spelling fixes.')).toEqual({
+ gist: ['Rent goes up.'],
+ groups: [
+ { label: 'Rent', paragraphs: [], items: ['From 850 EUR to 920 EUR.'] },
+ { paragraphs: ['Also: spelling fixes.'], items: [] },
+ ],
+ })
+ })
+
+ it('keeps a second opening sentence in the gist when items follow it', () => {
+ expect(parseSummary('The budget grows by 10%.\nThe deadline moves to May.\n- Budget: 100 to 110\n- Deadline: April to May')).toEqual({
+ gist: ['The budget grows by 10%.', 'The deadline moves to May.'],
+ groups: [{ paragraphs: [], items: ['Budget: 100 to 110', 'Deadline: April to May'] }],
+ })
+ })
+
+ it('keeps values that only look like emphasis', () => {
+ expect(parseSummary('- Limit changed from 2**10 to 2**12.\n- __init__.py moved.').groups[0]!.items)
+ .toEqual(['Limit changed from 2**10 to 2**12.', '__init__.py moved.'])
+ })
+})
diff --git a/src/tests/versionSummary/sidebarEntry.spec.ts b/src/tests/versionSummary/sidebarEntry.spec.ts
new file mode 100644
index 00000000000..fcc40849d34
--- /dev/null
+++ b/src/tests/versionSummary/sidebarEntry.spec.ts
@@ -0,0 +1,109 @@
+/**
+ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import type { INode } from '@nextcloud/files'
+import type { VersionEntry } from '../../comparison/versionEnds.ts'
+
+import axios from '@nextcloud/axios'
+import { loadState } from '@nextcloud/initial-state'
+import { isPublicShare } from '@nextcloud/sharing/public'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { useFileVersions } from '../../comparison/versions.ts'
+import { canSummarize } from '../../versionSummary/sidebarEntry.ts'
+import { recentChangesBase, summarizeRecentChanges } from '../../versionSummary/summarizeRecentChanges.ts'
+
+vi.mock('@nextcloud/files', async () => await vi.importActual('@nextcloud/files'))
+const viewer = vi.hoisted(() => Object.assign(new EventTarget(), { compare: vi.fn(async () => {}) }))
+vi.mock('@nextcloud/viewer', () => ({ getViewer: () => viewer }))
+vi.mock('@nextcloud/auth', async (importOriginal) => ({ ...await importOriginal