feat: AI 대화 DB 영속 + 다중 대화/기록 목록

- AiConversation·AiMessage 엔티티(user/conversation CASCADE), 제목 자동 생성
- 대화 스코프 API: GET/POST /ai/conversations, GET/:id, POST/:id/messages, DELETE/:id (전부 본인 소유 스코프 → IDOR 차단)
- 클라는 새 메시지 1건만 전송, 서버가 DB 이력으로 Claude 호출(무상태 /ai/chat 폐기)
- Claude 실패 시 사용자 메시지·빈 대화 롤백(고아 데이터 방지)
- 프론트: AgentChatPanel 채팅↔지난 대화 목록 뷰(열기/삭제), ai.store 재작성(목록·현재 대화)
- 다른 기기·재로그인·새로고침에도 기록 유지

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-20 08:58:40 +09:00
parent 5da3ec8818
commit e432832c92
13 changed files with 697 additions and 128 deletions
+75 -10
View File
@@ -1,32 +1,97 @@
import {
Body,
Controller,
DefaultValuePipe,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
ParseIntPipe,
ParseUUIDPipe,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AiService } from './ai.service';
import { ChatDto } from './dto/chat.dto';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import type { PublicUser } from '../user/user.service';
import type { PaginatedResult } from '../../common/pagination/pagination';
import {
AiService,
type ConversationDetail,
type ConversationSummary,
type SendResult,
} from './ai.service';
import { SendMessageDto } from './dto/send-message.dto';
// AI 채팅 컨트롤러 — 인증 필요. 외부 API 호출 비용이 있어 라우트 단위 throttle 적용.
// AI 채팅 컨트롤러 — 인증 필요. 대화는 본인 소유만 접근(서비스에서 스코프).
@ApiTags('AI')
@Controller('ai')
@Controller('ai/conversations')
@UseGuards(JwtAuthGuard)
export class AiController {
constructor(private readonly aiService: AiService) {}
@Post('chat')
@Get()
@ApiOperation({ summary: '내 대화 목록 (최근순, 페이지네이션)' })
@ApiResponse({ status: 200, description: '목록 조회 성공' })
list(
@CurrentUser() user: PublicUser,
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
@Query('size', new DefaultValuePipe(20), ParseIntPipe) size: number,
): Promise<PaginatedResult<ConversationSummary>> {
return this.aiService.listConversations(user.id, page, size);
}
@Get(':id')
@ApiOperation({ summary: '대화 상세 (메시지 포함)' })
@ApiResponse({ status: 200, description: '조회 성공' })
@ApiResponse({ status: 404, description: '대화 없음 (RES_001)' })
get(
@CurrentUser() user: PublicUser,
@Param('id', ParseUUIDPipe) id: string,
): Promise<ConversationDetail> {
return this.aiService.getConversation(user.id, id);
}
@Post()
@HttpCode(HttpStatus.CREATED)
@Throttle({ default: { limit: 20, ttl: 60_000 } })
@ApiOperation({ summary: '새 대화 시작 (첫 메시지)' })
@ApiResponse({ status: 201, description: '생성 + AI 응답' })
start(
@CurrentUser() user: PublicUser,
@Body() dto: SendMessageDto,
): Promise<SendResult> {
return this.aiService.startConversation(user.id, dto.content);
}
@Post(':id/messages')
@HttpCode(HttpStatus.OK)
@Throttle({ default: { limit: 20, ttl: 60_000 } })
@ApiOperation({ summary: 'AI 채팅 (Claude)' })
@ApiOperation({ summary: '대화에 메시지 추가' })
@ApiResponse({ status: 200, description: 'AI 응답' })
@ApiResponse({ status: 502, description: 'AI 응답 실패 (BIZ_001)' })
async chat(@Body() dto: ChatDto): Promise<{ reply: string }> {
const reply = await this.aiService.chat(dto.messages);
return { reply };
@ApiResponse({ status: 404, description: '대화 없음 (RES_001)' })
send(
@CurrentUser() user: PublicUser,
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: SendMessageDto,
): Promise<SendResult> {
return this.aiService.addMessage(user.id, id, dto.content);
}
@Delete(':id')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: '대화 삭제' })
@ApiResponse({ status: 200, description: '삭제 성공' })
@ApiResponse({ status: 404, description: '대화 없음 (RES_001)' })
async remove(
@CurrentUser() user: PublicUser,
@Param('id', ParseUUIDPipe) id: string,
): Promise<null> {
await this.aiService.deleteConversation(user.id, id);
return null;
}
}
+5 -1
View File
@@ -1,9 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AiController } from './ai.controller';
import { AiService } from './ai.service';
import { AiConversation } from './entities/ai-conversation.entity';
import { AiMessage } from './entities/ai-message.entity';
// AI 모듈 — Claude(Anthropic) 채팅 프록시
// AI 모듈 — Claude(Anthropic) 채팅 프록시 + 대화/메시지 영속
@Module({
imports: [TypeOrmModule.forFeature([AiConversation, AiMessage])],
controllers: [AiController],
providers: [AiService],
})
+187 -7
View File
@@ -1,22 +1,48 @@
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BusinessException } from '../../common/exceptions/business.exception';
import type { ChatMessageDto } from './dto/chat.dto';
import {
paginated,
resolvePage,
type PaginatedResult,
} from '../../common/pagination/pagination';
import { AiConversation } from './entities/ai-conversation.entity';
import { AiMessage } from './entities/ai-message.entity';
// Anthropic Messages API 응답(필요 필드만)
interface AnthropicResponse {
content?: { type: string; text?: string }[];
}
// 외부 노출 형태
export interface ConversationSummary {
id: string;
title: string;
updatedAt: Date;
}
export interface ConversationDetail {
id: string;
title: string;
messages: { role: 'user' | 'assistant'; content: string }[];
}
export interface SendResult {
conversationId: string;
title: string;
reply: string;
}
const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
const REQUEST_TIMEOUT_MS = 30_000;
const MAX_TOKENS = 1024;
const TITLE_MAX = 60;
const SYSTEM_PROMPT =
'당신은 업무 협업 도구 "Relay" 의 AI 어시스턴트입니다. ' +
'사용자의 질문에 한국어로 간결하고 정확하게 답하세요. ' +
'모르는 내용은 추측하지 말고 모른다고 답하세요.';
// AI(Claude) 채팅 서비스 — Anthropic Messages API 프록시.
// AI(Claude) 채팅 서비스 — 대화/메시지를 DB 에 보관하고 Anthropic Messages API 를 호출.
// 키(CLAUDE_API_KEY)는 서버 env 에만 두고 클라이언트에 노출하지 않는다.
@Injectable()
export class AiService {
@@ -24,7 +50,13 @@ export class AiService {
private readonly apiKey: string;
private readonly model: string;
constructor(config: ConfigService) {
constructor(
config: ConfigService,
@InjectRepository(AiConversation)
private readonly convRepo: Repository<AiConversation>,
@InjectRepository(AiMessage)
private readonly msgRepo: Repository<AiMessage>,
) {
this.apiKey = (config.get<string>('CLAUDE_API_KEY') ?? '').trim();
this.model = (
config.get<string>('CLAUDE_MODEL') ?? 'claude-sonnet-4-6'
@@ -38,8 +70,152 @@ export class AiService {
return this.apiKey.length > 0;
}
// 대화 이력을 받아 Claude 응답 텍스트를 반환
async chat(messages: ChatMessageDto[]): Promise<string> {
// 대화 목록(최근순, 페이지네이션)
async listConversations(
userId: string,
page?: number,
size?: number,
): Promise<PaginatedResult<ConversationSummary>> {
const params = resolvePage(page, size);
const [rows, total] = await this.convRepo.findAndCount({
where: { user: { id: userId } },
order: { updatedAt: 'DESC' },
skip: params.skip,
take: params.take,
});
return paginated(
rows.map((c) => ({ id: c.id, title: c.title, updatedAt: c.updatedAt })),
total,
params,
);
}
// 대화 상세(본인 소유만) — 메시지 시간순
async getConversation(
userId: string,
conversationId: string,
): Promise<ConversationDetail> {
const conv = await this.getOwnedConversation(userId, conversationId);
const messages = await this.msgRepo.find({
where: { conversation: { id: conv.id } },
order: { createdAt: 'ASC' },
});
return {
id: conv.id,
title: conv.title,
messages: messages.map((m) => ({ role: m.role, content: m.content })),
};
}
// 새 대화 시작 — 첫 메시지로 대화 생성 후 응답
async startConversation(
userId: string,
content: string,
): Promise<SendResult> {
this.ensureEnabled();
const conv = await this.convRepo.save(
this.convRepo.create({
user: { id: userId },
title: this.makeTitle(content),
}),
);
return this.appendAndReply(conv, content);
}
// 기존 대화에 메시지 추가 후 응답(본인 소유만)
async addMessage(
userId: string,
conversationId: string,
content: string,
): Promise<SendResult> {
this.ensureEnabled();
const conv = await this.getOwnedConversation(userId, conversationId);
return this.appendAndReply(conv, content);
}
// 대화 삭제(본인 소유만) — 메시지 CASCADE
async deleteConversation(
userId: string,
conversationId: string,
): Promise<void> {
const conv = await this.getOwnedConversation(userId, conversationId);
await this.convRepo.remove(conv);
}
// 사용자 메시지 저장 → 전체 이력으로 Claude 호출 → 응답 저장 → 대화 updatedAt 갱신.
// Claude 실패 시 방금 저장한 사용자 메시지를 롤백(빈 대화면 대화도 삭제)해 고아 데이터 방지.
private async appendAndReply(
conv: AiConversation,
content: string,
): Promise<SendResult> {
const userMsg = await this.msgRepo.save(
this.msgRepo.create({
conversation: { id: conv.id },
role: 'user',
content,
}),
);
const history = await this.msgRepo.find({
where: { conversation: { id: conv.id } },
order: { createdAt: 'ASC' },
});
let reply: string;
try {
reply = await this.callClaude(
history.map((m) => ({ role: m.role, content: m.content })),
);
} catch (e) {
// 롤백 — 방금 사용자 메시지 제거, 남은 메시지가 없으면(첫 메시지였다면) 대화도 삭제
await this.msgRepo.delete(userMsg.id);
const remaining = await this.msgRepo.count({
where: { conversation: { id: conv.id } },
});
if (remaining === 0) {
await this.convRepo.delete(conv.id);
}
throw e;
}
await this.msgRepo.save(
this.msgRepo.create({
conversation: { id: conv.id },
role: 'assistant',
content: reply,
}),
);
// 최근 대화로 정렬되도록 updatedAt 갱신(@UpdateDateColumn)
await this.convRepo.save(conv);
return { conversationId: conv.id, title: conv.title, reply };
}
// 소유권 확인 — 본인 대화가 아니면 404(존재 비노출)
private async getOwnedConversation(
userId: string,
conversationId: string,
): Promise<AiConversation> {
const conv = await this.convRepo.findOne({
where: { id: conversationId, user: { id: userId } },
});
if (!conv) {
throw new BusinessException(
'RES_001',
'대화를 찾을 수 없습니다.',
HttpStatus.NOT_FOUND,
);
}
return conv;
}
private makeTitle(content: string): string {
const firstLine = content.trim().split('\n')[0].trim();
if (!firstLine) return '새 대화';
return firstLine.length > TITLE_MAX
? `${firstLine.slice(0, TITLE_MAX)}`
: firstLine;
}
private ensureEnabled(): void {
if (!this.enabled) {
throw new BusinessException(
'BIZ_001',
@@ -47,7 +223,12 @@ export class AiService {
HttpStatus.SERVICE_UNAVAILABLE,
);
}
}
// Anthropic Messages API 호출 — 실패 시 내부/키 노출 없이 일반 문구
private async callClaude(
messages: { role: 'user' | 'assistant'; content: string }[],
): Promise<string> {
let response: Response;
try {
response = await fetch(ANTHROPIC_URL, {
@@ -61,12 +242,11 @@ export class AiService {
model: this.model,
max_tokens: MAX_TOKENS,
system: SYSTEM_PROMPT,
messages: messages.map((m) => ({ role: m.role, content: m.content })),
messages,
}),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
} catch (e) {
// 네트워크 오류/타임아웃 — 키나 내부 정보는 노출하지 않는다
this.logger.error(
`Anthropic 요청 실패: ${e instanceof Error ? e.message : String(e)}`,
);
-36
View File
@@ -1,36 +0,0 @@
import {
ArrayMaxSize,
ArrayNotEmpty,
IsArray,
IsIn,
IsNotEmpty,
IsString,
MaxLength,
ValidateNested,
} from 'class-validator';
import { Type } from 'class-transformer';
import { ApiProperty } from '@nestjs/swagger';
// 대화 메시지 1건 — 역할(user/assistant)과 내용
export class ChatMessageDto {
@ApiProperty({ description: '역할', enum: ['user', 'assistant'] })
@IsIn(['user', 'assistant'], { message: '잘못된 메시지 역할입니다.' })
role!: 'user' | 'assistant';
@ApiProperty({ description: '메시지 내용' })
@IsString()
@IsNotEmpty({ message: '메시지 내용을 입력해 주세요.' })
@MaxLength(8000, { message: '메시지가 너무 깁니다.' })
content!: string;
}
// AI 채팅 요청 — 대화 이력 전체를 전달(서버는 무상태)
export class ChatDto {
@ApiProperty({ description: '대화 이력', type: [ChatMessageDto] })
@IsArray()
@ArrayNotEmpty({ message: '메시지를 입력해 주세요.' })
@ArrayMaxSize(50, { message: '대화가 너무 깁니다. 새 대화를 시작해 주세요.' })
@ValidateNested({ each: true })
@Type(() => ChatMessageDto)
messages!: ChatMessageDto[];
}
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString, MaxLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
// 메시지 전송 — 대화 생성/이어가기 공통. 이력은 서버가 DB 에서 불러온다.
export class SendMessageDto {
@ApiProperty({ description: '사용자 메시지 내용' })
@IsString()
@IsNotEmpty({ message: '메시지 내용을 입력해 주세요.' })
@MaxLength(8000, { message: '메시지가 너무 깁니다.' })
content!: string;
}
@@ -0,0 +1,33 @@
import {
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
type Relation,
} from 'typeorm';
import { User } from '../../user/entities/user.entity';
// AI 대화 — 사용자별 채팅 스레드. 메시지는 AiMessage 로 분리(1:N).
@Entity('ai_conversations')
export class AiConversation {
@PrimaryGeneratedColumn('uuid')
id!: string;
@ManyToOne(() => User, { onDelete: 'CASCADE', nullable: false })
@JoinColumn({ name: 'user_id' })
user!: Relation<User>;
// 첫 사용자 메시지로 자동 생성되는 제목
@Column({ type: 'varchar', length: 120 })
title!: string;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
// 새 메시지 추가 시 갱신(최근 대화 정렬용)
@UpdateDateColumn({ name: 'updated_at' })
updatedAt!: Date;
}
@@ -0,0 +1,30 @@
import {
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
type Relation,
} from 'typeorm';
import { AiConversation } from './ai-conversation.entity';
// AI 대화 메시지 1건 — 대화에 종속(CASCADE).
@Entity('ai_messages')
export class AiMessage {
@PrimaryGeneratedColumn('uuid')
id!: string;
@ManyToOne(() => AiConversation, { onDelete: 'CASCADE', nullable: false })
@JoinColumn({ name: 'conversation_id' })
conversation!: Relation<AiConversation>;
@Column({ type: 'varchar' })
role!: 'user' | 'assistant';
@Column({ type: 'text' })
content!: string;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
}
+9 -4
View File
@@ -336,14 +336,19 @@ todo ─시작→ prog ─승인요청→ review ─승인→ done
Google/Kakao OAuth(passport, 키 미설정 시 자동 비활성) + 이메일 가입 인증(미인증 로그인 차단, 그랜드페더링). 메일 발송은 `MailService` 플레이스홀더(백엔드 로그). 상세는 §1 참조.
### AI 채팅 (`/api/ai`) — **✅ 완료**
### AI 채팅 (`/api/ai/conversations`) — **✅ 완료 (DB 영속, 다중 대화)**
| 메서드 | 경로 | 요청 | 응답 | 비고 |
|---|---|---|---|---|
| POST | `/ai/chat` | `{ messages: {role:'user'\|'assistant', content}[] }` | `{ reply }` | Claude(Anthropic) 프록시. 인증 필요, IP당 20회/분 throttle |
| GET | `/ai/conversations` | `?page&size` | `{items:[{id,title,updatedAt}],total,...}` | 내 대화 목록(최근순) |
| GET | `/ai/conversations/:id` | — | `{id,title,messages:[{role,content}]}` | 대화 상세(본인 소유만) |
| POST | `/ai/conversations` | `{ content }` | `{ conversationId, title, reply }` | 새 대화 시작(첫 메시지). throttle 20/분 |
| POST | `/ai/conversations/:id/messages` | `{ content }` | `{ conversationId, title, reply }` | 메시지 추가. throttle 20/분 |
| DELETE | `/ai/conversations/:id` | — | `null` | 대화 삭제(메시지 CASCADE) |
- `AiService` 가 Anthropic Messages API(`x-api-key`) 호출 — **키(`CLAUDE_API_KEY`)는 서버 env 에만**, 클라이언트 비노출. 모델 `CLAUDE_MODEL`(기본 `claude-sonnet-4-6`). 미설정 시 503. 외부 오류는 502 + 일반 문구(내부/키 비노출).
- 프론트: `components/AgentChatPanel.vue`(우측 슬라이드 패널). 버튼은 **AppShell 헤더에 상시 노출(모든 화면에서 열림)**. 대화 이력 전체를 매 요청 전송(서버 무상태). 기존 목업 터미널 패널은 제거.
- **대화/메시지를 DB 보관**(`AiConversation`·`AiMessage`, user CASCADE). 모든 접근은 **본인 소유 스코프**(타 사용자 대화는 404=RES_001, IDOR 차단). 클라는 "이 대화에 새 메시지 1건"만 보내고 **서버가 DB 이력으로 Claude 호출**(이전의 클라 전체-이력 전송 방식 폐기).
- `AiService` 가 Anthropic Messages API(`x-api-key`) 호출 — **키(`CLAUDE_API_KEY`)는 서버 env 에만**. 모델 `CLAUDE_MODEL`(기본 `claude-sonnet-4-6`). 미설정 503 / 외부오류 502(내부·키 비노출). **Claude 실패 시 방금 사용자 메시지·빈 대화 롤백**(고아 데이터 방지).
- 프론트: `components/AgentChatPanel.vue`(우측 슬라이드, **채팅 ↔ 지난 대화 목록** 전환·열기·삭제), 버튼은 **AppShell 헤더 상시 노출(모든 화면)**. `stores/ai.store` 가 목록·현재 대화 관리 → **DB 영속이라 다른 기기·재로그인에도 기록 유지**.
### 그 외(미착수)
+2 -1
View File
@@ -315,7 +315,8 @@
- **백엔드** 신규 `modules/ai/`: `AiService`(Anthropic Messages API 프록시 — 글로벌 `fetch` + `AbortSignal.timeout(30s)`, 키는 서버 env 만, 미설정 503·외부오류 502·내부정보 비노출), `AiController` `POST /ai/chat`(JwtAuthGuard + `@Throttle` 20/분), `ChatDto`(role enum + content MaxLength 8000 + 메시지 ArrayMaxSize 50). 모델 `CLAUDE_MODEL`(기본 `claude-sonnet-4-6`). `AiModule` → app.module.
- **프론트** 신규 `components/AgentChatPanel.vue`(우측 슬라이드 채팅 패널, 환영문구·말풍선·타이핑 인디케이터·에러·새대화, plain text + `white-space:pre-wrap`로 XSS 안전), `types/ai.ts`·`composables/useAi.ts`(대화 이력 전체 전송, 서버 무상태). **TaskDetailPage 의 기존 목업 에이전트 패널(스크립트·템플릿·전역 스타일 전부) 제거**. 이로써 보안 L1(에이전트 v-html)도 해소.
- **버튼은 AppShell 헤더로 이동 — 모든 화면에서 상시 노출/열림**(`agentOpen` 은 AppShell 가 보유, `<AgentChatPanel>` 도 AppShell 에서 렌더). **대화 이력은 `stores/ai.store.ts`(싱글톤)에 보관 → 화면 이동에도 유지, '새 대화' 버튼으로만 초기화**(입력 텍스트만 컴포넌트 로컬). 하드 리프레시는 초기화(인메모리).
- **버튼은 AppShell 헤더로 이동 — 모든 화면에서 상시 노출/열림**(`agentOpen` 은 AppShell 가 보유, `<AgentChatPanel>` 도 AppShell 에서 렌더).
- **DB 영속 + 다중 대화로 확장(2026-06-20)**: 사용자 요청 "어디서든 본인 기록 조회 → DB 필요". 무상태 `/ai/chat`**대화 스코프 API**(`AiConversation`·`AiMessage` 엔티티, user CASCADE). 엔드포인트 `GET /ai/conversations`(목록)·`GET/:id`(상세)·`POST /ai/conversations`(새 대화)·`POST /:id/messages`(추가)·`DELETE /:id` — 전부 **본인 소유 스코프**(타인 대화 404=IDOR 차단). **클라는 새 메시지 1건만 보내고 서버가 DB 이력으로 Claude 호출**(보안·페이로드 개선). **Claude 실패 시 사용자 메시지·빈 대화 롤백**. 프론트 `AgentChatPanel`**채팅↔지난 대화 목록 뷰**(열기/삭제), `ai.store` 가 목록·현재 대화 관리. **이제 다른 기기·재로그인·새로고침에도 기록 유지.** SendMessageDto(content 8000자). 검증 백엔드 build/lint 0·20 tests, 프론트 0. 런타임 미검증(키·DB 필요).
- 검증: 백엔드 build/lint 0·20 tests, 프론트 type-check/lint/build 0. **런타임 미검증**(실제 API 키 호출 필요). 모델 ID는 콘솔 가용 모델로 `CLAUDE_MODEL` 교체 가능.
#### 8-7. 그 외(미착수)
+187 -46
View File
@@ -1,17 +1,15 @@
<script setup lang="ts">
// AI 채팅 패널 — Claude API 와 대화. body 로 Teleport 되는 우측 슬라이드 패널.
// 대화 이력은 ai.store(싱글톤)에 보관해 화면 이동에도 유지되고, '새 대화' 로만 초기화된다.
// AI 채팅 패널 — Claude API 와 대화. 대화/이력은 DB(ai.store)에 보관.
// 우측 슬라이드 패널. 채팅 뷰 ↔ 지난 대화(기록) 목록 뷰 전환.
import { nextTick, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAiStore } from '@/stores/ai.store'
import { relativeTimeKo } from '@/shared/utils/format'
interface Props {
open: boolean
taskTitle?: string
}
const props = withDefaults(defineProps<Props>(), {
taskTitle: '',
})
const props = defineProps<Props>()
interface Emits {
(e: 'close'): void
@@ -19,24 +17,26 @@ interface Emits {
const emit = defineEmits<Emits>()
const aiStore = useAiStore()
const { messages, loading, error } = storeToRefs(aiStore)
const { conversations, listLoading, messages, loading, error } =
storeToRefs(aiStore)
// 입력값만 컴포넌트 로컬(전송 전 임시 텍스트)
// 입력값과 뷰 전환만 컴포넌트 로컬
const input = ref('')
const showHistory = ref(false)
const bodyEl = ref<HTMLElement | null>(null)
// 새 메시지/로딩 시 하단으로 스크롤
function scrollToBottom() {
void nextTick(() => {
if (bodyEl.value) bodyEl.value.scrollTop = bodyEl.value.scrollHeight
if (bodyEl.value && !showHistory.value) {
bodyEl.value.scrollTop = bodyEl.value.scrollHeight
}
})
}
watch(() => [messages.value.length, loading.value], scrollToBottom)
// 패널을 열 때 하단으로 스크롤
watch(
() => props.open,
(open) => {
if (open) scrollToBottom()
if (open && !showHistory.value) scrollToBottom()
},
)
@@ -44,13 +44,30 @@ async function send() {
const text = input.value
if (!text.trim() || loading.value) return
input.value = ''
await aiStore.send(text)
const ok = await aiStore.send(text)
if (!ok) input.value = text // 실패 시 입력 복원
}
function resetChat() {
aiStore.reset()
function newChat() {
aiStore.newConversation()
showHistory.value = false
input.value = ''
}
async function toggleHistory() {
showHistory.value = !showHistory.value
if (showHistory.value) await aiStore.loadConversations()
}
async function openConv(id: string) {
await aiStore.openConversation(id)
showHistory.value = false
}
async function removeConv(id: string) {
if (!window.confirm('이 대화를 삭제할까요?')) return
await aiStore.removeConversation(id)
}
</script>
<template>
@@ -69,26 +86,18 @@ function resetChat() {
<header class="ac-head">
<div class="ac-title">
<span class="ac-logo">AI</span>
<div class="ac-titletext">
<div class="ac-name">
Relay 어시스턴트
</div>
<div
v-if="taskTitle"
class="ac-ctx"
>
{{ taskTitle }}
</div>
<div class="ac-name">
{{ showHistory ? '지난 대화' : 'Relay 어시스턴트' }}
</div>
</div>
<div class="ac-headbtns">
<button
class="ac-iconbtn"
type="button"
title=" 대화"
aria-label=" 대화"
:disabled="loading"
@click="resetChat"
:title="showHistory ? '대화로 돌아가기' : '지난 대화'"
:aria-label="showHistory ? '대화로 돌아가기' : '지난 대화'"
:class="{ on: showHistory }"
@click="toggleHistory"
>
<svg
viewBox="0 0 24 24"
@@ -98,7 +107,26 @@ function resetChat() {
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" /><path d="M21 3v5h-5" />
<path d="M3 12a9 9 0 1 0 9-9 9.74 9.74 0 0 0-6.74 2.74L3 8" /><path d="M3 3v5h5" /><path d="M12 7v5l3 2" />
</svg>
</button>
<button
class="ac-iconbtn"
type="button"
title="새 대화"
aria-label=" 대화"
:disabled="loading"
@click="newChat"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 5v14M5 12h14" />
</svg>
</button>
<button
@@ -122,12 +150,66 @@ function resetChat() {
</div>
</header>
<!-- 대화 영역 -->
<!-- 기록(지난 대화) -->
<div
v-if="showHistory"
class="ac-body ac-history"
>
<div
v-if="listLoading && conversations.length === 0"
class="ac-hist-empty"
>
불러오는
</div>
<div
v-else-if="conversations.length === 0"
class="ac-hist-empty"
>
지난 대화가 없습니다.
</div>
<template v-else>
<div
v-for="c in conversations"
:key="c.id"
class="ac-hist-item"
@click="openConv(c.id)"
>
<div class="ac-hist-main">
<div class="ac-hist-title">
{{ c.title }}
</div>
<div class="ac-hist-time">
{{ relativeTimeKo(c.updatedAt) }}
</div>
</div>
<button
class="ac-hist-del"
type="button"
title="삭제"
aria-label="대화 삭제"
@click.stop="removeConv(c.id)"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 6h18M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2m2 0v14a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V6" />
</svg>
</button>
</div>
</template>
</div>
<!-- 채팅 -->
<div
v-else
ref="bodyEl"
class="ac-body"
>
<!-- 환영 문구 -->
<div
v-if="messages.length === 0"
class="ac-welcome"
@@ -158,7 +240,6 @@ function resetChat() {
</div>
</div>
<!-- 로딩(응답 대기) -->
<div
v-if="loading"
class="ac-msg assistant"
@@ -177,8 +258,11 @@ function resetChat() {
</div>
</div>
<!-- 입력 -->
<footer class="ac-foot">
<!-- 입력 (채팅 뷰에서만) -->
<footer
v-if="!showHistory"
class="ac-foot"
>
<div class="ac-inputrow">
<textarea
v-model="input"
@@ -271,22 +355,11 @@ function resetChat() {
font-weight: 800;
flex-shrink: 0;
}
.ac-titletext {
min-width: 0;
}
.ac-name {
font-size: 0.9375rem;
font-weight: 700;
color: var(--text);
}
.ac-ctx {
font-size: 0.75rem;
color: var(--text-3);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 16rem;
}
.ac-headbtns {
display: flex;
gap: 0.25rem;
@@ -307,6 +380,10 @@ function resetChat() {
background: #f1f2f4;
color: var(--text);
}
.ac-iconbtn.on {
background: var(--accent-weak);
color: var(--accent);
}
.ac-iconbtn:disabled {
opacity: 0.5;
cursor: default;
@@ -433,6 +510,70 @@ function resetChat() {
padding: 0.5rem 0.75rem;
}
/* 기록(지난 대화) 목록 */
.ac-history {
gap: 0;
padding: 0.5rem 0.5rem;
}
.ac-hist-empty {
margin: auto;
text-align: center;
font-size: 0.8125rem;
color: var(--text-3);
padding: 2rem 0;
}
.ac-hist-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 0.625rem;
border-radius: 0.5rem;
cursor: pointer;
}
.ac-hist-item:hover {
background: #f4f5f7;
}
.ac-hist-main {
flex: 1;
min-width: 0;
}
.ac-hist-title {
font-size: 0.875rem;
color: var(--text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.ac-hist-time {
font-size: 0.6875rem;
color: var(--text-3);
margin-top: 0.1875rem;
}
.ac-hist-del {
width: 1.75rem;
height: 1.75rem;
border: none;
background: transparent;
border-radius: 0.4375rem;
color: var(--text-3);
display: grid;
place-items: center;
cursor: pointer;
flex-shrink: 0;
opacity: 0;
}
.ac-hist-item:hover .ac-hist-del {
opacity: 1;
}
.ac-hist-del:hover {
background: var(--red-weak);
color: var(--red);
}
.ac-hist-del svg {
width: 0.9375rem;
height: 0.9375rem;
}
/* 입력 */
.ac-foot {
border-top: 1px solid var(--border);
+45 -5
View File
@@ -1,13 +1,53 @@
import { useApi } from './useApi'
import type { ChatMessage, ChatResult } from '@/types/ai'
import type {
ConversationDetail,
ConversationSummary,
SendResult,
} from '@/types/ai'
import type { Paginated } from '@/types/pagination'
// AI 도메인 API Composable — 대화 이력 전체를 전달(서버 무상태)
// AI 도메인 API Composable — 대화/메시지는 서버(DB)에서 관리(본인 소유 스코프)
export function useAi() {
const api = useApi()
async function chat(messages: ChatMessage[]): Promise<ChatResult> {
return (await api.post('/ai/chat', { messages })) as unknown as ChatResult
async function listConversations(
page = 1,
size = 30,
): Promise<Paginated<ConversationSummary>> {
return (await api.get('/ai/conversations', {
params: { page, size },
})) as unknown as Paginated<ConversationSummary>
}
return { chat }
async function getConversation(id: string): Promise<ConversationDetail> {
return (await api.get(
`/ai/conversations/${id}`,
)) as unknown as ConversationDetail
}
// 새 대화 시작(첫 메시지)
async function startConversation(content: string): Promise<SendResult> {
return (await api.post('/ai/conversations', {
content,
})) as unknown as SendResult
}
// 기존 대화에 메시지 추가
async function sendMessage(id: string, content: string): Promise<SendResult> {
return (await api.post(`/ai/conversations/${id}/messages`, {
content,
})) as unknown as SendResult
}
async function deleteConversation(id: string): Promise<void> {
await api.delete(`/ai/conversations/${id}`)
}
return {
listConversations,
getConversation,
startConversation,
sendMessage,
deleteConversation,
}
}
+94 -15
View File
@@ -1,40 +1,119 @@
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useAi } from '@/composables/useAi'
import type { ChatMessage } from '@/types/ai'
import type { ChatMessage, ConversationSummary } from '@/types/ai'
// AI 채팅 상태 — 싱글톤 스토어라 화면(AppShell) 재마운트에도 대화가 유지된다.
// 초기화는 사용자가 '새 대화' 를 누를 때만 수행한다.
// AI 채팅 상태 — 대화/메시지는 서버(DB)에 보관. 스토어는 현재 열린 대화 + 목록 캐시를 관리.
export const useAiStore = defineStore('ai', () => {
const { chat } = useAi()
const api = useAi()
// 대화 목록(최근순)
const conversations = ref<ConversationSummary[]>([])
const listLoading = ref(false)
// 현재 열린 대화
const currentId = ref<string | null>(null)
const messages = ref<ChatMessage[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
// 메시지 전송 — 사용자 발화 추가 후 대화 이력 전체로 응답 요청
async function send(text: string): Promise<void> {
// 대화 목록 로드(패널/기록 뷰 진입 시)
async function loadConversations(): Promise<void> {
listLoading.value = true
try {
const { items } = await api.listConversations(1, 30)
conversations.value = items
} catch {
// 목록 로드 실패는 조용히(빈 목록 유지)
} finally {
listLoading.value = false
}
}
// 새 대화 — DB 호출 없이 화면만 비운다(첫 메시지 전송 시 생성)
function newConversation(): void {
currentId.value = null
messages.value = []
error.value = null
}
// 기존 대화 열기 — 메시지 로드
async function openConversation(id: string): Promise<void> {
if (loading.value) return
error.value = null
try {
const detail = await api.getConversation(id)
currentId.value = detail.id
messages.value = detail.messages
} catch {
error.value = '대화를 불러오지 못했습니다.'
}
}
// 메시지 전송 — 성공 여부 반환(실패 시 호출측이 입력 복원)
async function send(text: string): Promise<boolean> {
const content = text.trim()
if (!content || loading.value) return
if (!content || loading.value) return false
error.value = null
messages.value.push({ role: 'user', content })
loading.value = true
try {
const { reply } = await chat(messages.value)
messages.value.push({ role: 'assistant', content: reply })
if (currentId.value === null) {
const res = await api.startConversation(content)
currentId.value = res.conversationId
messages.value.push({ role: 'assistant', content: res.reply })
conversations.value.unshift({
id: res.conversationId,
title: res.title,
updatedAt: new Date().toISOString(),
})
} else {
const res = await api.sendMessage(currentId.value, content)
messages.value.push({ role: 'assistant', content: res.reply })
bumpConversation(currentId.value)
}
return true
} catch {
// 실패 — 낙관적으로 추가한 사용자 메시지 롤백(백엔드도 롤백) + 에러 표시
messages.value.pop()
error.value = '응답을 가져오지 못했습니다. 잠시 후 다시 시도해 주세요.'
return false
} finally {
loading.value = false
}
}
// 새 대화 — 사용자가 명시적으로 누를 때만 초기화
function reset(): void {
messages.value = []
error.value = null
loading.value = false
// 대화 삭제 — 목록에서 제거, 현재 대화였다면 새 대화로
async function removeConversation(id: string): Promise<void> {
try {
await api.deleteConversation(id)
conversations.value = conversations.value.filter((c) => c.id !== id)
if (currentId.value === id) newConversation()
} catch {
error.value = '대화를 삭제하지 못했습니다.'
}
}
return { messages, loading, error, send, reset }
// 대화를 목록 맨 위로 이동 + 시각 갱신
function bumpConversation(id: string): void {
const idx = conversations.value.findIndex((c) => c.id === id)
if (idx < 0) return
const [c] = conversations.value.splice(idx, 1)
if (!c) return
c.updatedAt = new Date().toISOString()
conversations.value.unshift(c)
}
return {
conversations,
listLoading,
currentId,
messages,
loading,
error,
loadConversations,
newConversation,
openConversation,
send,
removeConversation,
}
})
+19 -3
View File
@@ -1,10 +1,26 @@
// AI 채팅 메시지 — 백엔드 ChatMessageDto 와 1:1
// AI 채팅 메시지 — 백엔드 메시지와 1:1
export interface ChatMessage {
role: 'user' | 'assistant'
content: string
}
// AI 채팅 응답
export interface ChatResult {
// 대화 목록 항목
export interface ConversationSummary {
id: string
title: string
updatedAt: string
}
// 대화 상세(메시지 포함)
export interface ConversationDetail {
id: string
title: string
messages: ChatMessage[]
}
// 메시지 전송 결과(대화 생성/이어가기 공통)
export interface SendResult {
conversationId: string
title: string
reply: string
}