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
1 change: 1 addition & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
['name' => 'chattyLLM#deleteMessage', 'url' => '/chat/delete_message', 'verb' => 'DELETE'],
['name' => 'chattyLLM#getMessages', 'url' => '/chat/messages', 'verb' => 'GET'],
['name' => 'chattyLLM#getMessage', 'url' => '/chat/sessions/{sessionId}/messages/{messageId}', 'verb' => 'GET'],
['name' => 'chattyLLM#searchMessages', 'url' => '/chat/search', 'verb' => 'GET'],
['name' => 'chattyLLM#generateForSession', 'url' => '/chat/generate', 'verb' => 'GET'],
['name' => 'chattyLLM#regenerateForSession', 'url' => '/chat/regenerate', 'verb' => 'GET'],
['name' => 'chattyLLM#checkSession', 'url' => '/chat/check_session', 'verb' => 'GET'],
Expand Down
27 changes: 27 additions & 0 deletions lib/Controller/ChattyLLMController.php
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,33 @@
}
}

/**
* Search chat messages
*
* Search through all chat messages for the current user
*
* @param string $query The search query
* @return JSONResponse<Http::STATUS_OK, array{messages: list<AssistantChatMessage>, sessionIds: list<int>}, array{}>|JSONResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_UNAUTHORIZED, array{error: string}, array{}>

Check failure on line 475 in lib/Controller/ChattyLLMController.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-stable33

MoreSpecificReturnType

lib/Controller/ChattyLLMController.php:475:13: MoreSpecificReturnType: The declared return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array{attachments: list<array{fileId: int, type: string}>, content: string, id: int, ocp_task_id: int, role: string, session_id: int, sources: string, timestamp: int}>, sessionIds?: list<int>}, array<never, never>>' for OCA\Assistant\Controller\ChattyLLMController::searchMessages is more specific than the inferred return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array<string, mixed>>, sessionIds?: list<int>}, array<never, never>>' (see https://psalm.dev/070)

Check failure on line 475 in lib/Controller/ChattyLLMController.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-stable34

MoreSpecificReturnType

lib/Controller/ChattyLLMController.php:475:13: MoreSpecificReturnType: The declared return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array{attachments: list<array{fileId: int, type: string}>, content: string, id: int, ocp_task_id: int, role: string, session_id: int, sources: string, timestamp: int}>, sessionIds?: list<int>}, array<never, never>>' for OCA\Assistant\Controller\ChattyLLMController::searchMessages is more specific than the inferred return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array<string, mixed>>, sessionIds?: list<int>}, array<never, never>>' (see https://psalm.dev/070)

Check failure on line 475 in lib/Controller/ChattyLLMController.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-master

MoreSpecificReturnType

lib/Controller/ChattyLLMController.php:475:13: MoreSpecificReturnType: The declared return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array{attachments: list<array{fileId: int, type: string}>, content: string, id: int, ocp_task_id: int, role: string, session_id: int, sources: string, timestamp: int}>, sessionIds?: list<int>}, array<never, never>>' for OCA\Assistant\Controller\ChattyLLMController::searchMessages is more specific than the inferred return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array<string, mixed>>, sessionIds?: list<int>}, array<never, never>>' (see https://psalm.dev/070)
*
* 200: Search results returned successfully
* 401: Not logged in
*/
#[NoAdminRequired]
#[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT, tags: ['chat_api'])]
public function searchMessages(string $query): JSONResponse {

try {
$result = $this->chatService->searchMessages($this->userId, $query);
return new JSONResponse($result);

Check failure on line 486 in lib/Controller/ChattyLLMController.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-stable33

LessSpecificReturnStatement

lib/Controller/ChattyLLMController.php:486:11: LessSpecificReturnStatement: The type 'OCP\AppFramework\Http\JSONResponse<200, array{messages: list<array<string, mixed>>, sessionIds: list<int>}, array<never, never>>' is more general than the declared return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array{attachments: list<array{fileId: int, type: string}>, content: string, id: int, ocp_task_id: int, role: string, session_id: int, sources: string, timestamp: int}>, sessionIds?: list<int>}, array<never, never>>' for OCA\Assistant\Controller\ChattyLLMController::searchMessages (see https://psalm.dev/129)

Check failure on line 486 in lib/Controller/ChattyLLMController.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-stable34

LessSpecificReturnStatement

lib/Controller/ChattyLLMController.php:486:11: LessSpecificReturnStatement: The type 'OCP\AppFramework\Http\JSONResponse<200, array{messages: list<array<string, mixed>>, sessionIds: list<int>}, array<never, never>>' is more general than the declared return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array{attachments: list<array{fileId: int, type: string}>, content: string, id: int, ocp_task_id: int, role: string, session_id: int, sources: string, timestamp: int}>, sessionIds?: list<int>}, array<never, never>>' for OCA\Assistant\Controller\ChattyLLMController::searchMessages (see https://psalm.dev/129)

Check failure on line 486 in lib/Controller/ChattyLLMController.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-master

LessSpecificReturnStatement

lib/Controller/ChattyLLMController.php:486:11: LessSpecificReturnStatement: The type 'OCP\AppFramework\Http\JSONResponse<200, array{messages: list<array<string, mixed>>, sessionIds: list<int>}, array<never, never>>' is more general than the declared return type 'OCP\AppFramework\Http\JSONResponse<200|401|500, array{error?: string, messages?: list<array{attachments: list<array{fileId: int, type: string}>, content: string, id: int, ocp_task_id: int, role: string, session_id: int, sources: string, timestamp: int}>, sessionIds?: list<int>}, array<never, never>>' for OCA\Assistant\Controller\ChattyLLMController::searchMessages (see https://psalm.dev/129)
} catch (InternalException $e) {
$this->logger->warning('Failed to search chat messages', ['exception' => $e]);
return new JSONResponse(['error' => $this->l10n->t('Failed to search chat messages')], Http::STATUS_INTERNAL_SERVER_ERROR);
} catch (\OCA\Assistant\Service\UnauthorizedException $e) {
return new JSONResponse(['error' => $this->l10n->t('User not logged in')], Http::STATUS_UNAUTHORIZED);
}
}


/**
* Generate a new assistant message
*
Expand Down
20 changes: 20 additions & 0 deletions lib/Db/ChattyLLM/MessageMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,24 @@ public function deleteMessageById(int $sessionId, int $messageId): void {

$qb->executeStatement();
}

/**
* @param string $userId
* @param string $query
* @param int $limit
* @return list<Message>
* @throws \OCP\DB\Exception
*/
public function searchMessages(string $userId, string $query, int $limit = 100): array {
$qb = $this->db->getQueryBuilder();
$qb->select(array_map(fn ($col) => 'm.' . $col, Message::$columns))
->from($this->getTableName(), 'm')
->join('m', 'assistant_chat_sns', 's', $qb->expr()->eq('m.session_id', 's.id'))
->where($qb->expr()->eq('s.user_id', $qb->createPositionalParameter($userId, IQueryBuilder::PARAM_STR)))
->andWhere($qb->expr()->iLike('m.content', $qb->createPositionalParameter('%' . $this->db->escapeLikeParameter($query) . '%', IQueryBuilder::PARAM_STR)))
->orderBy('m.timestamp', 'DESC')
->setMaxResults($limit);

return $this->findEntities($qb);
}
}
26 changes: 26 additions & 0 deletions lib/Service/ChatService.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,32 @@ public function getSessionsForUser(?string $userId): array {
}
}

/**
* @return array{messages: list<array<string,mixed>>, sessionIds: list<int>}
* @throws UnauthorizedException
* @throws InternalException
*/
public function searchMessages(?string $userId, string $query): array {
if ($userId === null) {
throw new UnauthorizedException($this->l10n->t('Unauthorized'));
}
// For empty queries return two empty lists right away
if (trim($query) === '') {
return ['messages' => [], 'sessionIds' => []];
}
try {
$messages = $this->messageMapper->searchMessages($userId, $query);
} catch (Exception $e) {
throw new InternalException(previous: $e);
}
$sessionIds = array_values(array_unique(
array_map(fn (Message $m) => $m->getSessionId(), $messages)
));
return [
'messages' => array_map(fn (Message $m) => $m->jsonSerialize(), $messages), // convert Message objects into plain arrays
'sessionIds' => $sessionIds,
];
}
/**
* @throws BadRequestException
* @throws InternalException
Expand Down
47 changes: 46 additions & 1 deletion src/components/ChattyLLM/ChattyLLMInputForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,21 @@
<PlusIcon :size="20" />
</template>
</NcAppNavigationNew>
<NcAppNavigationSearch
v-model="searchQuery"
:placeholder="t('assistant', 'Search messages…')" />
<div v-if="sessions == null" class="unloaded-sessions">
<NcLoadingIcon :size="30" />
{{ t('assistant', 'Loading conversations…') }}
</div>
<div v-else-if="sessions != null && sessions.length === 0" class="unloaded-sessions">
{{ t('assistant', 'No conversations yet') }}
</div>
<div v-else-if="searchResults !== null && filteredSessions.length === 0" class="unloaded-sessions">
{{ t('assistant', 'No conversations match your search') }}
</div>
<NcAppNavigationItem
v-for="session in sessions"
v-for="session in filteredSessions"
v-else
:key="'conversation' + session.id"
:active="session.id === active?.id"
Expand Down Expand Up @@ -204,6 +210,7 @@ import NcAppNavigationNew from '@nextcloud/vue/components/NcAppNavigationNew'
import NcButton from '@nextcloud/vue/components/NcButton'
import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon'
import NcDialog from '@nextcloud/vue/components/NcDialog'
import NcAppNavigationSearch from '@nextcloud/vue/components/NcAppNavigationSearch'

import ConversationBox from './ConversationBox.vue'
import EditableTextField from './EditableTextField.vue'
Expand All @@ -221,6 +228,7 @@ import { SHAPE_TYPE_NAMES, TASK_STATUS_INT } from '../../constants.js'
// future: type (text, image, file, etc), attachments, etc support

const getChatURL = (endpoint) => generateOcsUrl('/apps/assistant/chat' + endpoint)

const Roles = {
HUMAN: 'human',
ASSISTANT: 'assistant',
Expand All @@ -247,6 +255,7 @@ export default {
NcAppNavigationItem,
NcAppNavigationList,
NcAppNavigationNew,
NcAppNavigationSearch,
NcButton,
NcLoadingIcon,
NcDialog,
Expand Down Expand Up @@ -279,6 +288,7 @@ export default {
newSession: false,
messageDelete: false,
sessionDelete: false,
search: false,
},
msgCursor: 0,
msgLimit: 20,
Expand All @@ -303,6 +313,9 @@ export default {
message: t('assisant', 'Which actions can you do for me?'),
},
],
searchQuery: '',
searchResults: null,
searchDebounceTimer: null,
}
},

Expand All @@ -315,6 +328,13 @@ export default {
const sessionTitle = this.getSessionTitle(session)?.trim()
return t('assistant', 'Are you sure you want to delete "{sessionTitle}"?', { sessionTitle })
},

filteredSessions() {
if (!this.sessions || this.searchResults === null) {
return this.sessions
}
return this.sessions.filter(s => this.searchResults.sessionIds.includes(s.id))
},
},

watch: {
Expand Down Expand Up @@ -392,6 +412,17 @@ export default {
this.loading.titleGeneration = false
}
},

searchQuery(newVal) {
clearTimeout(this.searchDebounceTimer)
if (!newVal.trim()) {
this.searchResults = null
return
}
this.searchDebounceTimer = setTimeout(() => {
this.performSearch(newVal.trim())
}, 350)
},
},

beforeUnmount() {
Expand Down Expand Up @@ -913,6 +944,20 @@ export default {
const url = generateUrl('/apps/assistant/config')
return axios.put(url, req)
},

async performSearch(query) {
this.loading.search = true
try {
const response = await axios.get(getChatURL('/search'), { params: { query } })
this.searchResults = response.data
} catch (error) {
console.error('Search error:', error)
showError(error?.response?.data?.error ?? t('assistant', 'Error searching messages'))
this.searchResults = null
} finally {
this.loading.search = false
}
},
},
}
</script>
Expand Down
130 changes: 130 additions & 0 deletions tests/unit/Service/ChatServiceSearchTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php

declare(strict_types=1);

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

namespace OCA\Assistant\Tests;

use OCA\Assistant\Db\ChattyLLM\Message;
use OCA\Assistant\Db\ChattyLLM\MessageMapper;
use OCA\Assistant\Db\ChattyLLM\SessionMapper;
use OCA\Assistant\Service\ChatService;
use OCA\Assistant\Service\SessionSummaryService;
use OCA\Assistant\Service\UnauthorizedException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IAppConfig;
use OCP\IL10N;
use OCP\IUserManager;
use OCP\TaskProcessing\IManager;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;

class ChatServiceSearchTest extends TestCase {

private ChatService $service;
private MessageMapper $messageMapper;

protected function setUp(): void {
parent::setUp();

// Mock all ChatService dependencies
$this->messageMapper = $this->createMock(MessageMapper::class);

$l10n = $this->createMock(IL10N::class);
$l10n->method('t')->willReturnArgument(0);

$this->service = new ChatService(
$this->createMock(IUserManager::class),
$this->createMock(IAppConfig::class),
$l10n,
$this->createMock(SessionMapper::class),
$this->messageMapper,
$this->createMock(SessionSummaryService::class),
$this->createMock(IManager::class),
$this->createMock(LoggerInterface::class),
$this->createMock(ITimeFactory::class),
);
}

public function testSearchMessagesUserIdNull(): void {
// UserId = null should throw an error
$this->expectException(UnauthorizedException::class);
$this->service->searchMessages(null, 'hello');
}

public function testSearchMessagesBlankQuery(): void {
// A blank query should not hit the database but return empty
$this->messageMapper->expects($this->never())
->method('searchMessages');

$result = $this->service->searchMessages('user1', ' ');

$this->assertSame([], $result['messages']);
$this->assertSame([], $result['sessionIds']);
}

public function testSearchMessagesSameSession(): void {
// Two messages from the same session
$msg1 = new Message();
$msg1->setSessionId(1);
$msg1->setRole(Message::ROLE_HUMAN);
$msg1->setContent('hello assistant');
$msg1->setTimestamp(1000);
$msg1->setSources('[]');
$msg1->setAttachments('[]');

$msg2 = new Message();
$msg2->setSessionId(1);
$msg2->setRole(Message::ROLE_ASSISTANT);
$msg2->setContent('hello human');
$msg2->setTimestamp(1001);
$msg2->setSources('[]');
$msg2->setAttachments('[]');

$this->messageMapper->expects($this->once())
->method('searchMessages')
->with('user1', 'hello')
->willReturn([$msg1, $msg2]);

$result = $this->service->searchMessages('user1', 'hello');

// Two messages returned
$this->assertCount(2, $result['messages']);
// Check that the messages have the same session ID
$this->assertSame([1], $result['sessionIds']);
}

public function testSearchMessagesDifferentSession(): void {
$msg1 = new Message();
$msg1->setSessionId(2);
$msg1->setRole(Message::ROLE_HUMAN);
$msg1->setContent('hello from session 2');
$msg1->setTimestamp(1000);
$msg1->setSources('[]');
$msg1->setAttachments('[]');

$msg2 = new Message();
$msg2->setSessionId(3);
$msg2->setRole(Message::ROLE_HUMAN);
$msg2->setContent('hello from session 3');
$msg2->setTimestamp(1001);
$msg2->setSources('[]');
$msg2->setAttachments('[]');

$this->messageMapper->expects($this->once())
->method('searchMessages')
->with('user1', 'hello')
->willReturn([$msg1, $msg2]);

$result = $this->service->searchMessages('user1', 'hello');

$this->assertCount(2, $result['messages']);

// Check that the messages have different session IDs
$this->assertSame([2, 3], $result['sessionIds']);
}
}
Loading