From 64dc26f4edd567af12903d676f04502739fa6735 Mon Sep 17 00:00:00 2001 From: Hoang Pham Date: Wed, 4 Nov 2026 15:01:02 +0700 Subject: [PATCH] feat(versions): admin setting for summaries of changes Administration > Artificial intelligence gets "Summaries of changes in Text": a switch, a notice of what is sent where and kept how long, the chat provider that receives the texts (with a warning when there is none), the hourly limits and how many summaries started in the last hour. Turning it off removes stored summaries and pending tasks, and says when some are left for the cleanup job to retry. Part of #8904 Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Hoang Pham --- appinfo/info.xml | 3 + appinfo/routes.php | 2 + composer/composer/autoload_classmap.php | 1 + composer/composer/autoload_static.php | 1 + lib/Controller/VersionSummaryController.php | 31 +++ lib/Service/VersionSummaryService.php | 4 + lib/Settings/VersionSummariesSettings.php | 68 ++++++ src/settings.ts | 9 + .../views/VersionSummariesSettings.spec.ts | 88 ++++++++ src/views/VersionSummariesSettings.vue | 202 ++++++++++++++++++ templates/settings-version-summaries.php | 7 + .../VersionSummaryControllerTest.php | 32 ++- .../Settings/VersionSummariesSettingsTest.php | 92 ++++++++ vite.config.ts | 1 + 14 files changed, 540 insertions(+), 1 deletion(-) create mode 100644 lib/Settings/VersionSummariesSettings.php create mode 100644 src/settings.ts create mode 100644 src/tests/views/VersionSummariesSettings.spec.ts create mode 100644 src/views/VersionSummariesSettings.vue create mode 100644 templates/settings-version-summaries.php create mode 100644 tests/unit/Settings/VersionSummariesSettingsTest.php diff --git a/appinfo/info.xml b/appinfo/info.xml index 30f91dbdcc3..dbae515a852 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -39,6 +39,9 @@ OCA\Text\Command\ResetDocument + + OCA\Text\Settings\VersionSummariesSettings + OCA\Text\DAV\WorkspacePlugin diff --git a/appinfo/routes.php b/appinfo/routes.php index f0fa76a3f16..864f674d62b 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -75,5 +75,7 @@ ['name' => 'VersionSummary#lookup', 'url' => '/version-summaries/{fileId}', 'verb' => 'GET'], /** @see Controller\VersionSummaryController::generate() */ ['name' => 'VersionSummary#generate', 'url' => '/version-summaries/{fileId}', 'verb' => 'POST'], + /** @see Controller\VersionSummaryController::updateSettings() */ + ['name' => 'VersionSummary#updateSettings', 'url' => '/settings/version-summaries', 'verb' => 'PUT'], ] ]; diff --git a/composer/composer/autoload_classmap.php b/composer/composer/autoload_classmap.php index 75fe997b260..3a48b97cde3 100644 --- a/composer/composer/autoload_classmap.php +++ b/composer/composer/autoload_classmap.php @@ -111,6 +111,7 @@ 'OCA\\Text\\Service\\VersionSummaryPrompt' => $baseDir . '/../lib/Service/VersionSummaryPrompt.php', 'OCA\\Text\\Service\\VersionSummaryService' => $baseDir . '/../lib/Service/VersionSummaryService.php', 'OCA\\Text\\Service\\WorkspaceService' => $baseDir . '/../lib/Service/WorkspaceService.php', + 'OCA\\Text\\Settings\\VersionSummariesSettings' => $baseDir . '/../lib/Settings/VersionSummariesSettings.php', 'OCA\\Text\\TextFile' => $baseDir . '/../lib/TextFile.php', 'OCA\\Text\\YjsMessage' => $baseDir . '/../lib/YjsMessage.php', ); diff --git a/composer/composer/autoload_static.php b/composer/composer/autoload_static.php index ebb88eb31cd..95d53ff5677 100644 --- a/composer/composer/autoload_static.php +++ b/composer/composer/autoload_static.php @@ -126,6 +126,7 @@ class ComposerStaticInitText 'OCA\\Text\\Service\\VersionSummaryPrompt' => __DIR__ . '/..' . '/../lib/Service/VersionSummaryPrompt.php', 'OCA\\Text\\Service\\VersionSummaryService' => __DIR__ . '/..' . '/../lib/Service/VersionSummaryService.php', 'OCA\\Text\\Service\\WorkspaceService' => __DIR__ . '/..' . '/../lib/Service/WorkspaceService.php', + 'OCA\\Text\\Settings\\VersionSummariesSettings' => __DIR__ . '/..' . '/../lib/Settings/VersionSummariesSettings.php', 'OCA\\Text\\TextFile' => __DIR__ . '/..' . '/../lib/TextFile.php', 'OCA\\Text\\YjsMessage' => __DIR__ . '/..' . '/../lib/YjsMessage.php', ); diff --git a/lib/Controller/VersionSummaryController.php b/lib/Controller/VersionSummaryController.php index 24606b3007b..c2980611e25 100644 --- a/lib/Controller/VersionSummaryController.php +++ b/lib/Controller/VersionSummaryController.php @@ -10,6 +10,7 @@ namespace OCA\Text\Controller; use OCA\Text\Exception\VersionSummaryException; +use OCA\Text\Service\ConfigService; use OCA\Text\Service\VersionSummaryService; use OCP\AppFramework\Http; use OCP\AppFramework\Http\Attribute\NoAdminRequired; @@ -24,6 +25,7 @@ public function __construct( string $appName, IRequest $request, private readonly VersionSummaryService $versionSummaryService, + private readonly ConfigService $configService, private readonly IUserSession $userSession, ) { parent::__construct($appName, $request); @@ -60,6 +62,35 @@ public function generate(int $fileId, string $from, string $to, string $fromHash return $this->respond(fn ($user) => $this->versionSummaryService->generate($user, $fileId, $from, $to, $fromHash, $toHash)); } + /** + * Turn summaries on or off and set their hourly limits. Off removes every + * summary and pending task, and says whether all are gone. + * + * @param bool|null $enabled Whether summaries are on + * @param int|null $hourlyLimit Summaries the instance may start per hour + * @param int|null $userHourlyLimit Summaries one person may start per hour + */ + public function updateSettings(?bool $enabled = null, ?int $hourlyLimit = null, ?int $userHourlyLimit = null): DataResponse { + $removed = null; + if ($hourlyLimit !== null) { + $this->configService->setVersionSummariesHourlyLimit($hourlyLimit); + } + if ($userHourlyLimit !== null) { + $this->configService->setVersionSummariesUserHourlyLimit($userHourlyLimit); + } + if ($enabled === true) { + $this->configService->setVersionSummariesEnabled(true); + } elseif ($enabled === false) { + $removed = $this->versionSummaryService->turnOff(); + } + return new DataResponse([ + 'enabled' => $this->configService->isVersionSummariesEnabled(), + 'hourlyLimit' => $this->configService->getVersionSummariesHourlyLimit(), + 'userHourlyLimit' => $this->configService->getVersionSummariesUserHourlyLimit(), + 'removed' => $removed, + ]); + } + /** * @param callable(\OCP\IUser): array $answer */ diff --git a/lib/Service/VersionSummaryService.php b/lib/Service/VersionSummaryService.php index b4a2536b26c..2e1c4d9fd5a 100644 --- a/lib/Service/VersionSummaryService.php +++ b/lib/Service/VersionSummaryService.php @@ -616,6 +616,10 @@ private function purgeAll(bool $evenIfBusy = false): bool { }, true, $evenIfBusy); } + public function startedLastHour(): int { + return $this->mapper->countStartsSince($this->now() - self::HOUR)['count']; + } + public function hasSummaries(): bool { return $this->mapper->hasAny(); } diff --git a/lib/Settings/VersionSummariesSettings.php b/lib/Settings/VersionSummariesSettings.php new file mode 100644 index 00000000000..6a1a82ef30b --- /dev/null +++ b/lib/Settings/VersionSummariesSettings.php @@ -0,0 +1,68 @@ +taskProcessing->getAvailableTaskTypes()[TextToTextChat::ID])) { + try { + $provider = $this->taskProcessing->getPreferredProvider(TextToTextChat::ID)->getName(); + } catch (\Exception $e) { + // The form says no provider is set up + $this->logger->warning('Could not read the chat provider for summaries of changes', ['exception' => $e]); + } + } + $enabled = $this->configService->isVersionSummariesEnabled(); + $this->initialState->provideInitialState('version_summaries_settings', [ + 'enabled' => $enabled, + 'provider' => $provider, + 'hourlyLimit' => $this->configService->getVersionSummariesHourlyLimit(), + 'userHourlyLimit' => $this->configService->getVersionSummariesUserHourlyLimit(), + 'startedLastHour' => $this->versionSummaryService->startedLastHour(), + 'maxInputBytes' => $this->configService->getVersionSummariesMaxInputBytes(), + // Turned off, but a background job has yet to remove some + 'removalPending' => !$enabled && $this->versionSummaryService->hasSummaries(), + ]); + Util::addScript('text', 'text-settings'); + Util::addStyle('text', 'text-settings'); + return new TemplateResponse('text', 'settings-version-summaries'); + } + + public function getSection(): string { + return 'ai'; + } + + public function getPriority(): int { + return 80; + } +} diff --git a/src/settings.ts b/src/settings.ts new file mode 100644 index 00000000000..6cca86c2325 --- /dev/null +++ b/src/settings.ts @@ -0,0 +1,9 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { createApp } from 'vue' +import VersionSummariesSettings from './views/VersionSummariesSettings.vue' + +createApp(VersionSummariesSettings).mount('#text-version-summaries-settings') diff --git a/src/tests/views/VersionSummariesSettings.spec.ts b/src/tests/views/VersionSummariesSettings.spec.ts new file mode 100644 index 00000000000..4419e46277e --- /dev/null +++ b/src/tests/views/VersionSummariesSettings.spec.ts @@ -0,0 +1,88 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import axios from '@nextcloud/axios' +import { loadState } from '@nextcloud/initial-state' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import VersionSummariesSettings from '../../views/VersionSummariesSettings.vue' + +vi.mock('@nextcloud/initial-state', () => ({ loadState: vi.fn() })) + +// Mount the settings as the server described them +function mountSettings(enabled: boolean, provider: string | null, fields: Record = {}) { + vi.mocked(loadState).mockReturnValue({ enabled, provider, hourlyLimit: 60, userHourlyLimit: 10, startedLastHour: 3, maxInputBytes: 240_000, removalPending: false, ...fields }) + return mount(VersionSummariesSettings) +} + +// The server's answer to a change +function saved(fields: Record) { + return { data: { ocs: { data: { enabled: true, hourlyLimit: 60, userHourlyLimit: 10, removed: null, ...fields } } } } +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('VersionSummariesSettings', () => { + it('names the provider as it is written', () => { + const wrapper = mountSettings(true, 'Smith & Sons ') + + expect(wrapper.text()).toContain('AI provider: Smith & Sons ') + }) + + it('keeps a limit edited while its earlier value was being saved', async () => { + let answer!: (value: unknown) => void + vi.spyOn(axios, 'put').mockReturnValueOnce(new Promise((resolve) => { + answer = resolve + }) as never) + const wrapper = mountSettings(true, 'LocalAI') + const [instance] = wrapper.findAll('input[type="number"]') + + await instance!.setValue('20') + ;(instance!.element as HTMLInputElement).value = '5' + await instance!.trigger('input') + answer(saved({ hourlyLimit: 20 })) + await flushPromises() + + expect((instance!.element as HTMLInputElement).value).toBe('5') + }) + + it('keeps the stored limit when the field is left empty', async () => { + const put = vi.spyOn(axios, 'put') + const wrapper = mountSettings(true, 'LocalAI') + const [instance] = wrapper.findAll('input[type="number"]') + + await instance!.setValue('') + await flushPromises() + await instance!.trigger('change') + await flushPromises() + + expect(put).not.toHaveBeenCalledWith(expect.anything(), { hourlyLimit: 0 }) + expect(wrapper.findAllComponents({ name: 'NcInputField' })[0]!.props('modelValue')).toBe('60') + }) + + it('counts the instructions in the size both versions may have', () => { + const wrapper = mountSettings(true, 'LocalAI') + + expect(wrapper.text()).toContain('Both versions and the instructions together may have at most') + }) + + it('shows the switch as stored, and takes no second change while saving', async () => { + let answer!: (value: unknown) => void + const put = vi.spyOn(axios, 'put').mockReturnValueOnce(new Promise((resolve) => { + answer = resolve + }) as never) + const wrapper = mountSettings(false, 'LocalAI') + + await wrapper.find('input[type="checkbox"]').setValue(true) + expect(wrapper.find('input[type="checkbox"]').attributes('disabled')).toBeDefined() + answer(saved({ enabled: false })) + await flushPromises() + + expect(put).toHaveBeenCalledTimes(1) + expect(wrapper.find('input[type="checkbox"]').element).toHaveProperty('checked', false) + }) +}) diff --git a/src/views/VersionSummariesSettings.vue b/src/views/VersionSummariesSettings.vue new file mode 100644 index 00000000000..25c02d7288f --- /dev/null +++ b/src/views/VersionSummariesSettings.vue @@ -0,0 +1,202 @@ + + + + + + + diff --git a/templates/settings-version-summaries.php b/templates/settings-version-summaries.php new file mode 100644 index 00000000000..26716244c3c --- /dev/null +++ b/templates/settings-version-summaries.php @@ -0,0 +1,7 @@ + +
diff --git a/tests/unit/Controller/VersionSummaryControllerTest.php b/tests/unit/Controller/VersionSummaryControllerTest.php index a8b610a47f9..d77b30cd032 100644 --- a/tests/unit/Controller/VersionSummaryControllerTest.php +++ b/tests/unit/Controller/VersionSummaryControllerTest.php @@ -10,6 +10,7 @@ namespace OCA\Text\Controller; use OCA\Text\Exception\VersionSummaryException; +use OCA\Text\Service\ConfigService; use OCA\Text\Service\VersionSummaryService; use OCP\AppFramework\Http; use OCP\IRequest; @@ -20,14 +21,16 @@ class VersionSummaryControllerTest extends TestCase { private VersionSummaryService&MockObject $service; + private ConfigService&MockObject $config; private IUserSession&MockObject $session; private VersionSummaryController $controller; protected function setUp(): void { parent::setUp(); $this->service = $this->createMock(VersionSummaryService::class); + $this->config = $this->createMock(ConfigService::class); $this->session = $this->createMock(IUserSession::class); - $this->controller = new VersionSummaryController('text', $this->createMock(IRequest::class), $this->service, $this->session); + $this->controller = new VersionSummaryController('text', $this->createMock(IRequest::class), $this->service, $this->config, $this->session); } public function testAnswersARefusalWithItsReason(): void { @@ -45,4 +48,31 @@ public function testAnswersNotFoundWithoutAUser(): void { $this->assertSame(Http::STATUS_NOT_FOUND, $this->controller->lookup(42, '1000', 'current', 'a', 'b')->getStatus()); } + + public function testTurnsOffAndSaysWhetherAllIsGone(): void { + $this->config->method('getVersionSummariesHourlyLimit')->willReturn(60); + $this->config->method('getVersionSummariesUserHourlyLimit')->willReturn(10); + $this->service->expects($this->once())->method('turnOff')->willReturn(false); + + $this->assertSame( + ['enabled' => false, 'hourlyLimit' => 60, 'userHourlyLimit' => 10, 'removed' => false], + $this->controller->updateSettings(false)->getData(), + ); + } + + public function testKeepsEverythingWhenTurnedOn(): void { + $this->config->expects($this->once())->method('setVersionSummariesEnabled')->with(true); + $this->service->expects($this->never())->method('turnOff'); + + $this->assertNull($this->controller->updateSettings(true)->getData()['removed']); + } + + public function testSetsOnlyTheLimitsGiven(): void { + $this->config->expects($this->never())->method('setVersionSummariesEnabled'); + $this->config->expects($this->never())->method('setVersionSummariesHourlyLimit'); + $this->config->expects($this->once())->method('setVersionSummariesUserHourlyLimit')->with(3); + $this->service->expects($this->never())->method('turnOff'); + + $this->controller->updateSettings(null, null, 3); + } } diff --git a/tests/unit/Settings/VersionSummariesSettingsTest.php b/tests/unit/Settings/VersionSummariesSettingsTest.php new file mode 100644 index 00000000000..de83798e0fb --- /dev/null +++ b/tests/unit/Settings/VersionSummariesSettingsTest.php @@ -0,0 +1,92 @@ +config = $this->createMock(ConfigService::class); + $this->config->method('getVersionSummariesHourlyLimit')->willReturn(60); + $this->config->method('getVersionSummariesUserHourlyLimit')->willReturn(10); + $this->config->method('getVersionSummariesMaxInputBytes')->willReturn(240_000); + $this->summaries = $this->createMock(VersionSummaryService::class); + $this->summaries->method('startedLastHour')->willReturn(3); + $this->tasks = $this->createMock(IManager::class); + $this->initialState = $this->createMock(IInitialState::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->settings = new VersionSummariesSettings($this->config, $this->summaries, $this->tasks, $this->initialState, $this->logger); + } + + /** + * @return array What the view receives + */ + private function form(): array { + $state = []; + $this->initialState->method('provideInitialState')->willReturnCallback(function (string $key, array $value) use (&$state): void { + $this->assertSame('version_summaries_settings', $key); + $state = $value; + }); + $this->settings->getForm(); + return $state; + } + + public function testNamesTheProviderThatReceivesTheTexts(): void { + $this->config->method('isVersionSummariesEnabled')->willReturn(true); + $provider = $this->createMock(IProvider::class); + $provider->method('getName')->willReturn('LocalAI'); + $this->tasks->method('getAvailableTaskTypes')->willReturn([TextToTextChat::ID => []]); + $this->tasks->method('getPreferredProvider')->with(TextToTextChat::ID)->willReturn($provider); + + $this->assertSame([ + 'enabled' => true, + 'provider' => 'LocalAI', + 'hourlyLimit' => 60, + 'userHourlyLimit' => 10, + 'startedLastHour' => 3, + 'maxInputBytes' => 240_000, + 'removalPending' => false, + ], $this->form()); + } + + public function testSaysWhenThereIsNoProvider(): void { + $this->tasks->method('getAvailableTaskTypes')->willReturn([TextToTextChat::ID => []]); + $this->tasks->method('getPreferredProvider')->willThrowException(new \Exception('No provider')); + $this->logger->expects($this->once())->method('warning'); + + $this->assertNull($this->form()['provider']); + } + + public function testSaysThatSummariesAreStillToBeRemovedAfterTurningOff(): void { + $this->config->method('isVersionSummariesEnabled')->willReturn(false); + $this->summaries->method('hasSummaries')->willReturn(true); + $this->tasks->method('getAvailableTaskTypes')->willReturn([]); + + $form = $this->form(); + $this->assertNull($form['provider']); + $this->assertTrue($form['removalPending']); + } +} diff --git a/vite.config.ts b/vite.config.ts index 1830d335ca4..de71b08de8c 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -37,6 +37,7 @@ const config = createAppConfig( viewer: path.join(__dirname, 'src', 'viewer.js'), editor: path.join(__dirname, 'src', 'editor.js'), init: path.join(__dirname, 'src', 'init.js'), + settings: path.join(__dirname, 'src', 'settings.ts'), }, { createEmptyCSSEntryPoints: true,