feat: conversation review flow and token fixes

This commit is contained in:
JOJO 2026-01-05 00:59:35 +08:00
parent f9b5aa2af9
commit 3540fa8e4b
9 changed files with 1048 additions and 21 deletions

View File

@ -2668,6 +2668,9 @@ class MainTerminal:
# fast-only 模型强制快速模式 # fast-only 模型强制快速模式
if profile.get("fast_only") and self.run_mode != "fast": if profile.get("fast_only") and self.run_mode != "fast":
self.set_run_mode("fast") self.set_run_mode("fast")
# Qwen-VL 不支持深度思考,自动回落到思考模式
if model_key == "qwen3-vl-plus" and self.run_mode == "deep":
self.set_run_mode("thinking")
# 如果模型支持思考,但当前 run_mode 为 thinking/deep则保持否则无需调整 # 如果模型支持思考,但当前 run_mode 为 thinking/deep则保持否则无需调整
self.api_client.start_new_task(force_deep=self.deep_thinking_mode) self.api_client.start_new_task(force_deep=self.deep_thinking_mode)
return self.model_key return self.model_key

View File

@ -209,6 +209,7 @@
@file-selected="handleFileSelected" @file-selected="handleFileSelected"
@pick-images="openImagePicker" @pick-images="openImagePicker"
@remove-image="handleRemoveImage" @remove-image="handleRemoveImage"
@open-review="openReviewDialog"
/> />
</div> </div>
</main> </main>
@ -226,15 +227,41 @@
<PersonalizationDrawer /> <PersonalizationDrawer />
<LiquidGlassWidget /> <LiquidGlassWidget />
<ImagePicker <transition name="overlay-fade">
v-if="imagePickerOpen" <ImagePicker
:open="imagePickerOpen" v-if="imagePickerOpen"
:entries="imageEntries" :open="imagePickerOpen"
:initial-selected="selectedImages" :entries="imageEntries"
:loading="imageLoading" :initial-selected="selectedImages"
@close="closeImagePicker" :loading="imageLoading"
@confirm="handleImagesConfirmed" @close="closeImagePicker"
/> @confirm="handleImagesConfirmed"
/>
</transition>
<transition name="overlay-fade">
<ConversationReviewDialog
v-if="reviewDialogOpen"
:open="reviewDialogOpen"
:conversations="conversations"
:current-conversation-id="currentConversationId"
:selected-id="reviewSelectedConversationId"
:loading="conversationsLoading"
:loading-more="loadingMoreConversations"
:has-more="hasMoreConversations"
:submitting="reviewSubmitting"
:preview="reviewPreviewLines"
:preview-loading="reviewPreviewLoading"
:preview-error="reviewPreviewError"
:preview-limit="reviewPreviewLimit"
:send-to-model="reviewSendToModel"
:generated-path="reviewGeneratedPath"
@close="reviewDialogOpen = false"
@select="handleReviewSelect"
@load-more="loadMoreConversations"
@toggle-send="reviewSendToModel = $event"
@confirm="handleConfirmReview"
/>
</transition>
<div <div
v-if="isMobileViewport" v-if="isMobileViewport"

View File

@ -13,6 +13,7 @@ import QuickMenu from './components/input/QuickMenu.vue';
import InputComposer from './components/input/InputComposer.vue'; import InputComposer from './components/input/InputComposer.vue';
import AppShell from './components/shell/AppShell.vue'; import AppShell from './components/shell/AppShell.vue';
import ImagePicker from './components/overlay/ImagePicker.vue'; import ImagePicker from './components/overlay/ImagePicker.vue';
import ConversationReviewDialog from './components/overlay/ConversationReviewDialog.vue';
import { useUiStore } from './stores/ui'; import { useUiStore } from './stores/ui';
import { useConversationStore } from './stores/conversation'; import { useConversationStore } from './stores/conversation';
import { useChatStore } from './stores/chat'; import { useChatStore } from './stores/chat';
@ -288,7 +289,18 @@ const appOptions = {
// 工具控制菜单 // 工具控制菜单
icons: ICONS, icons: ICONS,
toolCategoryIcons: TOOL_CATEGORY_ICON_MAP toolCategoryIcons: TOOL_CATEGORY_ICON_MAP,
// 对话回顾
reviewDialogOpen: false,
reviewSelectedConversationId: null,
reviewSubmitting: false,
reviewPreviewLines: [],
reviewPreviewLoading: false,
reviewPreviewError: null,
reviewPreviewLimit: 20,
reviewSendToModel: true,
reviewGeneratedPath: null
} }
}, },
@ -467,7 +479,12 @@ const appOptions = {
return this.streamingUi || this.taskInProgress || monitorLock || this.stopRequested; return this.streamingUi || this.taskInProgress || monitorLock || this.stopRequested;
}, },
composerHeroActive() { composerHeroActive() {
return this.blankHeroActive || this.blankHeroExiting; return (this.blankHeroActive || this.blankHeroExiting) && !this.composerInteractionActive;
},
composerInteractionActive() {
const hasText = !!(this.inputMessage && this.inputMessage.trim().length > 0);
const hasImages = Array.isArray(this.selectedImages) && this.selectedImages.length > 0;
return this.quickMenuOpen || hasText || hasImages;
} }
}, },
@ -2722,6 +2739,23 @@ const appOptions = {
if (data.run_mode) { if (data.run_mode) {
this.runMode = data.run_mode; this.runMode = data.run_mode;
this.thinkingMode = data.thinking_mode ?? (data.run_mode !== 'fast'); this.thinkingMode = data.thinking_mode ?? (data.run_mode !== 'fast');
} else {
// 前端兼容策略:根据模型特性自动调整运行模式
if (key === 'qwen3-vl-plus') {
// Qwen-VL 不支持深度思考,若当前为 deep 则回落到思考模式
if (this.runMode === 'deep') {
this.runMode = 'thinking';
this.thinkingMode = true;
} else {
this.thinkingMode = this.runMode !== 'fast';
}
} else if (key === 'qwen3-max') {
// Qwen-Max 仅快速模式
this.runMode = 'fast';
this.thinkingMode = false;
} else {
this.thinkingMode = this.runMode !== 'fast';
}
} }
this.uiPushToast({ this.uiPushToast({
title: '模型已切换', title: '模型已切换',
@ -2859,6 +2893,183 @@ const appOptions = {
this.compressConversation(); this.compressConversation();
}, },
openReviewDialog() {
if (!this.isConnected) {
this.uiPushToast({
title: '无法使用',
message: '当前未连接,无法生成回顾文件',
type: 'warning'
});
return;
}
if (!this.conversations.length && !this.conversationsLoading) {
this.loadConversationsList();
}
const fallback = this.conversations.find((c) => c.id !== this.currentConversationId);
if (!fallback) {
this.uiPushToast({
title: '暂无可用对话',
message: '没有可供回顾的其他对话记录',
type: 'info'
});
return;
}
this.reviewSelectedConversationId = fallback.id;
this.reviewDialogOpen = true;
this.reviewPreviewLines = [];
this.reviewPreviewError = null;
this.reviewGeneratedPath = null;
this.loadReviewPreview(fallback.id);
this.closeQuickMenu();
},
handleReviewSelect(id) {
if (id === this.currentConversationId) {
this.uiPushToast({
title: '无法引用当前对话',
message: '请选择其他对话生成回顾',
type: 'warning'
});
return;
}
this.reviewSelectedConversationId = id;
this.loadReviewPreview(id);
},
async handleConfirmReview() {
if (this.reviewSubmitting) return;
if (!this.reviewSelectedConversationId) {
this.uiPushToast({
title: '请选择对话',
message: '请选择要生成回顾的对话记录',
type: 'info'
});
return;
}
if (this.reviewSelectedConversationId === this.currentConversationId) {
this.uiPushToast({
title: '无法引用当前对话',
message: '请选择其他对话生成回顾',
type: 'warning'
});
return;
}
if (!this.currentConversationId) {
this.uiPushToast({
title: '无法发送',
message: '当前没有活跃对话,无法自动发送提示消息',
type: 'warning'
});
return;
}
this.reviewSubmitting = true;
try {
const { path, char_count } = await this.generateConversationReview(this.reviewSelectedConversationId);
if (!path) {
throw new Error('未获取到生成的文件路径');
}
const count = typeof char_count === 'number' ? char_count : 0;
this.reviewGeneratedPath = path;
const suggestion =
count && count <= 10000
? '建议直接完整阅读。'
: '建议使用 read 工具进行搜索或分段阅读。';
if (this.reviewSendToModel) {
const message = `帮我继续这个任务,对话文件在 ${path},文件长 ${count || '未知'} 字符,${suggestion} 请阅读文件了解后,不要直接继续工作,而是向我汇报你的理解,然后等我做出指示。`;
const sent = this.sendAutoUserMessage(message);
if (sent) {
this.reviewDialogOpen = false;
}
} else {
this.uiPushToast({
title: '回顾文件已生成',
message: path,
type: 'success'
});
}
} catch (error) {
const msg = error instanceof Error ? error.message : String(error || '生成失败');
this.uiPushToast({
title: '生成回顾失败',
message: msg,
type: 'error'
});
} finally {
this.reviewSubmitting = false;
}
},
async loadReviewPreview(conversationId) {
this.reviewPreviewLoading = true;
this.reviewPreviewError = null;
this.reviewPreviewLines = [];
try {
const resp = await fetch(`/api/conversations/${conversationId}/review_preview?limit=${this.reviewPreviewLimit}`);
const payload = await resp.json().catch(() => ({}));
if (!resp.ok || !payload?.success) {
const msg = payload?.message || payload?.error || '获取预览失败';
throw new Error(msg);
}
this.reviewPreviewLines = payload?.data?.preview || [];
} catch (error) {
const msg = error instanceof Error ? error.message : String(error || '获取预览失败');
this.reviewPreviewError = msg;
} finally {
this.reviewPreviewLoading = false;
}
},
async generateConversationReview(conversationId) {
const response = await fetch(`/api/conversations/${conversationId}/review`, {
method: 'POST'
});
const payload = await response.json().catch(() => ({}));
if (!response.ok || !payload?.success) {
const msg = payload?.message || payload?.error || '生成失败';
throw new Error(msg);
}
const data = payload.data || payload;
return {
path: data.path || data.file_path || data.relative_path,
char_count: data.char_count ?? data.length ?? data.size ?? 0
};
},
sendAutoUserMessage(text) {
const message = (text || '').trim();
if (!message || !this.isConnected) {
return false;
}
const quotaType = this.thinkingMode ? 'thinking' : 'fast';
if (this.isQuotaExceeded(quotaType)) {
this.showQuotaToast({ type: quotaType });
return false;
}
this.taskInProgress = true;
this.chatAddUserMessage(message, []);
if (this.socket) {
this.socket.emit('send_message', {
message,
images: [],
conversation_id: this.currentConversationId
});
}
if (typeof this.monitorShowPendingReply === 'function') {
this.monitorShowPendingReply();
}
if (this.autoScrollEnabled) {
this.scrollToBottom();
}
this.autoResizeInput();
setTimeout(() => {
if (this.currentConversationId) {
this.updateCurrentContextTokens();
}
}, 1000);
return true;
},
autoResizeInput() { autoResizeInput() {
this.$nextTick(() => { this.$nextTick(() => {
const textarea = this.getComposerElement('stadiumInput'); const textarea = this.getComposerElement('stadiumInput');
@ -3231,7 +3442,8 @@ const appOptions = {
QuickMenu, QuickMenu,
InputComposer, InputComposer,
AppShell, AppShell,
ImagePicker ImagePicker,
ConversationReviewDialog
}; };
export default appOptions; export default appOptions;

View File

@ -87,6 +87,7 @@
@toggle-focus-panel="$emit('toggle-focus-panel')" @toggle-focus-panel="$emit('toggle-focus-panel')"
@toggle-token-panel="$emit('toggle-token-panel')" @toggle-token-panel="$emit('toggle-token-panel')"
@compress-conversation="$emit('compress-conversation')" @compress-conversation="$emit('compress-conversation')"
@open-review="$emit('open-review')"
/> />
</div> </div>
</div> </div>
@ -121,7 +122,8 @@ const emit = defineEmits([
'toggle-token-panel', 'toggle-token-panel',
'compress-conversation', 'compress-conversation',
'file-selected', 'file-selected',
'remove-image' 'remove-image',
'open-review'
]); ]);
const props = defineProps<{ const props = defineProps<{

View File

@ -4,6 +4,14 @@
<button type="button" class="menu-entry" @click="$emit('quick-upload')" :disabled="!isConnected || uploading"> <button type="button" class="menu-entry" @click="$emit('quick-upload')" :disabled="!isConnected || uploading">
{{ uploading ? '上传中...' : '上传文件' }} {{ uploading ? '上传中...' : '上传文件' }}
</button> </button>
<button
type="button"
class="menu-entry"
@click.stop="$emit('open-review')"
:disabled="!isConnected || streamingMessage"
>
对话回顾
</button>
<button <button
v-if="currentModelKey === 'qwen3-vl-plus'" v-if="currentModelKey === 'qwen3-vl-plus'"
type="button" type="button"
@ -195,6 +203,7 @@ defineEmits<{
(event: 'select-run-mode', mode: 'fast' | 'thinking' | 'deep'): void; (event: 'select-run-mode', mode: 'fast' | 'thinking' | 'deep'): void;
(event: 'toggle-model-menu'): void; (event: 'toggle-model-menu'): void;
(event: 'select-model', key: string): void; (event: 'select-model', key: string): void;
(event: 'open-review'): void;
}>(); }>();
const runModeOptions = [ const runModeOptions = [

View File

@ -0,0 +1,531 @@
<template>
<div class="review-overlay" @click.self="$emit('close')">
<div class="review-window">
<div class="review-header">
<div>
<div class="title">对话回顾</div>
<div class="subtitle">选择要生成回顾文件的对话</div>
</div>
<div class="header-actions">
<div v-if="generatedPath" class="hint">已生成 {{ generatedPath }}</div>
<button type="button" class="ghost-btn" @click="$emit('close')" :disabled="submitting">关闭</button>
</div>
</div>
<div class="review-body">
<div class="review-left">
<div class="list-head">
<span>对话列表</span>
<span class="counts" v-if="conversations.length"> {{ conversations.length }} </span>
</div>
<div class="conversation-list" :class="{ loading }">
<div v-if="loading" class="empty">正在加载...</div>
<div v-else-if="!conversations.length" class="empty">暂无对话</div>
<template v-else>
<button
v-for="conv in conversations"
:key="conv.id"
type="button"
class="conversation-item"
:class="{
active: conv.id === selectedId,
current: conv.id === currentConversationId
}"
@click="$emit('select', conv.id)"
:disabled="submitting || conv.id === currentConversationId"
>
<div class="row">
<span class="title">{{ conv.title || '未命名对话' }}</span>
<span v-if="conv.id === currentConversationId" class="tag current-tag">当前</span>
</div>
<div class="meta">
<span>{{ formatUpdatedAt(conv.updated_at) }}</span>
<span>
{{ conv.total_messages || 0 }}
<span v-if="(conv.total_tools || 0) > 0"> · {{ conv.total_tools }}工具</span>
</span>
</div>
</button>
</template>
<div class="list-footer" v-if="hasMore || conversations.length">
<button
type="button"
class="ghost-btn"
@click="$emit('load-more')"
:disabled="loadingMore || !hasMore || submitting"
>
{{ loadingMore ? '载入中...' : hasMore ? '加载更多' : '没有更多了' }}
</button>
</div>
</div>
</div>
<div class="review-right">
<div class="preview-header">
<span>预览 {{ previewLimit }} </span>
<span v-if="preview && preview.length" class="preview-count">{{ preview.length }} </span>
</div>
<div class="preview-box" :class="{ loading: previewLoading }">
<div v-if="previewLoading" class="placeholder">
<img :src="icons.loading" alt="" class="big-icon" />
<div class="text-main">预览生成中...</div>
</div>
<div v-else-if="previewError" class="placeholder error">
<img :src="icons.error" alt="" class="big-icon" />
<div class="text-main">{{ previewError }}</div>
</div>
<div v-else-if="!preview || !preview.length" class="placeholder">
<img :src="icons.empty" alt="" class="big-icon" />
<div class="text-main">选择左侧对话以查看预览</div>
<div class="text-sub">最多展示前 {{ previewLimit }} </div>
</div>
<div v-else class="preview-list">
<div v-for="(line, idx) in preview" :key="idx" class="preview-line">
{{ line }}
</div>
</div>
</div>
</div>
</div>
<div class="review-footer">
<label class="toggle-send">
<input type="checkbox" :checked="sendToModel" @change="$emit('toggle-send', ($event.target as HTMLInputElement).checked)" />
<span class="switch"></span>
<span class="label">是否发送给模型</span>
</label>
<button
type="button"
class="primary-btn"
@click="$emit('confirm')"
:disabled="!selectedId || submitting"
>
{{ submitting ? '生成中...' : '确认' }}
</button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
defineOptions({ name: 'ConversationReviewDialog' });
const props = defineProps<{
open: boolean;
conversations: Array<{
id: string;
title: string;
updated_at: string | number;
total_messages?: number;
total_tools?: number;
}>;
selectedId: string | null;
loading: boolean;
loadingMore: boolean;
hasMore: boolean;
submitting: boolean;
currentConversationId: string | null;
preview: string[];
previewLoading: boolean;
previewError?: string | null;
previewLimit?: number;
sendToModel: boolean;
generatedPath?: string | null;
}>();
const icons = {
loading: new URL('../../icons/clock.svg', import.meta.url).href,
error: new URL('../../icons/triangle-alert.svg', import.meta.url).href,
empty: new URL('../../icons/file.svg', import.meta.url).href
};
defineEmits<{
(event: 'close'): void;
(event: 'select', id: string): void;
(event: 'load-more'): void;
(event: 'confirm'): void;
}>();
const formatUpdatedAt = (value: string | number) => {
if (!value) return '-';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '-';
const pad = (n: number) => String(n).padStart(2, '0');
return `${pad(date.getMonth() + 1)}/${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
};
</script>
<style scoped>
.review-overlay {
position: fixed;
inset: 0;
background: rgba(18, 19, 22, 0.4);
backdrop-filter: blur(8px);
display: flex;
align-items: center;
justify-content: center;
z-index: 420;
padding: 24px;
}
.review-window {
width: min(1100px, 96vw);
height: min(720px, 88vh);
background: #ffffff;
border-radius: 20px;
box-shadow: 0 28px 80px rgba(15, 23, 42, 0.25);
display: flex;
flex-direction: column;
overflow: hidden;
border: 1px solid rgba(15, 23, 42, 0.06);
}
.review-header,
.review-footer {
padding: 16px 20px;
display: flex;
align-items: center;
justify-content: space-between;
background: rgba(249, 248, 245, 0.8);
}
.review-header .title {
font-size: 18px;
font-weight: 700;
color: #182033;
}
.review-header .subtitle {
font-size: 13px;
color: #6b7280;
margin-top: 4px;
}
.header-actions {
display: flex;
align-items: center;
gap: 10px;
}
.hint {
font-size: 12px;
color: #4b5563;
padding: 6px 10px;
border-radius: 10px;
background: #f3f4f6;
border: 1px solid #e5e7eb;
max-width: 280px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.review-body {
flex: 1 1 auto;
display: grid;
grid-template-columns: 420px 1fr;
min-height: 0;
}
.review-left {
border-right: 1px solid rgba(15, 23, 42, 0.06);
padding: 12px 14px 14px;
display: flex;
flex-direction: column;
min-height: 0;
}
.list-head {
display: flex;
justify-content: space-between;
align-items: center;
font-weight: 600;
color: #1f2937;
margin-bottom: 8px;
}
.counts {
font-size: 12px;
color: #6b7280;
}
.conversation-list {
flex: 1 1 auto;
overflow-y: auto;
overflow-x: hidden;
border: 1px solid rgba(15, 23, 42, 0.06);
border-radius: 12px;
background: #ffffff;
padding: 8px;
display: flex;
flex-direction: column;
gap: 6px;
scrollbar-width: none;
}
.conversation-list::-webkit-scrollbar {
width: 0;
height: 0;
}
.conversation-item {
width: 100%;
max-width: 360px;
align-self: center;
text-align: left;
background: #ffffff;
border: 1px solid rgba(15, 23, 42, 0.08);
border-radius: 10px;
padding: 14px 14px;
cursor: pointer;
transition: border-color 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease;
overflow: hidden;
min-height: 64px;
line-height: 1.4;
}
.conversation-item:hover {
border-color: rgba(218, 119, 86, 0.4);
box-shadow: 0 6px 18px rgba(15, 23, 42, 0.12);
transform: translateY(-1px);
}
.conversation-item.active {
border-color: rgba(218, 119, 86, 0.8);
box-shadow: 0 8px 22px rgba(218, 119, 86, 0.2);
}
.conversation-item.current {
border-color: var(--claude-accent, #d14b31);
}
.conversation-item .row {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: #1f2937;
}
.conversation-item .title {
flex: 1 1 auto;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.conversation-item .tag {
padding: 2px 8px;
border-radius: 999px;
background: rgba(79, 70, 229, 0.12);
color: #4f46e5;
font-size: 12px;
}
.current-tag {
background: rgba(218, 119, 86, 0.18);
color: var(--claude-accent, #d14b31);
}
.conversation-item .meta {
margin-top: 6px;
font-size: 12px;
color: #6b7280;
display: flex;
gap: 10px;
}
.empty {
text-align: center;
color: #6b7280;
padding: 20px 0;
}
.list-footer {
margin-top: 10px;
display: flex;
justify-content: center;
}
.review-right {
display: flex;
flex-direction: column;
padding: 12px;
min-height: 0;
background: #ffffff;
}
.preview-header {
display: flex;
justify-content: space-between;
align-items: center;
font-weight: 600;
color: #1f2937;
padding: 8px 0;
}
.preview-count {
font-size: 12px;
color: #6b7280;
}
.preview-box {
flex: 1 1 auto;
border: 1px solid rgba(15, 23, 42, 0.06);
border-radius: 12px;
background: #ffffff;
padding: 10px;
overflow: auto;
width: 100%;
}
.preview-list {
display: flex;
flex-direction: column;
gap: 6px;
font-family: Menlo, Consolas, 'SFMono-Regular', monospace;
font-size: 13px;
color: #1f2937;
white-space: pre-wrap;
word-break: break-all;
}
.preview-line {
padding: 6px 8px;
border-radius: 8px;
background: #fff;
border: 1px solid rgba(15, 23, 42, 0.05);
}
.placeholder {
text-align: center;
color: #4b5563;
display: flex;
flex-direction: column;
gap: 8px;
padding: 20px;
align-items: center;
justify-content: center;
}
.big-icon {
width: 42px;
height: 42px;
object-fit: contain;
opacity: 0.85;
}
.text-main {
font-weight: 600;
font-size: 15px;
}
.text-sub {
font-size: 13px;
color: #6b7280;
}
.placeholder.error .text-main {
color: #b91c1c;
}
.review-footer {
gap: 14px;
justify-content: space-between;
align-items: center;
}
.ghost-btn,
.primary-btn {
border: none;
outline: none;
cursor: pointer;
border-radius: 10px;
padding: 10px 18px;
font-weight: 600;
font-size: 14px;
transition: transform 0.12s ease, box-shadow 0.12s ease, background 0.12s ease;
}
.toggle-send {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 14px;
color: #374151;
}
.toggle-send input {
display: none;
}
.toggle-send .switch {
width: 38px;
height: 22px;
border-radius: 999px;
background: #e5e7eb;
position: relative;
transition: background 0.2s ease;
}
.toggle-send .switch::after {
content: '';
position: absolute;
width: 18px;
height: 18px;
border-radius: 50%;
background: #ffffff;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.18);
top: 2px;
left: 2px;
transition: transform 0.2s ease;
}
.toggle-send input:checked + .switch {
background: #d14b31;
}
.toggle-send input:checked + .switch::after {
transform: translateX(16px);
}
.toggle-send .label {
user-select: none;
}
.ghost-btn {
background: #f3f4f6;
color: #1f2937;
}
.ghost-btn:hover:not(:disabled) {
background: #e5e7eb;
}
.primary-btn {
background: linear-gradient(135deg, #da7756, #d44b31);
color: #fffaf0;
box-shadow: 0 10px 24px rgba(212, 75, 49, 0.28);
}
.primary-btn:hover:not(:disabled) {
transform: translateY(-1px);
}
.ghost-btn:disabled,
.primary-btn:disabled,
.conversation-item:disabled {
opacity: 0.55;
cursor: not-allowed;
box-shadow: none;
transform: none;
}
@media (max-width: 900px) {
.review-body {
grid-template-columns: 1fr;
}
.review-left {
border-right: none;
border-bottom: 1px solid rgba(15, 23, 42, 0.06);
}
}
</style>

View File

@ -1,11 +1,12 @@
<template> <template>
<div class="image-picker-backdrop" @click.self="close"> <transition name="overlay-fade">
<div class="image-picker-panel"> <div v-if="open" class="image-picker-backdrop" @click.self="close">
<div class="header"> <div class="image-picker-panel">
<div class="title">选择图片最多9张</div> <div class="header">
<button class="close-btn" @click="close">×</button> <div class="title">选择图片最多9张</div>
</div> <button class="close-btn" @click="close">×</button>
<div class="body"> </div>
<div class="body">
<div v-if="loading" class="loading">加载中...</div> <div v-if="loading" class="loading">加载中...</div>
<div v-else-if="!images.length" class="empty">未找到图片文件</div> <div v-else-if="!images.length" class="empty">未找到图片文件</div>
<div v-else class="grid"> <div v-else class="grid">
@ -30,7 +31,8 @@
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</transition>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">

View File

@ -1623,6 +1623,26 @@
opacity: 0; opacity: 0;
} }
/* 通用覆盖层淡入动画(复用个人空间动效) */
.overlay-fade-enter-active,
.overlay-fade-leave-active {
transition: opacity 0.25s ease, backdrop-filter 0.25s ease;
}
.overlay-fade-enter-from,
.overlay-fade-leave-to {
opacity: 0;
backdrop-filter: blur(0);
}
.overlay-fade-enter-active > *:first-child,
.overlay-fade-leave-active > *:first-child {
transition: transform 0.25s ease, opacity 0.25s ease;
}
.overlay-fade-enter-from > *:first-child,
.overlay-fade-leave-to > *:first-child {
transform: translateY(18px) scale(0.985);
opacity: 0;
}
/* 彩蛋灌水特效 */ /* 彩蛋灌水特效 */
.easter-egg-overlay { .easter-egg-overlay {
position: fixed; position: fixed;

View File

@ -28,6 +28,131 @@ import logging
import hmac import hmac
import mimetypes import mimetypes
# ==========================================
# 回顾文件生成辅助
# ==========================================
def _sanitize_filename_component(text: str) -> str:
safe = (text or "untitled").strip()
safe = re.sub(r'[\\/:*?"<>|]+', '_', safe)
return safe or "untitled"
def build_review_lines(messages, limit=None):
"""
将对话消息序列拍平成简化文本
保留 user / assistant / system 以及 assistant 内的 tool 调用与 tool 消息
limit 为正整数时最多返回该数量的行用于预览
"""
lines = []
def append_line(text: str):
lines.append(text.rstrip())
def extract_text(content):
# content 可能是字符串、列表OpenAI 新结构)或字典
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
parts.append(item.get("text") or "")
elif isinstance(item, str):
parts.append(item)
return "".join(parts)
if isinstance(content, dict):
return content.get("text") or ""
return ""
def append_tool_call(name, args):
try:
args_text = json.dumps(args, ensure_ascii=False)
except Exception:
args_text = str(args)
append_line(f"tool_call{name} {args_text}")
for msg in messages or []:
role = msg.get("role")
base_content_raw = msg.get("content") if isinstance(msg.get("content"), (str, list, dict)) else msg.get("text") or ""
base_content = extract_text(base_content_raw)
if role in ("user", "assistant", "system"):
append_line(f"{role}{base_content}")
if role == "tool":
append_line(f"tool{extract_text(base_content_raw)}")
if role == "assistant":
# actions 格式
actions = msg.get("actions") or []
for action in actions:
if action.get("type") != "tool":
continue
tool = action.get("tool") or {}
name = tool.get("name") or "tool"
args = tool.get("arguments")
if args is None:
args = tool.get("argumentSnapshot")
try:
args_text = json.dumps(args, ensure_ascii=False)
except Exception:
args_text = str(args)
append_line(f"tool_call{name} {args_text}")
tool_content = tool.get("content")
if tool_content is None:
if isinstance(tool.get("result"), str):
tool_content = tool.get("result")
elif tool.get("result") is not None:
try:
tool_content = json.dumps(tool.get("result"), ensure_ascii=False)
except Exception:
tool_content = str(tool.get("result"))
elif tool.get("message"):
tool_content = tool.get("message")
else:
tool_content = ""
append_line(f"tool{tool_content}")
if isinstance(limit, int) and limit > 0 and len(lines) >= limit:
return lines[:limit]
# OpenAI 风格 tool_calls
tool_calls = msg.get("tool_calls") or []
for tc in tool_calls:
fn = tc.get("function") or {}
name = fn.get("name") or "tool"
args_raw = fn.get("arguments")
try:
args_obj = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
except Exception:
args_obj = args_raw
append_tool_call(name, args_obj)
# tool 结果在单独的 tool 消息
if isinstance(limit, int) and limit > 0 and len(lines) >= limit:
return lines[:limit]
# content 内嵌 tool_call部分供应商
if isinstance(base_content_raw, list):
for item in base_content_raw:
if isinstance(item, dict) and item.get("type") == "tool_call":
fn = item.get("function") or {}
name = fn.get("name") or "tool"
args_raw = fn.get("arguments")
try:
args_obj = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
except Exception:
args_obj = args_raw
append_tool_call(name, args_obj)
if isinstance(limit, int) and limit > 0 and len(lines) >= limit:
return lines[:limit]
if isinstance(limit, int) and limit > 0 and len(lines) >= limit:
return lines[:limit]
return lines if limit is None else lines[:limit]
# 控制台输出策略:默认静默,只保留简要事件 # 控制台输出策略:默认静默,只保留简要事件
_ORIGINAL_PRINT = print _ORIGINAL_PRINT = print
ENABLE_VERBOSE_CONSOLE = False ENABLE_VERBOSE_CONSOLE = False
@ -2950,6 +3075,99 @@ def duplicate_conversation(conversation_id, terminal: WebTerminal, workspace: Us
"message": "复制对话时发生异常" "message": "复制对话时发生异常"
}), 500 }), 500
@app.route('/api/conversations/<conversation_id>/review_preview', methods=['GET'])
@api_login_required
@with_terminal
def review_conversation_preview(conversation_id, terminal: WebTerminal, workspace: UserWorkspace, username: str):
"""生成对话回顾预览(不落盘,只返回前若干行文本)"""
try:
current_id = terminal.context_manager.current_conversation_id
if conversation_id == current_id:
return jsonify({
"success": False,
"message": "无法引用当前对话"
}), 400
conversation_data = terminal.context_manager.conversation_manager.load_conversation(conversation_id)
if not conversation_data:
return jsonify({
"success": False,
"error": "Conversation not found",
"message": f"对话 {conversation_id} 不存在"
}), 404
limit = request.args.get('limit', default=20, type=int) or 20
lines = build_review_lines(conversation_data.get("messages", []), limit=limit)
return jsonify({
"success": True,
"data": {
"preview": lines,
"count": len(lines)
}
})
except Exception as e:
print(f"[API] 对话回顾预览错误: {e}")
return jsonify({
"success": False,
"error": str(e),
"message": "生成预览时发生异常"
}), 500
@app.route('/api/conversations/<conversation_id>/review', methods=['POST'])
@api_login_required
@with_terminal
def review_conversation(conversation_id, terminal: WebTerminal, workspace: UserWorkspace, username: str):
"""生成完整对话回顾 Markdown 文件"""
try:
current_id = terminal.context_manager.current_conversation_id
if conversation_id == current_id:
return jsonify({
"success": False,
"message": "无法引用当前对话"
}), 400
conversation_data = terminal.context_manager.conversation_manager.load_conversation(conversation_id)
if not conversation_data:
return jsonify({
"success": False,
"error": "Conversation not found",
"message": f"对话 {conversation_id} 不存在"
}), 404
messages = conversation_data.get("messages", [])
lines = build_review_lines(messages)
content = "\n".join(lines) + "\n"
char_count = len(content)
uploads_dir = workspace.uploads_dir / "review"
uploads_dir.mkdir(parents=True, exist_ok=True)
title = conversation_data.get("title") or "untitled"
safe_title = _sanitize_filename_component(title)
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
filename = f"review_{safe_title}_{timestamp}.md"
target = uploads_dir / filename
target.write_text(content, encoding='utf-8')
return jsonify({
"success": True,
"data": {
"path": f"/user_upload/review/{filename}",
"char_count": char_count
}
})
except Exception as e:
print(f"[API] 对话回顾生成错误: {e}")
return jsonify({
"success": False,
"error": str(e),
"message": "生成对话回顾时发生异常"
}), 500
@app.route('/api/conversations/statistics', methods=['GET']) @app.route('/api/conversations/statistics', methods=['GET'])
@api_login_required @api_login_required
@with_terminal @with_terminal
@ -3907,6 +4125,9 @@ async def handle_task_with_sender(terminal: WebTerminal, workspace: UserWorkspac
debug_log(f"Chunk {chunk_count}: choices为空列表") debug_log(f"Chunk {chunk_count}: choices为空列表")
continue continue
choice = chunk["choices"][0] choice = chunk["choices"][0]
if not usage_info and isinstance(choice, dict) and choice.get("usage"):
# 兼容部分供应商将 usage 放在 choice 内的格式(例如部分 Kimi/Qwen 返回)
last_usage_payload = choice.get("usage")
delta = choice.get("delta", {}) delta = choice.get("delta", {})
finish_reason = choice.get("finish_reason") finish_reason = choice.get("finish_reason")
if finish_reason: if finish_reason: