feat: AI 채팅 패널 (Claude API)

- 백엔드 modules/ai: POST /ai/chat — Anthropic Messages API 프록시(키 서버 env 한정, 30s 타임아웃, throttle 20/분, 미설정 503/외부오류 502)
- ChatDto 검증(role enum, content 8000자, 메시지 50개 상한), 모델 CLAUDE_MODEL(기본 claude-sonnet-4-6)
- 프론트 AgentChatPanel: 우측 슬라이드 채팅(말풍선/타이핑/에러/새 대화), plain text 렌더로 XSS 안전
- AppShell 헤더에 AI 버튼 상시 노출 — 모든 화면에서 열림
- 대화 이력은 stores/ai.store(싱글톤)에 보관 → 화면 이동에도 유지, '새 대화'로만 초기화
- TaskDetailPage 의 기존 목업 에이전트 패널 전부 제거(보안 L1 해소)
- env.example 에 CLAUDE_MODEL 추가

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-20 00:04:48 +09:00
parent db6a80a6f4
commit 5da3ec8818
15 changed files with 814 additions and 1199 deletions
+3 -1
View File
@@ -49,5 +49,7 @@ GITEA_TEMPLATE_REPO=project-base
REPO_IMPORT_ADMIN_EMAIL=admin@example.com
# --- AI 에이전트 (Claude) ---
# Claude(Anthropic) API 키 — AI 에이전트 패널 연동용(추후). 미설정 시 AI 기능 비활성.
# Claude(Anthropic) API 키 — AI 채팅 패널용. 미설정 시 AI 기능 비활성.
CLAUDE_API_KEY=change-me-claude-api-key
# 사용할 모델 ID — 미설정 시 claude-sonnet-4-6. 콘솔에서 사용 가능한 모델로 교체 가능.
CLAUDE_MODEL=claude-sonnet-4-6
+3 -1
View File
@@ -49,5 +49,7 @@ GITEA_TEMPLATE_REPO=project-base
REPO_IMPORT_ADMIN_EMAIL=admin@example.com
# --- AI 에이전트 (Claude) ---
# Claude(Anthropic) API 키 — AI 에이전트 패널 연동용(추후). 미설정 시 AI 기능 비활성.
# Claude(Anthropic) API 키 — AI 채팅 패널용. 미설정 시 AI 기능 비활성.
CLAUDE_API_KEY=change-me-claude-api-key
# 사용할 모델 ID — 미설정 시 claude-sonnet-4-6. 콘솔에서 사용 가능한 모델로 교체 가능.
CLAUDE_MODEL=claude-sonnet-4-6
+2
View File
@@ -17,6 +17,7 @@ import { RepoModule } from './modules/repo/repo.module';
import { TaskModule } from './modules/task/task.module';
import { ActivityModule } from './modules/activity/activity.module';
import { NotificationModule } from './modules/notification/notification.module';
import { AiModule } from './modules/ai/ai.module';
@Module({
imports: [
@@ -95,6 +96,7 @@ import { NotificationModule } from './modules/notification/notification.module';
TaskModule,
ActivityModule,
NotificationModule,
AiModule,
],
controllers: [AppController],
providers: [
+32
View File
@@ -0,0 +1,32 @@
import {
Body,
Controller,
HttpCode,
HttpStatus,
Post,
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';
// AI 채팅 컨트롤러 — 인증 필요. 외부 API 호출 비용이 있어 라우트 단위 throttle 적용.
@ApiTags('AI')
@Controller('ai')
@UseGuards(JwtAuthGuard)
export class AiController {
constructor(private readonly aiService: AiService) {}
@Post('chat')
@HttpCode(HttpStatus.OK)
@Throttle({ default: { limit: 20, ttl: 60_000 } })
@ApiOperation({ summary: 'AI 채팅 (Claude)' })
@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 };
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { AiController } from './ai.controller';
import { AiService } from './ai.service';
// AI 모듈 — Claude(Anthropic) 채팅 프록시
@Module({
controllers: [AiController],
providers: [AiService],
})
export class AiModule {}
+100
View File
@@ -0,0 +1,100 @@
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { BusinessException } from '../../common/exceptions/business.exception';
import type { ChatMessageDto } from './dto/chat.dto';
// Anthropic Messages API 응답(필요 필드만)
interface AnthropicResponse {
content?: { type: string; text?: string }[];
}
const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
const REQUEST_TIMEOUT_MS = 30_000;
const MAX_TOKENS = 1024;
const SYSTEM_PROMPT =
'당신은 업무 협업 도구 "Relay" 의 AI 어시스턴트입니다. ' +
'사용자의 질문에 한국어로 간결하고 정확하게 답하세요. ' +
'모르는 내용은 추측하지 말고 모른다고 답하세요.';
// AI(Claude) 채팅 서비스 — Anthropic Messages API 프록시.
// 키(CLAUDE_API_KEY)는 서버 env 에만 두고 클라이언트에 노출하지 않는다.
@Injectable()
export class AiService {
private readonly logger = new Logger(AiService.name);
private readonly apiKey: string;
private readonly model: string;
constructor(config: ConfigService) {
this.apiKey = (config.get<string>('CLAUDE_API_KEY') ?? '').trim();
this.model = (
config.get<string>('CLAUDE_MODEL') ?? 'claude-sonnet-4-6'
).trim();
if (!this.apiKey) {
this.logger.warn('CLAUDE_API_KEY 미설정 — AI 채팅 비활성화');
}
}
get enabled(): boolean {
return this.apiKey.length > 0;
}
// 대화 이력을 받아 Claude 응답 텍스트를 반환
async chat(messages: ChatMessageDto[]): Promise<string> {
if (!this.enabled) {
throw new BusinessException(
'BIZ_001',
'AI 기능이 설정되지 않았습니다. 관리자에게 문의해 주세요.',
HttpStatus.SERVICE_UNAVAILABLE,
);
}
let response: Response;
try {
response = await fetch(ANTHROPIC_URL, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01',
},
body: JSON.stringify({
model: this.model,
max_tokens: MAX_TOKENS,
system: SYSTEM_PROMPT,
messages: messages.map((m) => ({ role: m.role, content: m.content })),
}),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
} catch (e) {
// 네트워크 오류/타임아웃 — 키나 내부 정보는 노출하지 않는다
this.logger.error(
`Anthropic 요청 실패: ${e instanceof Error ? e.message : String(e)}`,
);
throw new BusinessException(
'BIZ_001',
'AI 응답을 가져오지 못했습니다. 잠시 후 다시 시도해 주세요.',
HttpStatus.BAD_GATEWAY,
);
}
if (!response.ok) {
const detail = await response.text().catch(() => '');
this.logger.error(
`Anthropic API 오류 ${response.status}: ${detail.slice(0, 500)}`,
);
throw new BusinessException(
'BIZ_001',
'AI 응답을 가져오지 못했습니다. 잠시 후 다시 시도해 주세요.',
HttpStatus.BAD_GATEWAY,
);
}
const data = (await response.json()) as AnthropicResponse;
const text = (data.content ?? [])
.filter((b) => b.type === 'text' && typeof b.text === 'string')
.map((b) => b.text)
.join('')
.trim();
return text || '(빈 응답을 받았습니다.)';
}
}
+36
View File
@@ -0,0 +1,36 @@
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[];
}
+10 -1
View File
@@ -336,9 +336,18 @@ todo ─시작→ prog ─승인요청→ review ─승인→ done
Google/Kakao OAuth(passport, 키 미설정 시 자동 비활성) + 이메일 가입 인증(미인증 로그인 차단, 그랜드페더링). 메일 발송은 `MailService` 플레이스홀더(백엔드 로그). 상세는 §1 참조.
### AI 채팅 (`/api/ai`) — **✅ 완료**
| 메서드 | 경로 | 요청 | 응답 | 비고 |
|---|---|---|---|---|
| POST | `/ai/chat` | `{ messages: {role:'user'\|'assistant', content}[] }` | `{ reply }` | Claude(Anthropic) 프록시. 인증 필요, IP당 20회/분 throttle |
- `AiService` 가 Anthropic Messages API(`x-api-key`) 호출 — **키(`CLAUDE_API_KEY`)는 서버 env 에만**, 클라이언트 비노출. 모델 `CLAUDE_MODEL`(기본 `claude-sonnet-4-6`). 미설정 시 503. 외부 오류는 502 + 일반 문구(내부/키 비노출).
- 프론트: `components/AgentChatPanel.vue`(우측 슬라이드 패널). 버튼은 **AppShell 헤더에 상시 노출(모든 화면에서 열림)**. 대화 이력 전체를 매 요청 전송(서버 무상태). 기존 목업 터미널 패널은 제거.
### 그 외(미착수)
AI 에이전트 패널. 메일 실제 발송(SMTP) — 현재 로그 대체. (전체 페이지네이션 통일·실시간 알림·Redis 캐싱은 완료.)
메일 실제 발송(SMTP) — 현재 로그 대체. 보안 후속(계정잠금/CAPTCHA 등). (페이지네이션·실시간 알림·Redis 캐싱·소셜로그인·이메일인증·refresh 회전·AI 채팅은 완료.)
---
+11 -2
View File
@@ -309,8 +309,17 @@
- **L6** CORS `localhost:3000`·Swagger `/api-docs` 비운영 한정.
검증: 백엔드 build/lint 0·20 tests, 프론트 변경 없음.
#### 8-6. 그 외(미착수)
- AI 에이전트 패널 실연동(+ L1 v-html escape), 메일 실발송(SMTP), 보안 후속(토큰 완전회전·계정잠금·비번 재설정 플로우).
#### 8-6. AI 채팅 패널 ✅ (2026-06-19)
**지시**: 기존 목업 UI(가짜 "relay order draft" 터미널)는 버리고, **Claude API로 채팅만** 되도록. 키는 백엔드 env(`CLAUDE_API_KEY`)에 등록됨.
- **백엔드** 신규 `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`(싱글톤)에 보관 → 화면 이동에도 유지, '새 대화' 버튼으로만 초기화**(입력 텍스트만 컴포넌트 로컬). 하드 리프레시는 초기화(인메모리).
- 검증: 백엔드 build/lint 0·20 tests, 프론트 type-check/lint/build 0. **런타임 미검증**(실제 API 키 호출 필요). 모델 ID는 콘솔 가용 모델로 `CLAUDE_MODEL` 교체 가능.
#### 8-7. 그 외(미착수)
- 메일 실발송(SMTP), 비번 재설정 플로우, 보안 후속(계정잠금/CAPTCHA).
---
+500
View File
@@ -0,0 +1,500 @@
<script setup lang="ts">
// AI 채팅 패널 — Claude API 와 대화. body 로 Teleport 되는 우측 슬라이드 패널.
// 대화 이력은 ai.store(싱글톤)에 보관해 화면 이동에도 유지되고, '새 대화' 로만 초기화된다.
import { nextTick, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAiStore } from '@/stores/ai.store'
interface Props {
open: boolean
taskTitle?: string
}
const props = withDefaults(defineProps<Props>(), {
taskTitle: '',
})
interface Emits {
(e: 'close'): void
}
const emit = defineEmits<Emits>()
const aiStore = useAiStore()
const { messages, loading, error } = storeToRefs(aiStore)
// 입력값만 컴포넌트 로컬(전송 전 임시 텍스트)
const input = ref('')
const bodyEl = ref<HTMLElement | null>(null)
// 새 메시지/로딩 시 하단으로 스크롤
function scrollToBottom() {
void nextTick(() => {
if (bodyEl.value) bodyEl.value.scrollTop = bodyEl.value.scrollHeight
})
}
watch(() => [messages.value.length, loading.value], scrollToBottom)
// 패널을 열 때 하단으로 스크롤
watch(
() => props.open,
(open) => {
if (open) scrollToBottom()
},
)
async function send() {
const text = input.value
if (!text.trim() || loading.value) return
input.value = ''
await aiStore.send(text)
}
function resetChat() {
aiStore.reset()
input.value = ''
}
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="ac-backdrop"
@click="emit('close')"
/>
<aside
class="ac-panel"
:class="{ open }"
aria-label="AI 채팅"
>
<!-- 헤더 -->
<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>
</div>
<div class="ac-headbtns">
<button
class="ac-iconbtn"
type="button"
title="새 대화"
aria-label=" 대화"
:disabled="loading"
@click="resetChat"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
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" />
</svg>
</button>
<button
class="ac-iconbtn"
type="button"
title="닫기"
aria-label="닫기"
@click="emit('close')"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
</div>
</header>
<!-- 대화 영역 -->
<div
ref="bodyEl"
class="ac-body"
>
<!-- 환영 문구 -->
<div
v-if="messages.length === 0"
class="ac-welcome"
>
<div class="ac-welcome-logo">
AI
</div>
<div class="ac-welcome-title">
무엇을 도와드릴까요?
</div>
<div class="ac-welcome-sub">
업무나 일정에 대해 자유롭게 질문해 보세요.
</div>
</div>
<div
v-for="(m, i) in messages"
:key="i"
class="ac-msg"
:class="m.role"
>
<span
v-if="m.role === 'assistant'"
class="ac-ava"
>AI</span>
<div class="ac-bubble">
{{ m.content }}
</div>
</div>
<!-- 로딩(응답 대기) -->
<div
v-if="loading"
class="ac-msg assistant"
>
<span class="ac-ava">AI</span>
<div class="ac-bubble ac-typing">
<span /><span /><span />
</div>
</div>
<div
v-if="error"
class="ac-error"
>
{{ error }}
</div>
</div>
<!-- 입력 -->
<footer class="ac-foot">
<div class="ac-inputrow">
<textarea
v-model="input"
class="ac-input"
rows="1"
placeholder="메시지를 입력하세요…"
:disabled="loading"
@keydown.enter.exact.prevent="send"
/>
<button
class="ac-send"
type="button"
title="전송"
aria-label="전송"
:disabled="loading || !input.trim()"
@click="send"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m22 2-7 20-4-9-9-4Z" /><path d="M22 2 11 13" />
</svg>
</button>
</div>
<div class="ac-hint">
Enter 전송 · Shift+Enter 줄바꿈
</div>
</footer>
</aside>
</Teleport>
</template>
<style scoped>
.ac-backdrop {
position: fixed;
inset: 0;
background: rgba(17, 18, 22, 0.32);
z-index: 60;
}
.ac-panel {
position: fixed;
top: 0;
right: 0;
bottom: 0;
width: 26rem;
max-width: 96vw;
background: #fff;
border-left: 1px solid var(--border);
box-shadow: -0.5rem 0 1.5rem rgba(17, 18, 22, 0.12);
display: flex;
flex-direction: column;
transform: translateX(100%);
transition: transform 0.22s ease;
z-index: 61;
}
.ac-panel.open {
transform: translateX(0);
}
/* 헤더 */
.ac-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 0.875rem 1rem;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.ac-title {
display: flex;
align-items: center;
gap: 0.625rem;
min-width: 0;
}
.ac-logo {
width: 2rem;
height: 2rem;
border-radius: 0.5rem;
background: var(--accent);
color: #fff;
display: grid;
place-items: center;
font-size: 0.75rem;
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;
flex-shrink: 0;
}
.ac-iconbtn {
width: 2rem;
height: 2rem;
border: none;
background: transparent;
border-radius: 0.5rem;
color: var(--text-3);
display: grid;
place-items: center;
cursor: pointer;
}
.ac-iconbtn:hover {
background: #f1f2f4;
color: var(--text);
}
.ac-iconbtn:disabled {
opacity: 0.5;
cursor: default;
}
.ac-iconbtn svg {
width: 1.0625rem;
height: 1.0625rem;
}
/* 대화 영역 */
.ac-body {
flex: 1;
overflow-y: auto;
padding: 1.125rem 1rem;
display: flex;
flex-direction: column;
gap: 0.875rem;
}
.ac-welcome {
margin: auto;
text-align: center;
padding: 1.5rem 0;
}
.ac-welcome-logo {
width: 2.75rem;
height: 2.75rem;
border-radius: 0.75rem;
background: var(--accent-weak);
color: var(--accent);
display: grid;
place-items: center;
font-weight: 800;
margin: 0 auto 0.875rem;
}
.ac-welcome-title {
font-size: 1rem;
font-weight: 700;
color: var(--text);
}
.ac-welcome-sub {
font-size: 0.8125rem;
color: var(--text-3);
margin-top: 0.375rem;
line-height: 1.5;
}
.ac-msg {
display: flex;
gap: 0.5rem;
max-width: 100%;
}
.ac-msg.user {
justify-content: flex-end;
}
.ac-ava {
width: 1.625rem;
height: 1.625rem;
border-radius: 0.5rem;
background: var(--accent-weak);
color: var(--accent);
display: grid;
place-items: center;
font-size: 0.625rem;
font-weight: 800;
flex-shrink: 0;
margin-top: 0.125rem;
}
.ac-bubble {
font-size: 0.875rem;
line-height: 1.6;
color: var(--text);
white-space: pre-wrap;
word-break: break-word;
padding: 0.5625rem 0.75rem;
border-radius: 0.75rem;
max-width: 19rem;
}
.ac-msg.assistant .ac-bubble {
background: #f4f5f7;
border-top-left-radius: 0.25rem;
}
.ac-msg.user .ac-bubble {
background: var(--accent);
color: #fff;
border-top-right-radius: 0.25rem;
}
/* 타이핑 인디케이터 */
.ac-typing {
display: inline-flex;
gap: 0.25rem;
align-items: center;
}
.ac-typing span {
width: 0.375rem;
height: 0.375rem;
border-radius: 50%;
background: var(--text-3);
animation: ac-blink 1.2s infinite ease-in-out both;
}
.ac-typing span:nth-child(2) {
animation-delay: 0.18s;
}
.ac-typing span:nth-child(3) {
animation-delay: 0.36s;
}
@keyframes ac-blink {
0%,
80%,
100% {
opacity: 0.25;
}
40% {
opacity: 1;
}
}
.ac-error {
font-size: 0.8125rem;
color: var(--red);
background: var(--red-weak);
border: 1px solid var(--red-border);
border-radius: 0.5rem;
padding: 0.5rem 0.75rem;
}
/* 입력 */
.ac-foot {
border-top: 1px solid var(--border);
padding: 0.75rem 1rem 0.875rem;
flex-shrink: 0;
}
.ac-inputrow {
display: flex;
align-items: flex-end;
gap: 0.5rem;
border: 1px solid var(--border-strong);
border-radius: 0.625rem;
padding: 0.375rem 0.375rem 0.375rem 0.75rem;
background: #fff;
}
.ac-inputrow:focus-within {
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-weak);
}
.ac-input {
flex: 1;
border: none;
outline: none;
resize: none;
font-family: inherit;
font-size: 0.875rem;
line-height: 1.5;
color: var(--text);
background: transparent;
max-height: 7rem;
padding: 0.25rem 0;
}
.ac-input::placeholder {
color: var(--text-3);
}
.ac-send {
width: 2rem;
height: 2rem;
border: none;
border-radius: 0.5rem;
background: var(--accent);
color: #fff;
display: grid;
place-items: center;
cursor: pointer;
flex-shrink: 0;
}
.ac-send:hover:not(:disabled) {
background: var(--accent-hover);
}
.ac-send:disabled {
opacity: 0.45;
cursor: default;
}
.ac-send svg {
width: 1rem;
height: 1rem;
}
.ac-hint {
font-size: 0.6875rem;
color: var(--text-3);
margin-top: 0.4375rem;
text-align: center;
}
</style>
+13
View File
@@ -0,0 +1,13 @@
import { useApi } from './useApi'
import type { ChatMessage, ChatResult } from '@/types/ai'
// AI 도메인 API Composable — 대화 이력 전체를 전달(서버 무상태)
export function useAi() {
const api = useApi()
async function chat(messages: ChatMessage[]): Promise<ChatResult> {
return (await api.post('/ai/chat', { messages })) as unknown as ChatResult
}
return { chat }
}
+42 -1
View File
@@ -7,12 +7,16 @@ import { useRoute, useRouter, RouterLink } from 'vue-router'
import { useAuthStore } from '@/stores/auth.store'
import { useNotificationStore } from '@/stores/notification.store'
import UserAvatar from '@/components/UserAvatar.vue'
import AgentChatPanel from '@/components/AgentChatPanel.vue'
import type { NotificationView } from '@/types/notification'
const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
// AI 채팅 패널 — 모든 화면 헤더에서 열 수 있다
const agentOpen = ref(false)
// 현재 경로 기준으로 상단 네비 활성 항목을 판별
const activeNav = computed<'tasks' | 'repos'>(() =>
route.path.startsWith('/repos') ? 'repos' : 'tasks',
@@ -86,9 +90,32 @@ async function onLogout() {
</nav>
<div class="topbar-right">
<!-- 화면별 추가 액션(: AI 에이전트 버튼) 끼워 넣는 슬롯 -->
<!-- 화면별 추가 액션을 끼워 넣는 슬롯 -->
<slot name="actions" />
<!-- AI 어시스턴트 모든 화면에서 상시 노출 -->
<button
class="icon-btn agent"
type="button"
title="AI 어시스턴트"
aria-label="AI 어시스턴트"
@click="agentOpen = true"
>
<svg
width="17"
height="17"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 3 13.4 8.6 19 10l-5.6 1.4L12 17l-1.4-5.6L5 10l5.6-1.4Z" />
<path d="M18 16l.7 2.3L21 19l-2.3.7L18 22l-.7-2.3L15 19l2.3-.7Z" />
</svg>
</button>
<button
class="icon-btn"
type="button"
@@ -263,6 +290,12 @@ async function onLogout() {
</header>
<slot />
<!-- AI 채팅 패널 헤더 어디서든 열림 -->
<AgentChatPanel
:open="agentOpen"
@close="agentOpen = false"
/>
</template>
<style scoped>
@@ -348,6 +381,14 @@ async function onLogout() {
background: #f1f2f4;
color: var(--text);
}
/* AI 어시스턴트 버튼 강조 */
.icon-btn.agent {
color: var(--accent);
}
.icon-btn.agent:hover {
background: var(--accent-weak);
color: var(--accent-hover);
}
/* 알림 종 + 드롭다운 */
.noti-wrap {
position: relative;
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useAi } from '@/composables/useAi'
import type { ChatMessage } from '@/types/ai'
// AI 채팅 상태 — 싱글톤 스토어라 화면(AppShell) 재마운트에도 대화가 유지된다.
// 초기화는 사용자가 '새 대화' 를 누를 때만 수행한다.
export const useAiStore = defineStore('ai', () => {
const { chat } = useAi()
const messages = ref<ChatMessage[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
// 메시지 전송 — 사용자 발화 추가 후 대화 이력 전체로 응답 요청
async function send(text: string): Promise<void> {
const content = text.trim()
if (!content || loading.value) return
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 })
} catch {
error.value = '응답을 가져오지 못했습니다. 잠시 후 다시 시도해 주세요.'
} finally {
loading.value = false
}
}
// 새 대화 — 사용자가 명시적으로 누를 때만 초기화
function reset(): void {
messages.value = []
error.value = null
loading.value = false
}
return { messages, loading, error, send, reset }
})
+10
View File
@@ -0,0 +1,10 @@
// AI 채팅 메시지 — 백엔드 ChatMessageDto 와 1:1
export interface ChatMessage {
role: 'user' | 'assistant'
content: string
}
// AI 채팅 응답
export interface ChatResult {
reply: string
}