Skip to content
Draft
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
3 changes: 3 additions & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@
<commands>
<command>OCA\Text\Command\ResetDocument</command>
</commands>
<settings>
<admin>OCA\Text\Settings\VersionSummariesSettings</admin>
</settings>
<sabre>
<plugins>
<plugin>OCA\Text\DAV\WorkspacePlugin</plugin>
Expand Down
2 changes: 2 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
]
];
1 change: 1 addition & 0 deletions composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
);
1 change: 1 addition & 0 deletions composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
);
Expand Down
31 changes: 31 additions & 0 deletions lib/Controller/VersionSummaryController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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<string, mixed> $answer
*/
Expand Down
4 changes: 4 additions & 0 deletions lib/Service/VersionSummaryService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
68 changes: 68 additions & 0 deletions lib/Settings/VersionSummariesSettings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Text\Settings;

use OCA\Text\Service\ConfigService;
use OCA\Text\Service\VersionSummaryService;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\Settings\ISettings;
use OCP\TaskProcessing\IManager;
use OCP\TaskProcessing\TaskTypes\TextToTextChat;
use OCP\Util;
use Psr\Log\LoggerInterface;

/**
* Turning summaries of changes on, in the admin settings for artificial intelligence
*/
class VersionSummariesSettings implements ISettings {
public function __construct(
private readonly ConfigService $configService,
private readonly VersionSummaryService $versionSummaryService,
private readonly IManager $taskProcessing,
private readonly IInitialState $initialState,
private readonly LoggerInterface $logger,
) {
}

public function getForm(): TemplateResponse {
$provider = null;
if (isset($this->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;
}
}
9 changes: 9 additions & 0 deletions src/settings.ts
Original file line number Diff line number Diff line change
@@ -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')
88 changes: 88 additions & 0 deletions src/tests/views/VersionSummariesSettings.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = {}) {
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<string, unknown>) {
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 <AI>')

expect(wrapper.text()).toContain('AI provider: Smith & Sons <AI>')
})

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)
})
})
Loading
Loading