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
2 changes: 1 addition & 1 deletion appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Known providers:
More details on how to set this up in the [admin docs](https://docs.nextcloud.com/server/latest/admin_manual/ai/index.html)
]]> </description>
<version>3.5.0-dev.3</version>
<version>3.5.0-dev.4</version>
<licence>agpl</licence>
<author>Julien Veyssier</author>
<namespace>Assistant</namespace>
Expand Down
4 changes: 4 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use OCA\Assistant\Listener\TaskSuccessfulListener;
use OCA\Assistant\Listener\Text2Image\Text2ImageReferenceListener;
use OCA\Assistant\Listener\Text2Image\Text2StickerListener;
use OCA\Assistant\Listener\UserDeletedListener;
use OCA\Assistant\Notification\Notifier;
use OCA\Assistant\Reference\FreePromptReferenceProvider;
use OCA\Assistant\Reference\SpeechToTextReferenceProvider;
Expand All @@ -48,6 +49,7 @@
use OCP\TaskProcessing\Events\TaskFailedEvent;
use OCP\TaskProcessing\Events\TaskSuccessfulEvent;
use OCP\TaskProcessing\IManager;
use OCP\User\Events\UserDeletedEvent;

class Application extends App implements IBootstrap {

Expand Down Expand Up @@ -102,6 +104,8 @@ public function register(IRegistrationContext $context): void {

$context->registerEventListener(AddContentSecurityPolicyEvent::class, CSPListener::class);

$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class);

if (class_exists('OCP\\TaskProcessing\\TaskTypes\\AudioToAudioChat')) {
$context->registerTaskProcessingProvider(AudioToAudioChatProvider::class);
}
Expand Down
11 changes: 11 additions & 0 deletions lib/Db/AssignmentMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,15 @@ public function findDueAssignmentsForUser(string $userId): \Generator {
yield $assignment;
}
}

/**
* @throws \OCP\DB\Exception
*/
public function deleteAllForUser(string $userId): void {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->getTableName())
->where($qb->expr()->eq('user_id', $qb->createPositionalParameter($userId, IQueryBuilder::PARAM_STR)));

$qb->executeStatement();
}
}
24 changes: 24 additions & 0 deletions lib/Db/ChattyLLM/SessionMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,19 @@ public function getUserSessionForAssignment(string $userId, int $assignmentId):
return $this->findEntity($qb);
}

/**
* @return \Generator<array-key, Session>
* @throws \OCP\DB\Exception
*/
public function getAllUserSessions(string $userId): \Generator {
$qb = $this->db->getQueryBuilder();
$qb->select(Session::$columns)
->from($this->getTableName())
->where($qb->expr()->eq('user_id', $qb->createPositionalParameter($userId, IQueryBuilder::PARAM_STR)));

yield from $this->yieldEntities($qb);
}

/**
* @param string $userId
* @param bool $isAssignment
Expand Down Expand Up @@ -205,6 +218,17 @@ public function deleteSession(string $userId, int $sessionId) {
$qb->executeStatement();
}

/**
* @throws \OCP\DB\Exception
*/
public function deleteAllSessionsForUser(string $userId): void {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->getTableName())
->where($qb->expr()->eq('user_id', $qb->createPositionalParameter($userId, IQueryBuilder::PARAM_STR)));

$qb->executeStatement();
}

public function updateSessionIsRemembered(?string $userId, int $sessionId, bool $is_remembered) {
$session = $this->getUserSession($userId, $sessionId);
$session->setIsRemembered($is_remembered);
Expand Down
59 changes: 59 additions & 0 deletions lib/Listener/UserDeletedListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

declare(strict_types=1);

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

namespace OCA\Assistant\Listener;

use OCA\Assistant\Service\AssignmentsService;
use OCA\Assistant\Service\ChatService;
use OCA\Assistant\Service\InternalException;
use OCA\Assistant\Service\SessionSummaryService;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\User\Events\UserDeletedEvent;
use Psr\Log\LoggerInterface;

/**
* @template-implements IEventListener<UserDeletedEvent>
*/
class UserDeletedListener implements IEventListener {

public function __construct(
private ChatService $chatService,
private AssignmentsService $assignmentsService,
private LoggerInterface $logger,
private SessionSummaryService $sessionSummaryService,
) {
}

public function handle(Event $event): void {
if (!($event instanceof UserDeletedEvent)) {
return;
}

$userId = $event->getUid();

try {
$this->assignmentsService->deleteAllForUser($userId);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't cleanup the jobs created by SessionSummaryService. I think we should check if there are some jobs scheduled for the user and remove them from the bg job queue.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed a new commit that does both.

} catch (InternalException $e) {
$this->logger->error('Error while deleting assignments for user ' . $userId, ['exception' => $e]);
}

try {
$this->chatService->deleteAllUserChatData($userId);
} catch (InternalException $e) {
$this->logger->error('Error while deleting chat data for user ' . $userId, ['exception' => $e]);
}

try {
$this->sessionSummaryService->deleteSummaryJobsForUser($userId);
} catch (InternalException $e) {
$this->logger->error('Error while deleting summary jobs for user ' . $userId, ['exception' => $e]);
}
}
}
110 changes: 110 additions & 0 deletions lib/Migration/Version030500Date20260715083046.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

declare(strict_types=1);

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

namespace OCA\Assistant\Migration;

use Closure;
use OCA\Assistant\Service\AssignmentsService;
use OCA\Assistant\Service\ChatService;
use OCA\Assistant\Service\InternalException;
use OCA\Assistant\Service\SessionSummaryService;
use OCP\DB\ISchemaWrapper;
use OCP\IDBConnection;
use OCP\IUserManager;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
use Override;
use Psr\Log\LoggerInterface;

class Version030500Date20260715083046 extends SimpleMigrationStep {

public function __construct(
private IDBConnection $db,
private IUserManager $userManager,
private AssignmentsService $assignmentsService,
private ChatService $chatService,
private SessionSummaryService $sessionSummaryService,
private LoggerInterface $logger,
) {
}

/**
* Clean up chat and assignment data left behind by users deleted before UserDeletedListener existed.
*
* @param IOutput $output
* @param Closure(): ISchemaWrapper $schemaClosure
* @param array $options
*/
#[Override]
public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
$userIds = $this->getDistinctUserIds();
$cleaned = 0;

foreach ($userIds as $userId) {
if ($this->userManager->userExists($userId)) {
continue;
}

try {
$this->assignmentsService->deleteAllForUser($userId);
} catch (InternalException $e) {
$this->logger->error('Error while deleting assignments for deleted user ' . $userId, ['exception' => $e]);
}

try {
$this->chatService->deleteAllUserChatData($userId);
} catch (InternalException $e) {
$this->logger->error('Error while deleting chat data for deleted user ' . $userId, ['exception' => $e]);
}

try {
$this->sessionSummaryService->deleteSummaryJobsForUser($userId);
} catch (InternalException $e) {
$this->logger->error('Error while deleting summary jobs for deleted user ' . $userId, ['exception' => $e]);
}

$cleaned++;
}

if ($cleaned > 0) {
$output->info('Cleaned up assistant data for ' . $cleaned . ' deleted user(s)');
}
}

/**
* @return list<string>

Check failure on line 81 in lib/Migration/Version030500Date20260715083046.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-master

MoreSpecificReturnType

lib/Migration/Version030500Date20260715083046.php:81:13: MoreSpecificReturnType: The declared return type 'list<string>' for OCA\Assistant\Migration\Version030500Date20260715083046::getDistinctUserIds is more specific than the inferred return type 'array<int<0, max>, mixed>' (see https://psalm.dev/070)
*/
private function getDistinctUserIds(): array {
$userIds = [];

$userIdsChat = [];
$userIdsAssignments = [];

if ($this->db->tableExists('assistant_chat_sns')) {
$qb = $this->db->getQueryBuilder();
$qb->selectDistinct('user_id')
->from('assistant_chat_sns');
$result = $qb->executeQuery();
$userIdsChat = $result->fetchFirstColumn();
$result->closeCursor();
}

if ($this->db->tableExists('assistant_assignments')) {
$qb = $this->db->getQueryBuilder();
$qb->selectDistinct('user_id')
->from('assistant_assignments');
$result = $qb->executeQuery();
$userIdsAssignments = $result->fetchFirstColumn();
$result->closeCursor();
}

$userIds = array_unique(array_merge($userIdsChat, $userIdsAssignments));
return $userIds;

Check failure on line 108 in lib/Migration/Version030500Date20260715083046.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-master

LessSpecificReturnStatement

lib/Migration/Version030500Date20260715083046.php:108:10: LessSpecificReturnStatement: The type 'array<int<0, max>, mixed>' is more general than the declared return type 'list<string>' for OCA\Assistant\Migration\Version030500Date20260715083046::getDistinctUserIds (see https://psalm.dev/129)
}
}
20 changes: 20 additions & 0 deletions lib/Service/AssignmentsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use OCP\DB\Exception;
use OCP\IDateTimeZone;
use OCP\IL10N;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;

class AssignmentsService {
Expand All @@ -33,6 +34,7 @@ public function __construct(
private IJobList $jobList,
private IL10N $l10n,
private IDateTimeZone $dateTimeZone,
private IUserManager $userManager,
) {
}

Expand Down Expand Up @@ -84,13 +86,31 @@ public function createAssignment(?string $userId, string $title, string $prompt,
return $assignment;
}

/**
* @throws InternalException
*/
public function deleteAllForUser(string $userId): void {
try {
$this->assignmentMapper->deleteAllForUser($userId);
} catch (Exception $e) {
throw new InternalException(previous: $e);
}
if ($this->jobList->has(RunAssignmentsJob::class, ['userId' => $userId])) {
$this->jobList->remove(RunAssignmentsJob::class, ['userId' => $userId]);
}
}

/**
* @throws InternalException|UnauthorizedException
*/
public function runDueAssignmentsForUser(?string $userId): void {
if ($userId === null) {
throw new UnauthorizedException();
}
if ($this->userManager->get($userId) === null) {
$this->deleteAllForUser($userId);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we also clean everything up here? The chat sessions+messages and the summary bg jobs?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean, they should already be cleaned up via listener, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If some users where deleted before this PR, there can still be data hanging around.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair, but maybe that should be a migration step and not solved here?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, a repair step seems appropriate.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A repair step makes sense for this.

return;
}
try {
foreach ($this->assignmentMapper->findDueAssignmentsForUser($userId) as $assignment) {
if ($assignment === null) {
Expand Down
15 changes: 15 additions & 0 deletions lib/Service/ChatService.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,21 @@ public function deleteSession(?string $userId, int $sessionId): void {
}
}

/**
* @throws InternalException
*/
public function deleteAllUserChatData(string $userId): void {
try {
$sessions = $this->sessionMapper->getAllUserSessions($userId);
foreach ($sessions as $session) {
$this->messageMapper->deleteMessagesBySession($session->getId());
}
$this->sessionMapper->deleteAllSessionsForUser($userId);
} catch (Exception|\RuntimeException $e) {
throw new InternalException(previous: $e);
}
}

/**
* @return list<Session>
* @throws InternalException
Expand Down
9 changes: 9 additions & 0 deletions lib/Service/SessionSummaryService.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ public function __construct(
) {
}

public function deleteSummaryJobsForUser(string $userId): void {
if ($this->jobList->has(GenerateNewChatSummaries::class, ['userId' => $userId])) {
$this->jobList->remove(GenerateNewChatSummaries::class, ['userId' => $userId]);
}
if ($this->jobList->has(RegenerateOutdatedChatSummariesJob::class, ['userId' => $userId])) {
$this->jobList->remove(RegenerateOutdatedChatSummariesJob::class, ['userId' => $userId]);
}
}

private function generateSummaries(array $sessions): void {
foreach ($sessions as $session) {
try {
Expand Down
Loading