Skip to content
Open
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
1 change: 1 addition & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Refer to the [Context Chat Backend's readme](https://github.com/nextcloud/contex
<command>OCA\ContextChat\Command\Search</command>
<command>OCA\ContextChat\Command\Statistics</command>
<command>OCA\ContextChat\Command\Reindex</command>
<command>OCA\ContextChat\Command\CleanupUntagged</command>
<command>OCA\ContextChat\Command\Wipe</command>
</commands>
<repair-steps>
Expand Down
7 changes: 7 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
use OCA\ContextChat\Listener\AppDisableListener;
use OCA\ContextChat\Listener\FileListener;
use OCA\ContextChat\Listener\ShareListener;
use OCA\ContextChat\Listener\TagListener;
use OCA\ContextChat\Listener\UserDeletedListener;
use OCA\ContextChat\Notification\Notifier;
use OCP\App\Events\AppDisableEvent;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
Expand All @@ -26,6 +28,8 @@
use OCP\Files\Events\NodeRemovedFromCache;
use OCP\Share\Events\ShareCreatedEvent;
use OCP\Share\Events\ShareDeletedEvent;
use OCP\SystemTag\TagAssignedEvent;
use OCP\SystemTag\TagUnassignedEvent;
use OCP\User\Events\UserDeletedEvent;

class Application extends App implements IBootstrap {
Expand Down Expand Up @@ -70,8 +74,11 @@ public function register(IRegistrationContext $context): void {
$context->registerEventListener(NodeRenamedEvent::class, FileListener::class);
$context->registerEventListener(NodeRemovedFromCache::class, FileListener::class);
$context->registerEventListener(NodeWrittenEvent::class, FileListener::class);
$context->registerEventListener(TagAssignedEvent::class, TagListener::class);
$context->registerEventListener(TagUnassignedEvent::class, TagListener::class);
$context->registerEventListener(AppDisableEvent::class, AppDisableListener::class);
$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class);
$context->registerNotifierService(Notifier::class);
// These events were added mid-way through NC 30, 31
if (class_exists('OCP\Files\Config\Event\UserMountAddedEvent')) {
$context->registerEventListener('OCP\Files\Config\Event\UserMountAddedEvent', FileListener::class);
Expand Down
79 changes: 79 additions & 0 deletions lib/BackgroundJobs/TagListChangedJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

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

namespace OCA\ContextChat\BackgroundJobs;

use OCA\ContextChat\Logger;
use OCA\ContextChat\Service\FsEventService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\QueuedJob;
use OCP\Files\IRootFolder;
use OCP\SystemTag\ISystemTagObjectMapper;

/**
* An admin added a tag to, or removed a tag from, the allow or deny list. Only the
* files and folders that carry that tag can change status, so only those are
* looked at (a tag on a folder covers everything inside it).
*
* ACTION_INDEX: the tag no longer blocks, or now allows: queue what is eligible.
* ACTION_REMOVE: the tag now blocks, or no longer allows: remove from the index
* what is no longer eligible.
*
* Eligibility is decided with the lists as they are when the job runs.
*/
class TagListChangedJob extends QueuedJob {
public const ACTION_INDEX = 'index';
public const ACTION_REMOVE = 'remove';

public function __construct(
ITimeFactory $timeFactory,
private Logger $logger,
private IRootFolder $rootFolder,
private ISystemTagObjectMapper $tagMapper,
private FsEventService $fsEventService,
) {
parent::__construct($timeFactory);
}

/**
* @param array{tag_id:int|string, action:string} $argument
*/
protected function run($argument): void {
$tagId = (string)($argument['tag_id'] ?? '');
$action = $argument['action'] ?? '';
if ($tagId === '' || !in_array($action, [self::ACTION_INDEX, self::ACTION_REMOVE], true)) {
$this->logger->warning('[TagListChangedJob] Invalid arguments, nothing done');
return;
}

try {
$objectIds = $this->tagMapper->getObjectIdsForTags([$tagId], 'files');
} catch (\Throwable $e) {
// for example the tag was deleted in the meantime
$this->logger->warning('[TagListChangedJob] Cannot list files of tag ' . $tagId . ': ' . $e->getMessage(), ['exception' => $e]);
return;
}

foreach ($objectIds as $objectId) {
try {
$node = $this->rootFolder->getFirstNodeById((int)$objectId);
if ($node === null) {
continue;
}
if ($action === self::ACTION_INDEX) {
$this->fsEventService->onInsert($node);
} else {
$this->fsEventService->onTagRemoved($node);
}
} catch (\Throwable $e) {
$this->logger->warning('[TagListChangedJob] Failed for file id ' . $objectId . ': ' . $e->getMessage(), ['exception' => $e]);
}
}
}
}
87 changes: 87 additions & 0 deletions lib/BackgroundJobs/TagModeNoticeJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

declare(strict_types=1);

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

namespace OCA\ContextChat\BackgroundJobs;

use OCA\ContextChat\AppInfo\Application;
use OCA\ContextChat\Logger;
use OCA\ContextChat\Notification\Notifier;
use OCP\AppFramework\Services\IAppConfig;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\QueuedJob;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Notification\IManager;

/**
* Tells the users that the admin switched to indexing by tags, or takes that notice
* away again when the admin switches back to indexing everything.
*
* It runs in the background because there can be many users. The job looks at the
* mode as it is when it runs, so quick switches back and forth, and the order in which
* the jobs run, cannot leave a notice that no longer fits the mode.
*/
class TagModeNoticeJob extends QueuedJob {
public const ACTION_NOTIFY = 'notify';
public const ACTION_DISMISS = 'dismiss';

private const OBJECT_TYPE = 'tag_mode';
private const OBJECT_ID = 'enabled';

public function __construct(
ITimeFactory $timeFactory,
private Logger $logger,
private IAppConfig $appConfig,
private IUserManager $userManager,
private IManager $notificationManager,
) {
parent::__construct($timeFactory);
}

/**
* @param array{action:string, skip_user?:string|null} $argument
*/
protected function run($argument): void {
$action = $argument['action'] ?? '';
if (!in_array($action, [self::ACTION_NOTIFY, self::ACTION_DISMISS], true)) {
$this->logger->warning('[TagModeNoticeJob] Invalid action, nothing done');
return;
}

$tagMode = $this->appConfig->getAppValueString('index_mode', 'all', lazy: true) === 'tag_only';
if (($action === self::ACTION_NOTIFY) !== $tagMode) {
// the mode changed again after this job was queued
return;
}

$skipUser = $argument['skip_user'] ?? null;
$count = 0;
$this->userManager->callForSeenUsers(function (IUser $user) use ($action, $skipUser, &$count): void {
if (!$user->isEnabled() || $user->getUID() === $skipUser) {
return;
}

$notification = $this->notificationManager->createNotification();
$notification->setApp(Application::APP_ID)
->setUser($user->getUID())
->setObject(self::OBJECT_TYPE, self::OBJECT_ID);
// never leave two of them for one user
$this->notificationManager->markProcessed($notification);

if ($action === self::ACTION_NOTIFY) {
$notification->setDateTime($this->time->getDateTime())
->setSubject(Notifier::SUBJECT_TAG_MODE_ENABLED);
$this->notificationManager->notify($notification);
}
$count++;
});

$this->logger->info('[TagModeNoticeJob] ' . $action . ' done for ' . $count . ' users');
}
}
49 changes: 49 additions & 0 deletions lib/BackgroundJobs/TagRemovedJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

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

namespace OCA\ContextChat\BackgroundJobs;

use OCA\ContextChat\Service\FsEventService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\QueuedJob;
use OCP\Files\IRootFolder;

/**
* Runs after an allow or a deny tag was removed from a file or folder, once the
* tag rows are consistent again.
* - allow tag removed: removes from the index what is no longer eligible.
* - deny tag removed: queues for indexing what is now eligible.
*/
class TagRemovedJob extends QueuedJob {
public const KIND_ALLOW = 'allow';
public const KIND_DENY = 'deny';

public function __construct(
ITimeFactory $timeFactory,
private IRootFolder $rootFolder,
private FsEventService $fsEventService,
) {
parent::__construct($timeFactory);
}

/**
* @param array{file_id:int, kind?:string} $argument
*/
protected function run($argument): void {
$node = $this->rootFolder->getFirstNodeById($argument['file_id']);
if ($node === null) {
return;
}
if (($argument['kind'] ?? self::KIND_ALLOW) === self::KIND_DENY) {
$this->fsEventService->onInsert($node);
return;
}
$this->fsEventService->onTagRemoved($node);
}
}
83 changes: 83 additions & 0 deletions lib/BackgroundJobs/UntaggedCleanupCrawlJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

declare(strict_types=1);

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

namespace OCA\ContextChat\BackgroundJobs;

use OCA\ContextChat\Logger;
use OCA\ContextChat\Service\FsEventService;
use OCA\ContextChat\Service\IndexCompletionService;
use OCA\ContextChat\Service\StorageService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\QueuedJob;
use OCP\Files\IRootFolder;

/**
* For a single mount, walks all files in batches and removes from the
* index any file that does not have the "AI knowledge" tag. Mirrors
* StorageCrawlJob's batching/self-rescheduling shape, but for cleanup
* instead of indexing.
*/
class UntaggedCleanupCrawlJob extends QueuedJob {
public const BATCH_SIZE = 2000;
public const JOB_INTERVAL = 60;

public function __construct(
ITimeFactory $timeFactory,
private Logger $logger,
private IJobList $jobList,
private StorageService $storageService,
private FsEventService $fsEventService,
private IRootFolder $rootFolder,
private IndexCompletionService $indexCompletionService,
) {
parent::__construct($timeFactory);
}

/**
* @param array{storage_id:int, root_id:int, last_file_id:int|null} $argument
* @return void
*/
protected function run($argument): void {
$storageId = $argument['storage_id'];
$rootId = $argument['root_id'];
$lastFileId = ($argument['last_file_id'] ?? null) === null ? 0 : $argument['last_file_id'];

// Remove current iteration
$this->jobList->remove(self::class, $argument);

$mountFilesCount = 0;
$lastFileIdSeen = $lastFileId;
foreach ($this->storageService->getFilesInMount($storageId, $rootId, $lastFileId, self::BATCH_SIZE) as $fileId) {
$lastFileIdSeen = $fileId;
$mountFilesCount++;

$node = $this->rootFolder->getFirstNodeById($fileId);

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.

This is sadly immensely inefficient.

if ($node === null) {
continue;
}

if (!$this->fsEventService->hasAiKnowledgeTag($node)) {
$this->fsEventService->onDelete($node, false);
}
}

if ($mountFilesCount > 0) {
// Schedule next batch
$this->jobList->scheduleAfter(self::class, $this->time->getTime() + self::JOB_INTERVAL, [
'storage_id' => $storageId,
'root_id' => $rootId,
'last_file_id' => $lastFileIdSeen,
]);
} else {
$this->logger->info('[UntaggedCleanupCrawlJob] Finished mount storage_id=' . $storageId . ' root_id=' . $rootId);
$this->indexCompletionService->checkAndMarkComplete();
}
}
}
48 changes: 48 additions & 0 deletions lib/BackgroundJobs/UntaggedCleanupSchedulerJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

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

namespace OCA\ContextChat\BackgroundJobs;

use OCA\ContextChat\Logger;
use OCA\ContextChat\Service\StorageService;
use OCP\AppFramework\Services\IAppConfig;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\QueuedJob;

/**
* Discovers all mounts and schedules an UntaggedCleanupCrawlJob for each,
* mirroring SchedulerJob's shape.
*/
class UntaggedCleanupSchedulerJob extends QueuedJob {
public function __construct(
ITimeFactory $timeFactory,
private Logger $logger,
private IJobList $jobList,
private StorageService $storageService,
private IAppConfig $appConfig,
) {
parent::__construct($timeFactory);
}

protected function run($argument): void {
// Mirror SchedulerJob: a fresh cleanup run means the initial-indexing
// status is no longer settled until this run finishes.
$this->appConfig->setAppValueInt('last_indexed_time', 0, lazy: true);
foreach ($this->storageService->getMounts() as $mount) {
$this->logger->debug('[UntaggedCleanupSchedulerJob] Scheduling cleanup storage_id=' . $mount['storage_id'] . ' root_id=' . $mount['root_id']);
$this->jobList->add(UntaggedCleanupCrawlJob::class, [
'storage_id' => $mount['storage_id'],
'root_id' => $mount['root_id'],
'last_file_id' => 0,
]);
}
$this->jobList->remove(self::class);
}
}
Loading