JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(tools): fix file download history persistence and display issues on page refresh and session restore
haowenzhong199cbc350f6da
diff --git a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.pyindex b028fcf170..3ec523e5f6 100644--- a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py+++ b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py@@ -126,6 +126,7 @@ class SendFileToolkit:"mime_type": download_info["mime_type"],"download_url": download_info["download_url"],"download_token": download_info["download_token"],+ "expires_at": download_info.get("expires_at"),})except Exception as download_err:logger.warning(@@ -140,6 +141,21 @@ class SendFileToolkit:for file_path in valid_files]+ import time+ from jiuwenswarm.server.runtime.session.session_history import (+ append_history_record,+ )+ append_history_record(+ session_id=self.session_id,+ request_id=self.request_id,+ channel_id=self.channel_id,+ role="assistant",+ event_type="chat.file",+ content="",+ timestamp=time.time(),+ extra={"files": files_payload},+ )+msg = {"request_id": self.request_id,"channel_id": self.channel_id,diff --git a/jiuwenswarm/agents/harness/common/tools/web_file_download.py b/jiuwenswarm/agents/harness/common/tools/web_file_download.pyindex a6d1e7fca3..3c42c6b43f 100644--- a/jiuwenswarm/agents/harness/common/tools/web_file_download.py+++ b/jiuwenswarm/agents/harness/common/tools/web_file_download.py@@ -174,10 +174,13 @@ def build_file_download_info(if guessed_type:mime_type = guessed_type+ expires_at = int(time.time()) + expires_in+return {"name": file_name,"size": file_size,"mime_type": mime_type,"download_url": download_url,"download_token": token,+ "expires_at": expires_at,}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsxindex 88780bd6b5..bd75ec6ff1 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx@@ -747,7 +747,16 @@ function FileDownloadList({files: FileDownloadItem[];className?: string;}) {+ const { t } = useTranslation();++ const isExpired = (file: FileDownloadItem): boolean => {+ if (!file.expires_at) return false;+ return Date.now() / 1000 > file.expires_at;+ };+const handleDownload = async (file: FileDownloadItem) => {+ if (isExpired(file)) return;+// 检查是否在 PyWebView 环境中(exe 模式)const pywebviewApi = (window as Window & { pywebview?: { api?: { download_file?: (url: string, filename: string) => Promise<boolean> | boolean } } }).pywebview?.api;if (pywebviewApi?.download_file) {@@ -772,10 +781,16 @@ function FileDownloadList({{files.map((file, index) => {const typeConfig = getFileTypeConfig(file.mime_type, file.name);const ext = getFileExtension(file.name);+ const expired = isExpired(file);return (<divkey={`${file.name}-${index}`}- className="flex items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 hover:shadow-md hover:border-border-hover transition-all duration-fast cursor-pointer group"+ className={clsx(+ 'flex items-center gap-3 rounded-lg border px-3 py-2.5 transition-all duration-fast',+ expired+ ? 'border-border/50 bg-card/50 cursor-not-allowed opacity-60'+ : 'border-border bg-card hover:shadow-md hover:border-border-hover cursor-pointer group'+ )}onClick={() => handleDownload(file)}><div className={`flex-shrink-0 w-10 h-10 rounded-lg ${typeConfig.bg} flex items-center justify-center`}>@@ -792,14 +807,30 @@ function FileDownloadList({{ext || typeConfig.label}</span><span className="text-xs text-text-muted">{formatFileSize(file.size)}</span>+ {expired && (+ <span className="inline-flex items-center px-1 py-px rounded text-[10px] font-mono font-medium text-danger bg-danger/10 leading-none">+ {t('chatUi.fileExpired')}+ </span>+ )}</div></div><div- className="flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center text-text-muted group-hover:text-accent group-hover:bg-accent-subtle transition-colors duration-fast"+ className={clsx(+ 'flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center transition-colors duration-fast',+ expired+ ? 'text-text-muted/40'+ : 'text-text-muted group-hover:text-accent group-hover:bg-accent-subtle'+ )}>- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>- <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />- </svg>+ {expired ? (+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>+ <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />+ </svg>+ ) : (+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>+ <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />+ </svg>+ )}</div></div>);diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.tsindex 846ce4d576..5da53365dc 100644--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts@@ -1,4 +1,4 @@-import { Message, MessageRole, UsageSummary, WsEvent } from '../types';+import { Message, MessageRole, UsageSummary, FileDownloadItem, WsEvent } from '../types';import { webClient } from '../services/webClient';import { normalizeFinalContent } from '../utils/finalContent';@@ -11,6 +11,7 @@ const ALLOWED_ASSISTANT_EVENT_TYPES = new Set(['chat.tool_call','chat.tool_result','chat.usage_summary',+ 'chat.file','team.message','harness.message','harness.stage_result',@@ -46,6 +47,7 @@ type HistoryTimelineEntry =| { kind: 'tool_call'; at: string; payload: Record<string, unknown> }| { kind: 'tool_result'; at: string; payload: Record<string, unknown> }| { kind: 'usage_summary'; at: string; usage: UsageSummary }+ | { kind: 'file_items'; at: string; files: FileDownloadItem[] }| { kind: 'harness_message'; at: string; content: string; stage?: string }| { kind: 'harness_stage_result'; at: string; stage: string; status: string; error: string; messages: string[]; metrics: Record<string, unknown> };@@ -306,6 +308,19 @@ function parseHistoryTimelineEntry(return null;}+ if (eventType === 'chat.file') {+ const rawFiles = payload.files;+ if (!Array.isArray(rawFiles) || rawFiles.length === 0) {+ return null;+ }+ const files = rawFiles as FileDownloadItem[];+ return {+ kind: 'file_items',+ at,+ files,+ };+ }+if (eventType === 'harness.message') {const content = typeof payload.content === 'string' ? payload.content : '';const stage = typeof payload.stage === 'string' ? payload.stage : undefined;@@ -473,8 +488,13 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historconst messages: Message[] = [];const toolReplay: HistoryToolReplayItem[] = [];const harnessReplay: HistoryHarnessReplayItem[] = [];+ let pendingFileItems: FileDownloadItem[] | null = null;for (const e of entries) {if (e.kind === 'message') {+ if (e.message.role === 'assistant' && pendingFileItems) {+ e.message = { ...e.message, fileItems: pendingFileItems };+ pendingFileItems = null;+ }messages.push(e.message);} else if (e.kind === 'usage_summary') {for (let i = messages.length - 1; i >= 0; i--) {@@ -509,6 +529,8 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Histormetrics: e.metrics,},});+ } else if (e.kind === 'file_items') {+ pendingFileItems = e.files;} else {toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });}@@ -630,8 +652,13 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestoconst messages: Message[] = [];const toolReplay: HistoryToolReplayItem[] = [];const harnessReplay: HistoryHarnessReplayItem[] = [];+ let pendingFileItems: FileDownloadItem[] | null = null;for (const e of entries) {if (e.kind === 'message') {+ if (e.message.role === 'assistant' && pendingFileItems) {+ e.message = { ...e.message, fileItems: pendingFileItems };+ pendingFileItems = null;+ }messages.push(e.message);} else if (e.kind === 'usage_summary') {for (let i = messages.length - 1; i >= 0; i--) {@@ -665,6 +692,8 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestometrics: e.metrics,},});+ } else if (e.kind === 'file_items') {+ pendingFileItems = e.files;} else {toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 68b21b8eb9..bca45bdf70 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -1058,6 +1058,7 @@"copyMessage": "Copy message","stopReading": "Stop reading","readMessage": "Read message",+ "fileExpired": "Expired","parallelProgress": "Parallel tasks running ({{completedCount}}/{{total}} complete)","subtask": {"starting": "Starting...",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 8e29679c4d..d4096928e7 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -1057,6 +1057,7 @@"copyMessage": "复制消息","stopReading": "停止朗读","readMessage": "朗读消息",+ "fileExpired": "已过期","parallelProgress": "并行任务执行中 ({{completedCount}}/{{total}} 完成)","subtask": {"starting": "启动中...",diff --git a/jiuwenswarm/channels/web/frontend/src/types/message.ts b/jiuwenswarm/channels/web/frontend/src/types/message.tsindex 81fb728e82..d7ab575017 100644--- a/jiuwenswarm/channels/web/frontend/src/types/message.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/message.ts@@ -27,6 +27,7 @@ export interface FileDownloadItem {mime_type: string;download_url: string;download_token: string;+ expires_at?: number;}export interface ContextCompressionRuntime {diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex ab73988069..f8c5548f4d 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -88,6 +88,7 @@ _HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset("chat.tool_call","chat.tool_result","chat.usage_summary",+ "chat.file","team.message",})