mirror of
https://github.com/hicccc77/WeFlow.git
synced 2026-04-11 23:15:51 +00:00
Compare commits
2 Commits
aitest
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62161233ed | ||
|
|
67acb42163 |
66
.github/workflows/dev-daily-fixed.yml
vendored
66
.github/workflows/dev-daily-fixed.yml
vendored
@@ -60,23 +60,7 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
gh release create "$FIXED_DEV_TAG" --repo "$GITHUB_REPOSITORY" --title "Daily Dev Build" --notes "开发版发布页" --prerelease --target "$TARGET_BRANCH"
|
gh release create "$FIXED_DEV_TAG" --repo "$GITHUB_REPOSITORY" --title "Daily Dev Build" --notes "开发版发布页" --prerelease --target "$TARGET_BRANCH"
|
||||||
RELEASE_REST_ID="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_DEV_TAG" --jq '.id')"
|
RELEASE_REST_ID="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_DEV_TAG" --jq '.id')"
|
||||||
RELEASE_ENDPOINT="repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_DEV_TAG"
|
gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_REST_ID" -f draft=false -f prerelease=true >/dev/null
|
||||||
settled="false"
|
|
||||||
for i in 1 2 3 4 5; do
|
|
||||||
gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_REST_ID" -F draft=false -F prerelease=true >/dev/null 2>&1 || true
|
|
||||||
DRAFT_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.draft' 2>/dev/null || echo true)"
|
|
||||||
PRERELEASE_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.prerelease' 2>/dev/null || echo false)"
|
|
||||||
if [ "$DRAFT_STATE" = "false" ] && [ "$PRERELEASE_STATE" = "true" ]; then
|
|
||||||
settled="true"
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
if [ "$settled" != "true" ]; then
|
|
||||||
echo "Failed to settle release state after create:"
|
|
||||||
gh api "$RELEASE_ENDPOINT" --jq '{draft: .draft, prerelease: .prerelease, url: .html_url}'
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
dev-mac-arm64:
|
dev-mac-arm64:
|
||||||
needs: prepare
|
needs: prepare
|
||||||
@@ -97,22 +81,6 @@ jobs:
|
|||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
run: npm install
|
run: npm install
|
||||||
|
|
||||||
- name: Ensure mac key helpers are executable
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
for file in \
|
|
||||||
resources/key/macos/universal/xkey_helper \
|
|
||||||
resources/key/macos/universal/image_scan_helper \
|
|
||||||
resources/key/macos/universal/xkey_helper_macos \
|
|
||||||
resources/key/macos/universal/libwx_key.dylib
|
|
||||||
do
|
|
||||||
if [ -f "$file" ]; then
|
|
||||||
chmod +x "$file"
|
|
||||||
ls -l "$file"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: Set dev version
|
- name: Set dev version
|
||||||
shell: bash
|
shell: bash
|
||||||
run: npm version "${{ needs.prepare.outputs.dev_version }}" --no-git-tag-version --allow-same-version
|
run: npm version "${{ needs.prepare.outputs.dev_version }}" --no-git-tag-version --allow-same-version
|
||||||
@@ -302,25 +270,21 @@ jobs:
|
|||||||
- name: Update fixed dev release notes
|
- name: Update fixed dev release notes
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
FIXED_DEV_TAG: ${{ env.FIXED_DEV_TAG }}
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
TAG="${FIXED_DEV_TAG:-}"
|
TAG="$FIXED_DEV_TAG"
|
||||||
if [ -z "$TAG" ]; then
|
|
||||||
echo "FIXED_DEV_TAG is empty, abort."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
REPO="$GITHUB_REPOSITORY"
|
REPO="$GITHUB_REPOSITORY"
|
||||||
RELEASE_PAGE="https://github.com/$REPO/releases/tag/$TAG"
|
RELEASE_PAGE="https://github.com/$REPO/releases/tag/$TAG"
|
||||||
echo "Using release tag: $TAG"
|
|
||||||
|
|
||||||
if ! gh api "repos/$REPO/releases/tags/$TAG" >/dev/null 2>&1; then
|
if ! gh release view "$TAG" --repo "$REPO" >/dev/null 2>&1; then
|
||||||
echo "Release $TAG not found, skip notes update."
|
echo "Release $TAG not found, skip notes update."
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
ASSETS_JSON="$(gh api "repos/$REPO/releases/tags/$TAG")"
|
ASSETS_JSON="$(gh release view "$TAG" --repo "$REPO" --json assets)"
|
||||||
|
|
||||||
pick_asset() {
|
pick_asset() {
|
||||||
local pattern="$1"
|
local pattern="$1"
|
||||||
@@ -386,22 +350,4 @@ jobs:
|
|||||||
}
|
}
|
||||||
|
|
||||||
update_release_notes
|
update_release_notes
|
||||||
RELEASE_REST_ID="$(gh api "repos/$REPO/releases/tags/$TAG" --jq '.id')"
|
gh release view "$TAG" --repo "$REPO" --json isDraft,isPrerelease,url
|
||||||
RELEASE_ENDPOINT="repos/$REPO/releases/tags/$TAG"
|
|
||||||
settled="false"
|
|
||||||
for i in 1 2 3 4 5; do
|
|
||||||
gh api --method PATCH "repos/$REPO/releases/$RELEASE_REST_ID" -F draft=false -F prerelease=true >/dev/null 2>&1 || true
|
|
||||||
DRAFT_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.draft' 2>/dev/null || echo true)"
|
|
||||||
PRERELEASE_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.prerelease' 2>/dev/null || echo false)"
|
|
||||||
if [ "$DRAFT_STATE" = "false" ] && [ "$PRERELEASE_STATE" = "true" ]; then
|
|
||||||
settled="true"
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
if [ "$settled" != "true" ]; then
|
|
||||||
echo "Failed to settle release state after notes update:"
|
|
||||||
gh api "$RELEASE_ENDPOINT" --jq '{draft: .draft, prerelease: .prerelease, url: .html_url}'
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
gh api "repos/$REPO/releases/tags/$TAG" --jq '{isDraft: .draft, isPrerelease: .prerelease, url: .html_url}'
|
|
||||||
|
|||||||
65
.github/workflows/preview-nightly-main.yml
vendored
65
.github/workflows/preview-nightly-main.yml
vendored
@@ -86,23 +86,7 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
gh release create "$FIXED_PREVIEW_TAG" --repo "$GITHUB_REPOSITORY" --title "Preview Nightly Build" --notes "预览版发布页" --prerelease --target "$TARGET_BRANCH"
|
gh release create "$FIXED_PREVIEW_TAG" --repo "$GITHUB_REPOSITORY" --title "Preview Nightly Build" --notes "预览版发布页" --prerelease --target "$TARGET_BRANCH"
|
||||||
RELEASE_REST_ID="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_PREVIEW_TAG" --jq '.id')"
|
RELEASE_REST_ID="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_PREVIEW_TAG" --jq '.id')"
|
||||||
RELEASE_ENDPOINT="repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_PREVIEW_TAG"
|
gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_REST_ID" -f draft=false -f prerelease=true >/dev/null
|
||||||
settled="false"
|
|
||||||
for i in 1 2 3 4 5; do
|
|
||||||
gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_REST_ID" -F draft=false -F prerelease=true >/dev/null 2>&1 || true
|
|
||||||
DRAFT_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.draft' 2>/dev/null || echo true)"
|
|
||||||
PRERELEASE_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.prerelease' 2>/dev/null || echo false)"
|
|
||||||
if [ "$DRAFT_STATE" = "false" ] && [ "$PRERELEASE_STATE" = "true" ]; then
|
|
||||||
settled="true"
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
if [ "$settled" != "true" ]; then
|
|
||||||
echo "Failed to settle release state after create:"
|
|
||||||
gh api "$RELEASE_ENDPOINT" --jq '{draft: .draft, prerelease: .prerelease, url: .html_url}'
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
preview-mac-arm64:
|
preview-mac-arm64:
|
||||||
needs: prepare
|
needs: prepare
|
||||||
@@ -124,22 +108,6 @@ jobs:
|
|||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
run: npm install
|
run: npm install
|
||||||
|
|
||||||
- name: Ensure mac key helpers are executable
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
for file in \
|
|
||||||
resources/key/macos/universal/xkey_helper \
|
|
||||||
resources/key/macos/universal/image_scan_helper \
|
|
||||||
resources/key/macos/universal/xkey_helper_macos \
|
|
||||||
resources/key/macos/universal/libwx_key.dylib
|
|
||||||
do
|
|
||||||
if [ -f "$file" ]; then
|
|
||||||
chmod +x "$file"
|
|
||||||
ls -l "$file"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: Set preview version
|
- name: Set preview version
|
||||||
shell: bash
|
shell: bash
|
||||||
run: npm version "${{ needs.prepare.outputs.preview_version }}" --no-git-tag-version --allow-same-version
|
run: npm version "${{ needs.prepare.outputs.preview_version }}" --no-git-tag-version --allow-same-version
|
||||||
@@ -347,22 +315,17 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
TAG="${FIXED_PREVIEW_TAG:-}"
|
TAG="$FIXED_PREVIEW_TAG"
|
||||||
if [ -z "$TAG" ]; then
|
|
||||||
echo "FIXED_PREVIEW_TAG is empty, abort."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
CURRENT_PREVIEW_VERSION="${{ needs.prepare.outputs.preview_version }}"
|
CURRENT_PREVIEW_VERSION="${{ needs.prepare.outputs.preview_version }}"
|
||||||
REPO="$GITHUB_REPOSITORY"
|
REPO="$GITHUB_REPOSITORY"
|
||||||
RELEASE_PAGE="https://github.com/$REPO/releases/tag/$TAG"
|
RELEASE_PAGE="https://github.com/$REPO/releases/tag/$TAG"
|
||||||
echo "Using release tag: $TAG"
|
|
||||||
|
|
||||||
if ! gh api "repos/$REPO/releases/tags/$TAG" >/dev/null 2>&1; then
|
if ! gh release view "$TAG" --repo "$REPO" >/dev/null 2>&1; then
|
||||||
echo "Release $TAG not found (possibly all publish jobs failed), skip notes update."
|
echo "Release $TAG not found (possibly all publish jobs failed), skip notes update."
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
ASSETS_JSON="$(gh api "repos/$REPO/releases/tags/$TAG")"
|
ASSETS_JSON="$(gh release view "$TAG" --repo "$REPO" --json assets)"
|
||||||
|
|
||||||
pick_asset() {
|
pick_asset() {
|
||||||
local pattern="$1"
|
local pattern="$1"
|
||||||
@@ -429,22 +392,4 @@ jobs:
|
|||||||
}
|
}
|
||||||
|
|
||||||
update_release_notes
|
update_release_notes
|
||||||
RELEASE_REST_ID="$(gh api "repos/$REPO/releases/tags/$TAG" --jq '.id')"
|
gh release view "$TAG" --repo "$REPO" --json isDraft,isPrerelease,url
|
||||||
RELEASE_ENDPOINT="repos/$REPO/releases/tags/$TAG"
|
|
||||||
settled="false"
|
|
||||||
for i in 1 2 3 4 5; do
|
|
||||||
gh api --method PATCH "repos/$REPO/releases/$RELEASE_REST_ID" -F draft=false -F prerelease=true >/dev/null 2>&1 || true
|
|
||||||
DRAFT_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.draft' 2>/dev/null || echo true)"
|
|
||||||
PRERELEASE_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.prerelease' 2>/dev/null || echo false)"
|
|
||||||
if [ "$DRAFT_STATE" = "false" ] && [ "$PRERELEASE_STATE" = "true" ]; then
|
|
||||||
settled="true"
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
if [ "$settled" != "true" ]; then
|
|
||||||
echo "Failed to settle release state after notes update:"
|
|
||||||
gh api "$RELEASE_ENDPOINT" --jq '{draft: .draft, prerelease: .prerelease, url: .html_url}'
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
gh api "repos/$REPO/releases/tags/$TAG" --jq '{isDraft: .draft, isPrerelease: .prerelease, url: .html_url}'
|
|
||||||
|
|||||||
16
.github/workflows/release.yml
vendored
16
.github/workflows/release.yml
vendored
@@ -31,22 +31,6 @@ jobs:
|
|||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
run: npm install
|
run: npm install
|
||||||
|
|
||||||
- name: Ensure mac key helpers are executable
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
for file in \
|
|
||||||
resources/key/macos/universal/xkey_helper \
|
|
||||||
resources/key/macos/universal/image_scan_helper \
|
|
||||||
resources/key/macos/universal/xkey_helper_macos \
|
|
||||||
resources/key/macos/universal/libwx_key.dylib
|
|
||||||
do
|
|
||||||
if [ -f "$file" ]; then
|
|
||||||
chmod +x "$file"
|
|
||||||
ls -l "$file"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: Sync version with tag
|
- name: Sync version with tag
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
51
README.md
51
README.md
@@ -1,23 +1,34 @@
|
|||||||
# WeFlow
|
# WeFlow
|
||||||
|
|
||||||
WeFlow 是一个**完全本地**的微信**实时**聊天记录查看、分析与导出工具。它可以实时获取你的微信聊天记录并将其导出,还可以根据你的聊天记录为你生成独一无二的分析报告。
|
WeFlow 是一个**完全本地**的微信**实时**聊天记录查看、分析与导出工具。它可以实时获取你的微信聊天记录并将其导出,还可以根据你的聊天记录为你生成独一无二的分析报告
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="app.png" alt="WeFlow 应用预览" width="90%">
|
<img src="app.png" alt="WeFlow" width="90%">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<!-- 第一行修复样式 -->
|
<a href="https://github.com/hicccc77/WeFlow/stargazers">
|
||||||
<a href="https://github.com/hicccc77/WeFlow/stargazers"><img src="https://img.shields.io/github/stars/hicccc77/WeFlow?style=flat&label=Stars&labelColor=1F2937&color=2563EB" alt="Stargazers"></a>
|
<img src="https://img.shields.io/github/stars/hicccc77/WeFlow?style=flat-square" alt="Stargazers">
|
||||||
<a href="https://github.com/hicccc77/WeFlow/network/members"><img src="https://img.shields.io/github/forks/hicccc77/WeFlow?style=flat&label=Forks&labelColor=1F2937&color=7C3AED" alt="Forks"></a>
|
</a>
|
||||||
<a href="https://github.com/hicccc77/WeFlow/issues"><img src="https://img.shields.io/github/issues/hicccc77/WeFlow?style=flat&label=Issues&labelColor=1F2937&color=D97706" alt="Issues"></a>
|
<a href="https://github.com/hicccc77/WeFlow/network/members">
|
||||||
<a href="https://github.com/hicccc77/WeFlow/releases"><img src="https://img.shields.io/github/downloads/hicccc77/WeFlow/total?style=flat&label=Downloads&labelColor=1F2937&color=059669" alt="Downloads"></a>
|
<img src="https://img.shields.io/github/forks/hicccc77/WeFlow?style=flat-square" alt="Forks">
|
||||||
<br><br>
|
</a>
|
||||||
<!-- 第二行:电报矮一点(22px),排名高一点(32px),使用 vertical-align: middle 居中对齐 -->
|
<a href="https://github.com/hicccc77/WeFlow/issues">
|
||||||
<a href="https://t.me/weflow_cc"><img src="https://img.shields.io/badge/Telegram-频道-1D9BF0?style=flat&logo=telegram&logoColor=white&labelColor=1F2937&color=1D9BF0" alt="Telegram Channel" style="height: 22px; vertical-align: middle;"></a>
|
<img src="https://img.shields.io/github/issues/hicccc77/WeFlow?style=flat-square" alt="Issues">
|
||||||
<a href="https://www.star-history.com/hicccc77/weflow"><img src="https://api.star-history.com/badge?repo=hicccc77/WeFlow&theme=dark" alt="Star History Rank" style="height: 32px; vertical-align: middle;"></a>
|
</a>
|
||||||
|
<a href="https://github.com/hicccc77/WeFlow/releases">
|
||||||
|
<img src="https://img.shields.io/github/downloads/hicccc77/WeFlow/total?style=flat-square" alt="Downloads" />
|
||||||
|
</a>
|
||||||
|
<a href="https://t.me/weflow_cc">
|
||||||
|
<img src="https://img.shields.io/badge/Telegram%20频道-0088cc?style=flat-square&logo=telegram&logoColor=0088cc&labelColor=white" alt="Telegram">
|
||||||
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|
||||||
> [!TIP]
|
> [!TIP]
|
||||||
> 如果导出聊天记录后,想深入分析聊天内容可以试试 [ChatLab](https://chatlab.fun/)
|
> 如果导出聊天记录后,想深入分析聊天内容可以试试 [ChatLab](https://chatlab.fun/)
|
||||||
|
|
||||||
@@ -36,12 +47,14 @@ WeFlow 是一个**完全本地**的微信**实时**聊天记录查看、分析
|
|||||||
|
|
||||||
## 支持平台与设备
|
## 支持平台与设备
|
||||||
|
|
||||||
|
|
||||||
| 平台 | 设备/架构 | 安装包 |
|
| 平台 | 设备/架构 | 安装包 |
|
||||||
|------|----------|--------|
|
|------|----------|--------|
|
||||||
| Windows | Windows10+、x64(amd64) | `.exe` |
|
| Windows | Windows10+、x64(amd64) | `.exe` |
|
||||||
| macOS | Apple Silicon(M 系列,arm64) | `.dmg` |
|
| macOS | Apple Silicon(M 系列,arm64) | `.dmg` |
|
||||||
| Linux | x64 设备(amd64) | `.AppImage`、`.tar.gz` |
|
| Linux | x64 设备(amd64) | `.AppImage`、`.tar.gz` |
|
||||||
|
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
若你只想使用成品版本,可前往 [Releases](https://github.com/hicccc77/WeFlow/releases) 下载并安装。
|
若你只想使用成品版本,可前往 [Releases](https://github.com/hicccc77/WeFlow/releases) 下载并安装。
|
||||||
@@ -80,6 +93,7 @@ WeFlow 提供本地 HTTP API 服务,支持通过接口查询消息数据,可
|
|||||||
|
|
||||||
完整接口文档:[点击查看](docs/HTTP-API.md)
|
完整接口文档:[点击查看](docs/HTTP-API.md)
|
||||||
|
|
||||||
|
|
||||||
## 面向开发者
|
## 面向开发者
|
||||||
|
|
||||||
如果你想从源码构建或为项目贡献代码,请遵循以下步骤:
|
如果你想从源码构建或为项目贡献代码,请遵循以下步骤:
|
||||||
@@ -94,6 +108,7 @@ npm install
|
|||||||
|
|
||||||
# 3. 运行应用(开发模式)
|
# 3. 运行应用(开发模式)
|
||||||
npm run dev
|
npm run dev
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 致谢
|
## 致谢
|
||||||
@@ -105,16 +120,18 @@ npm run dev
|
|||||||
|
|
||||||
如果 WeFlow 确实帮到了你,可以考虑请我们喝杯咖啡:
|
如果 WeFlow 确实帮到了你,可以考虑请我们喝杯咖啡:
|
||||||
|
|
||||||
> TRC20 **Address:** `TZCtAw8CaeARWZBfvjidCnTcfnAtf6nvS6`
|
|
||||||
|
> TRC20 **Address:** `TZCtAw8CaeARWZBfvjidCnTcfnAtf6nvS6`
|
||||||
|
|
||||||
|
|
||||||
## Star History
|
## Star History
|
||||||
|
|
||||||
<a href="https://www.star-history.com/#hicccc77/WeFlow&type=date&legend=top-left">
|
<a href="https://www.star-history.com/#hicccc77/WeFlow&type=date&legend=top-left">
|
||||||
<picture>
|
<picture>
|
||||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&theme=dark&legend=top-left" />
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&theme=dark&legend=top-left" />
|
||||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&legend=top-left" />
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&legend=top-left" />
|
||||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&legend=top-left" />
|
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&legend=top-left" />
|
||||||
</picture>
|
</picture>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|||||||
201
electron/main.ts
201
electron/main.ts
@@ -31,10 +31,6 @@ import { destroyNotificationWindow, registerNotificationHandlers, showNotificati
|
|||||||
import { httpService } from './services/httpService'
|
import { httpService } from './services/httpService'
|
||||||
import { messagePushService } from './services/messagePushService'
|
import { messagePushService } from './services/messagePushService'
|
||||||
import { insightService } from './services/insightService'
|
import { insightService } from './services/insightService'
|
||||||
import { aiAnalysisService } from './services/aiAnalysisService'
|
|
||||||
import { aiAgentService } from './services/aiAgentService'
|
|
||||||
import { aiAssistantService } from './services/aiAssistantService'
|
|
||||||
import { aiSkillService } from './services/aiSkillService'
|
|
||||||
import { bizService } from './services/bizService'
|
import { bizService } from './services/bizService'
|
||||||
|
|
||||||
// 配置自动更新
|
// 配置自动更新
|
||||||
@@ -1602,14 +1598,6 @@ const runLegacySnsCacheMigration = async (
|
|||||||
return { copied, skipped, totalFiles: total }
|
return { copied, skipped, totalFiles: total }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function ensureAiSqlLabConnected(): Promise<{ success: boolean; error?: string }> {
|
|
||||||
const connectResult = await chatService.connect()
|
|
||||||
if (!connectResult.success) {
|
|
||||||
return { success: false, error: connectResult.error || '数据库未连接' }
|
|
||||||
}
|
|
||||||
return { success: true }
|
|
||||||
}
|
|
||||||
|
|
||||||
// 注册 IPC 处理器
|
// 注册 IPC 处理器
|
||||||
function registerIpcHandlers() {
|
function registerIpcHandlers() {
|
||||||
registerNotificationHandlers()
|
registerNotificationHandlers()
|
||||||
@@ -1647,180 +1635,6 @@ function registerIpcHandlers() {
|
|||||||
return insightService.triggerTest()
|
return insightService.triggerTest()
|
||||||
})
|
})
|
||||||
|
|
||||||
ipcMain.handle('insight:generateFootprintInsight', async (_, payload: {
|
|
||||||
rangeLabel: string
|
|
||||||
summary: {
|
|
||||||
private_inbound_people?: number
|
|
||||||
private_replied_people?: number
|
|
||||||
private_outbound_people?: number
|
|
||||||
private_reply_rate?: number
|
|
||||||
mention_count?: number
|
|
||||||
mention_group_count?: number
|
|
||||||
}
|
|
||||||
privateSegments?: Array<{ displayName?: string; session_id?: string; incoming_count?: number; outgoing_count?: number; message_count?: number; replied?: boolean }>
|
|
||||||
mentionGroups?: Array<{ displayName?: string; session_id?: string; count?: number }>
|
|
||||||
}) => {
|
|
||||||
return insightService.generateFootprintInsight(payload)
|
|
||||||
})
|
|
||||||
|
|
||||||
// ==================== AI Analysis V2 ====================
|
|
||||||
ipcMain.handle('ai:listConversations', async (_, payload?: { page?: number; pageSize?: number }) =>
|
|
||||||
aiAnalysisService.listConversations(payload?.page, payload?.pageSize)
|
|
||||||
)
|
|
||||||
ipcMain.handle('ai:createConversation', async (_, payload?: { title?: string }) =>
|
|
||||||
aiAnalysisService.createConversation(payload?.title || '')
|
|
||||||
)
|
|
||||||
ipcMain.handle('ai:renameConversation', async (_, payload: { conversationId: string; title: string }) =>
|
|
||||||
aiAnalysisService.renameConversation(payload.conversationId, payload.title)
|
|
||||||
)
|
|
||||||
ipcMain.handle('ai:deleteConversation', async (_, conversationId: string) =>
|
|
||||||
aiAnalysisService.deleteConversation(conversationId)
|
|
||||||
)
|
|
||||||
ipcMain.handle('ai:listMessages', async (_, payload: { conversationId: string; limit?: number }) =>
|
|
||||||
aiAnalysisService.listMessages(payload.conversationId, payload.limit)
|
|
||||||
)
|
|
||||||
ipcMain.handle('ai:exportConversation', async (_, payload: { conversationId: string }) =>
|
|
||||||
aiAnalysisService.exportConversation(payload.conversationId)
|
|
||||||
)
|
|
||||||
ipcMain.handle('ai:getToolCatalog', async () => aiAnalysisService.getToolCatalog())
|
|
||||||
ipcMain.handle('ai:executeTool', async (_, payload: { name: string; args?: Record<string, any> }) =>
|
|
||||||
aiAnalysisService.executeTool(payload.name, payload.args || {})
|
|
||||||
)
|
|
||||||
ipcMain.handle('ai:cancelToolTest', async (_, payload?: { taskId?: string }) =>
|
|
||||||
aiAnalysisService.cancelToolTest(payload?.taskId)
|
|
||||||
)
|
|
||||||
|
|
||||||
ipcMain.handle('agent:runStream', async (event, payload: {
|
|
||||||
mode?: 'chat' | 'sql'
|
|
||||||
conversationId?: string
|
|
||||||
userInput: string
|
|
||||||
assistantId?: string
|
|
||||||
activeSkillId?: string
|
|
||||||
chatScope?: 'group' | 'private'
|
|
||||||
sqlContext?: { schemaText?: string; targetHint?: string }
|
|
||||||
}) => {
|
|
||||||
return aiAgentService.runStream(payload, {
|
|
||||||
onChunk: (chunk) => {
|
|
||||||
try {
|
|
||||||
event.sender.send('agent:stream', chunk)
|
|
||||||
} catch {
|
|
||||||
// ignore sender errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
ipcMain.handle('agent:abort', async (_, payload: { runId?: string; conversationId?: string }) =>
|
|
||||||
aiAgentService.abort(payload || {})
|
|
||||||
)
|
|
||||||
|
|
||||||
ipcMain.handle('assistant:getAll', async () => aiAssistantService.getAll())
|
|
||||||
ipcMain.handle('assistant:getConfig', async (_, id: string) => aiAssistantService.getConfig(id))
|
|
||||||
ipcMain.handle('assistant:create', async (_, payload: any) => aiAssistantService.create(payload || {}))
|
|
||||||
ipcMain.handle('assistant:update', async (_, payload: { id: string; updates: any }) =>
|
|
||||||
aiAssistantService.update(payload.id, payload.updates || {})
|
|
||||||
)
|
|
||||||
ipcMain.handle('assistant:delete', async (_, id: string) => aiAssistantService.delete(id))
|
|
||||||
ipcMain.handle('assistant:reset', async (_, id: string) => aiAssistantService.reset(id))
|
|
||||||
ipcMain.handle('assistant:getBuiltinCatalog', async () => aiAssistantService.getBuiltinCatalog())
|
|
||||||
ipcMain.handle('assistant:getBuiltinToolCatalog', async () => aiAssistantService.getBuiltinToolCatalog())
|
|
||||||
ipcMain.handle('assistant:importFromMd', async (_, rawMd: string) => aiAssistantService.importFromMd(rawMd))
|
|
||||||
|
|
||||||
ipcMain.handle('skill:getAll', async () => aiSkillService.getAll())
|
|
||||||
ipcMain.handle('skill:getConfig', async (_, id: string) => aiSkillService.getConfig(id))
|
|
||||||
ipcMain.handle('skill:create', async (_, rawMd: string) => aiSkillService.create(rawMd))
|
|
||||||
ipcMain.handle('skill:update', async (_, payload: { id: string; rawMd: string }) =>
|
|
||||||
aiSkillService.update(payload.id, payload.rawMd)
|
|
||||||
)
|
|
||||||
ipcMain.handle('skill:delete', async (_, id: string) => aiSkillService.delete(id))
|
|
||||||
ipcMain.handle('skill:getBuiltinCatalog', async () => aiSkillService.getBuiltinCatalog())
|
|
||||||
ipcMain.handle('skill:importFromMd', async (_, rawMd: string) => aiSkillService.importFromMd(rawMd))
|
|
||||||
|
|
||||||
ipcMain.handle('llm:getConfig', async () => ({
|
|
||||||
success: true,
|
|
||||||
config: {
|
|
||||||
apiBaseUrl: String(configService?.get('aiModelApiBaseUrl') || ''),
|
|
||||||
apiKey: String(configService?.get('aiModelApiKey') || ''),
|
|
||||||
model: String(configService?.get('aiModelApiModel') || 'gpt-4o-mini')
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
ipcMain.handle('llm:setConfig', async (_, payload: { apiBaseUrl?: string; apiKey?: string; model?: string }) => {
|
|
||||||
if (typeof payload?.apiBaseUrl === 'string') configService?.set('aiModelApiBaseUrl', payload.apiBaseUrl)
|
|
||||||
if (typeof payload?.apiKey === 'string') configService?.set('aiModelApiKey', payload.apiKey)
|
|
||||||
if (typeof payload?.model === 'string') configService?.set('aiModelApiModel', payload.model)
|
|
||||||
return { success: true }
|
|
||||||
})
|
|
||||||
ipcMain.handle('llm:listModels', async () => ({
|
|
||||||
success: true,
|
|
||||||
models: [
|
|
||||||
{ id: 'gpt-4o-mini', label: 'gpt-4o-mini' },
|
|
||||||
{ id: 'gpt-4o', label: 'gpt-4o' },
|
|
||||||
{ id: 'gpt-5-mini', label: 'gpt-5-mini' }
|
|
||||||
]
|
|
||||||
}))
|
|
||||||
|
|
||||||
ipcMain.handle('chat:getSchema', async (_, payload?: { sessionId?: string }) => {
|
|
||||||
const connectResult = await ensureAiSqlLabConnected()
|
|
||||||
if (!connectResult.success) {
|
|
||||||
return { success: false, error: connectResult.error || '数据库未连接' }
|
|
||||||
}
|
|
||||||
return wcdbService.sqlLabGetSchema(payload)
|
|
||||||
})
|
|
||||||
ipcMain.handle('chat:executeSQL', async (_, payload: {
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path?: string | null
|
|
||||||
sql: string
|
|
||||||
limit?: number
|
|
||||||
}) => {
|
|
||||||
const connectResult = await ensureAiSqlLabConnected()
|
|
||||||
if (!connectResult.success) {
|
|
||||||
return { success: false, error: connectResult.error || '数据库未连接' }
|
|
||||||
}
|
|
||||||
return wcdbService.sqlLabExecuteReadonly(payload)
|
|
||||||
})
|
|
||||||
|
|
||||||
// 兼容层:旧 aiAnalysis API 转调新实现
|
|
||||||
ipcMain.handle('aiAnalysis:listConversations', async (_, payload?: { page?: number; pageSize?: number }) =>
|
|
||||||
aiAnalysisService.listConversations(payload?.page, payload?.pageSize)
|
|
||||||
)
|
|
||||||
ipcMain.handle('aiAnalysis:createConversation', async (_, payload?: { title?: string }) =>
|
|
||||||
aiAnalysisService.createConversation(payload?.title || '')
|
|
||||||
)
|
|
||||||
ipcMain.handle('aiAnalysis:deleteConversation', async (_, conversationId: string) =>
|
|
||||||
aiAnalysisService.deleteConversation(conversationId)
|
|
||||||
)
|
|
||||||
ipcMain.handle('aiAnalysis:listMessages', async (_, payload: { conversationId: string; limit?: number }) =>
|
|
||||||
aiAnalysisService.listMessages(payload.conversationId, payload.limit)
|
|
||||||
)
|
|
||||||
ipcMain.handle('aiAnalysis:sendMessage', async (event, payload: {
|
|
||||||
conversationId: string
|
|
||||||
userInput: string
|
|
||||||
options?: { parentMessageId?: string; persistUserMessage?: boolean; assistantId?: string; activeSkillId?: string }
|
|
||||||
}) =>
|
|
||||||
aiAnalysisService.sendMessage(payload.conversationId, payload.userInput, payload.options, {
|
|
||||||
onRunEvent: (runEvent) => {
|
|
||||||
try {
|
|
||||||
event.sender.send('aiAnalysis:runEvent', runEvent)
|
|
||||||
} catch {
|
|
||||||
// ignore sender errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
)
|
|
||||||
ipcMain.handle('aiAnalysis:retryMessage', async (event, payload: { conversationId: string; userMessageId?: string }) =>
|
|
||||||
aiAnalysisService.retryMessage(payload, {
|
|
||||||
onRunEvent: (runEvent) => {
|
|
||||||
try {
|
|
||||||
event.sender.send('aiAnalysis:runEvent', runEvent)
|
|
||||||
} catch {
|
|
||||||
// ignore sender errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
)
|
|
||||||
ipcMain.handle('aiAnalysis:abortRun', async (_, payload: { runId?: string; conversationId?: string }) =>
|
|
||||||
aiAnalysisService.abortRun(payload || {})
|
|
||||||
)
|
|
||||||
|
|
||||||
ipcMain.handle('config:clear', async () => {
|
ipcMain.handle('config:clear', async () => {
|
||||||
if (isLaunchAtStartupSupported() && getSystemLaunchAtStartup()) {
|
if (isLaunchAtStartupSupported() && getSystemLaunchAtStartup()) {
|
||||||
const result = setSystemLaunchAtStartup(false)
|
const result = setSystemLaunchAtStartup(false)
|
||||||
@@ -2549,21 +2363,6 @@ function registerIpcHandlers() {
|
|||||||
return chatService.searchMessages(keyword, sessionId, limit, offset, beginTimestamp, endTimestamp)
|
return chatService.searchMessages(keyword, sessionId, limit, offset, beginTimestamp, endTimestamp)
|
||||||
})
|
})
|
||||||
|
|
||||||
ipcMain.handle('chat:getMyFootprintStats', async (_, beginTimestamp: number, endTimestamp: number, options?: {
|
|
||||||
myWxid?: string
|
|
||||||
privateSessionIds?: string[]
|
|
||||||
groupSessionIds?: string[]
|
|
||||||
mentionLimit?: number
|
|
||||||
privateLimit?: number
|
|
||||||
mentionMode?: 'text_at_me' | string
|
|
||||||
}) => {
|
|
||||||
return chatService.getMyFootprintStats(beginTimestamp, endTimestamp, options)
|
|
||||||
})
|
|
||||||
|
|
||||||
ipcMain.handle('chat:exportMyFootprint', async (_, beginTimestamp: number, endTimestamp: number, format: 'csv' | 'json', filePath: string) => {
|
|
||||||
return chatService.exportMyFootprint(beginTimestamp, endTimestamp, format, filePath)
|
|
||||||
})
|
|
||||||
|
|
||||||
ipcMain.handle('sns:getTimeline', async (_, limit: number, offset: number, usernames?: string[], keyword?: string, startTime?: number, endTime?: number) => {
|
ipcMain.handle('sns:getTimeline', async (_, limit: number, offset: number, usernames?: string[], keyword?: string, startTime?: number, endTime?: number) => {
|
||||||
return snsService.getTimeline(limit, offset, usernames, keyword, startTime, endTime)
|
return snsService.getTimeline(limit, offset, usernames, keyword, startTime, endTime)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -258,31 +258,6 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
ipcRenderer.invoke('chat:getMessage', sessionId, localId),
|
ipcRenderer.invoke('chat:getMessage', sessionId, localId),
|
||||||
searchMessages: (keyword: string, sessionId?: string, limit?: number, offset?: number, beginTimestamp?: number, endTimestamp?: number) =>
|
searchMessages: (keyword: string, sessionId?: string, limit?: number, offset?: number, beginTimestamp?: number, endTimestamp?: number) =>
|
||||||
ipcRenderer.invoke('chat:searchMessages', keyword, sessionId, limit, offset, beginTimestamp, endTimestamp),
|
ipcRenderer.invoke('chat:searchMessages', keyword, sessionId, limit, offset, beginTimestamp, endTimestamp),
|
||||||
getMyFootprintStats: (
|
|
||||||
beginTimestamp: number,
|
|
||||||
endTimestamp: number,
|
|
||||||
options?: {
|
|
||||||
myWxid?: string
|
|
||||||
privateSessionIds?: string[]
|
|
||||||
groupSessionIds?: string[]
|
|
||||||
mentionLimit?: number
|
|
||||||
privateLimit?: number
|
|
||||||
mentionMode?: 'text_at_me' | string
|
|
||||||
}
|
|
||||||
) => ipcRenderer.invoke('chat:getMyFootprintStats', beginTimestamp, endTimestamp, options),
|
|
||||||
exportMyFootprint: (
|
|
||||||
beginTimestamp: number,
|
|
||||||
endTimestamp: number,
|
|
||||||
format: 'csv' | 'json',
|
|
||||||
filePath: string
|
|
||||||
) => ipcRenderer.invoke('chat:exportMyFootprint', beginTimestamp, endTimestamp, format, filePath),
|
|
||||||
getSchema: (payload?: { sessionId?: string }) => ipcRenderer.invoke('chat:getSchema', payload),
|
|
||||||
executeSQL: (payload: {
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path?: string | null
|
|
||||||
sql: string
|
|
||||||
limit?: number
|
|
||||||
}) => ipcRenderer.invoke('chat:executeSQL', payload),
|
|
||||||
onWcdbChange: (callback: (event: any, data: { type: string; json: string }) => void) => {
|
onWcdbChange: (callback: (event: any, data: { type: string; json: string }) => void) => {
|
||||||
ipcRenderer.on('wcdb-change', callback)
|
ipcRenderer.on('wcdb-change', callback)
|
||||||
return () => ipcRenderer.removeListener('wcdb-change', callback)
|
return () => ipcRenderer.removeListener('wcdb-change', callback)
|
||||||
@@ -533,188 +508,6 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
insight: {
|
insight: {
|
||||||
testConnection: () => ipcRenderer.invoke('insight:testConnection'),
|
testConnection: () => ipcRenderer.invoke('insight:testConnection'),
|
||||||
getTodayStats: () => ipcRenderer.invoke('insight:getTodayStats'),
|
getTodayStats: () => ipcRenderer.invoke('insight:getTodayStats'),
|
||||||
triggerTest: () => ipcRenderer.invoke('insight:triggerTest'),
|
triggerTest: () => ipcRenderer.invoke('insight:triggerTest')
|
||||||
generateFootprintInsight: (payload: {
|
|
||||||
rangeLabel: string
|
|
||||||
summary: {
|
|
||||||
private_inbound_people?: number
|
|
||||||
private_replied_people?: number
|
|
||||||
private_outbound_people?: number
|
|
||||||
private_reply_rate?: number
|
|
||||||
mention_count?: number
|
|
||||||
mention_group_count?: number
|
|
||||||
}
|
|
||||||
privateSegments?: Array<{ displayName?: string; session_id?: string; incoming_count?: number; outgoing_count?: number; message_count?: number; replied?: boolean }>
|
|
||||||
mentionGroups?: Array<{ displayName?: string; session_id?: string; count?: number }>
|
|
||||||
}) => ipcRenderer.invoke('insight:generateFootprintInsight', payload)
|
|
||||||
},
|
|
||||||
|
|
||||||
aiApi: {
|
|
||||||
listConversations: (payload?: { page?: number; pageSize?: number }) =>
|
|
||||||
ipcRenderer.invoke('ai:listConversations', payload),
|
|
||||||
createConversation: (payload?: { title?: string }) =>
|
|
||||||
ipcRenderer.invoke('ai:createConversation', payload),
|
|
||||||
renameConversation: (payload: { conversationId: string; title: string }) =>
|
|
||||||
ipcRenderer.invoke('ai:renameConversation', payload),
|
|
||||||
deleteConversation: (conversationId: string) =>
|
|
||||||
ipcRenderer.invoke('ai:deleteConversation', conversationId),
|
|
||||||
listMessages: (payload: { conversationId: string; limit?: number }) =>
|
|
||||||
ipcRenderer.invoke('ai:listMessages', payload),
|
|
||||||
exportConversation: (payload: { conversationId: string }) =>
|
|
||||||
ipcRenderer.invoke('ai:exportConversation', payload),
|
|
||||||
getToolCatalog: () => ipcRenderer.invoke('ai:getToolCatalog'),
|
|
||||||
executeTool: (payload: { name: string; args?: Record<string, any> }) =>
|
|
||||||
ipcRenderer.invoke('ai:executeTool', payload),
|
|
||||||
cancelToolTest: (payload?: { taskId?: string }) =>
|
|
||||||
ipcRenderer.invoke('ai:cancelToolTest', payload)
|
|
||||||
},
|
|
||||||
|
|
||||||
agentApi: {
|
|
||||||
runStream: (payload: {
|
|
||||||
mode?: 'chat' | 'sql'
|
|
||||||
conversationId?: string
|
|
||||||
userInput: string
|
|
||||||
assistantId?: string
|
|
||||||
activeSkillId?: string
|
|
||||||
chatScope?: 'group' | 'private'
|
|
||||||
sqlContext?: { schemaText?: string; targetHint?: string }
|
|
||||||
}) => ipcRenderer.invoke('agent:runStream', payload),
|
|
||||||
abort: (payload: { runId?: string; conversationId?: string }) =>
|
|
||||||
ipcRenderer.invoke('agent:abort', payload),
|
|
||||||
onStream: (callback: (payload: any) => void) => {
|
|
||||||
const listener = (_: unknown, payload: any) => callback(payload)
|
|
||||||
ipcRenderer.on('agent:stream', listener)
|
|
||||||
return () => ipcRenderer.removeListener('agent:stream', listener)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
assistantApi: {
|
|
||||||
getAll: () => ipcRenderer.invoke('assistant:getAll'),
|
|
||||||
getConfig: (id: string) => ipcRenderer.invoke('assistant:getConfig', id),
|
|
||||||
create: (payload: any) => ipcRenderer.invoke('assistant:create', payload),
|
|
||||||
update: (payload: { id: string; updates: any }) => ipcRenderer.invoke('assistant:update', payload),
|
|
||||||
delete: (id: string) => ipcRenderer.invoke('assistant:delete', id),
|
|
||||||
reset: (id: string) => ipcRenderer.invoke('assistant:reset', id),
|
|
||||||
getBuiltinCatalog: () => ipcRenderer.invoke('assistant:getBuiltinCatalog'),
|
|
||||||
getBuiltinToolCatalog: () => ipcRenderer.invoke('assistant:getBuiltinToolCatalog'),
|
|
||||||
importFromMd: (rawMd: string) => ipcRenderer.invoke('assistant:importFromMd', rawMd)
|
|
||||||
},
|
|
||||||
|
|
||||||
skillApi: {
|
|
||||||
getAll: () => ipcRenderer.invoke('skill:getAll'),
|
|
||||||
getConfig: (id: string) => ipcRenderer.invoke('skill:getConfig', id),
|
|
||||||
create: (rawMd: string) => ipcRenderer.invoke('skill:create', rawMd),
|
|
||||||
update: (payload: { id: string; rawMd: string }) => ipcRenderer.invoke('skill:update', payload),
|
|
||||||
delete: (id: string) => ipcRenderer.invoke('skill:delete', id),
|
|
||||||
getBuiltinCatalog: () => ipcRenderer.invoke('skill:getBuiltinCatalog'),
|
|
||||||
importFromMd: (rawMd: string) => ipcRenderer.invoke('skill:importFromMd', rawMd)
|
|
||||||
},
|
|
||||||
|
|
||||||
llmApi: {
|
|
||||||
getConfig: () => ipcRenderer.invoke('llm:getConfig'),
|
|
||||||
setConfig: (payload: { apiBaseUrl?: string; apiKey?: string; model?: string }) =>
|
|
||||||
ipcRenderer.invoke('llm:setConfig', payload),
|
|
||||||
listModels: () => ipcRenderer.invoke('llm:listModels')
|
|
||||||
},
|
|
||||||
|
|
||||||
aiAnalysis: {
|
|
||||||
listConversations: (payload?: { page?: number; pageSize?: number }) =>
|
|
||||||
ipcRenderer.invoke('aiAnalysis:listConversations', payload),
|
|
||||||
createConversation: (payload?: { title?: string }) =>
|
|
||||||
ipcRenderer.invoke('aiAnalysis:createConversation', payload),
|
|
||||||
deleteConversation: (conversationId: string) =>
|
|
||||||
ipcRenderer.invoke('aiAnalysis:deleteConversation', conversationId),
|
|
||||||
listMessages: (payload: { conversationId: string; limit?: number }) =>
|
|
||||||
ipcRenderer.invoke('aiAnalysis:listMessages', payload),
|
|
||||||
sendMessage: (payload: {
|
|
||||||
conversationId: string
|
|
||||||
userInput: string
|
|
||||||
options?: {
|
|
||||||
parentMessageId?: string
|
|
||||||
persistUserMessage?: boolean
|
|
||||||
assistantId?: string
|
|
||||||
activeSkillId?: string
|
|
||||||
chatScope?: 'group' | 'private'
|
|
||||||
}
|
|
||||||
}) => ipcRenderer.invoke('aiAnalysis:sendMessage', payload),
|
|
||||||
retryMessage: (payload: { conversationId: string; userMessageId?: string }) =>
|
|
||||||
ipcRenderer.invoke('aiAnalysis:retryMessage', payload),
|
|
||||||
abortRun: (payload: { runId?: string; conversationId?: string }) =>
|
|
||||||
ipcRenderer.invoke('aiAnalysis:abortRun', payload),
|
|
||||||
onRunEvent: (callback: (payload: {
|
|
||||||
runId: string
|
|
||||||
conversationId: string
|
|
||||||
stage: string
|
|
||||||
ts: number
|
|
||||||
message: string
|
|
||||||
intent?: string
|
|
||||||
round?: number
|
|
||||||
toolName?: string
|
|
||||||
status?: string
|
|
||||||
durationMs?: number
|
|
||||||
data?: Record<string, unknown>
|
|
||||||
}) => void) => {
|
|
||||||
const listener = (_: unknown, payload: any) => callback(payload)
|
|
||||||
ipcRenderer.on('aiAnalysis:runEvent', listener)
|
|
||||||
return () => ipcRenderer.removeListener('aiAnalysis:runEvent', listener)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('aiApi', {
|
|
||||||
listConversations: (payload?: { page?: number; pageSize?: number }) => ipcRenderer.invoke('ai:listConversations', payload),
|
|
||||||
createConversation: (payload?: { title?: string }) => ipcRenderer.invoke('ai:createConversation', payload),
|
|
||||||
renameConversation: (payload: { conversationId: string; title: string }) => ipcRenderer.invoke('ai:renameConversation', payload),
|
|
||||||
deleteConversation: (conversationId: string) => ipcRenderer.invoke('ai:deleteConversation', conversationId),
|
|
||||||
listMessages: (payload: { conversationId: string; limit?: number }) => ipcRenderer.invoke('ai:listMessages', payload),
|
|
||||||
exportConversation: (payload: { conversationId: string }) => ipcRenderer.invoke('ai:exportConversation', payload),
|
|
||||||
getToolCatalog: () => ipcRenderer.invoke('ai:getToolCatalog'),
|
|
||||||
executeTool: (payload: { name: string; args?: Record<string, any> }) => ipcRenderer.invoke('ai:executeTool', payload),
|
|
||||||
cancelToolTest: (payload?: { taskId?: string }) => ipcRenderer.invoke('ai:cancelToolTest', payload)
|
|
||||||
})
|
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('agentApi', {
|
|
||||||
runStream: (payload: {
|
|
||||||
mode?: 'chat' | 'sql'
|
|
||||||
conversationId?: string
|
|
||||||
userInput: string
|
|
||||||
assistantId?: string
|
|
||||||
activeSkillId?: string
|
|
||||||
chatScope?: 'group' | 'private'
|
|
||||||
sqlContext?: { schemaText?: string; targetHint?: string }
|
|
||||||
}) => ipcRenderer.invoke('agent:runStream', payload),
|
|
||||||
abort: (payload: { runId?: string; conversationId?: string }) => ipcRenderer.invoke('agent:abort', payload),
|
|
||||||
onStream: (callback: (payload: any) => void) => {
|
|
||||||
const listener = (_: unknown, payload: any) => callback(payload)
|
|
||||||
ipcRenderer.on('agent:stream', listener)
|
|
||||||
return () => ipcRenderer.removeListener('agent:stream', listener)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('assistantApi', {
|
|
||||||
getAll: () => ipcRenderer.invoke('assistant:getAll'),
|
|
||||||
getConfig: (id: string) => ipcRenderer.invoke('assistant:getConfig', id),
|
|
||||||
create: (payload: any) => ipcRenderer.invoke('assistant:create', payload),
|
|
||||||
update: (payload: { id: string; updates: any }) => ipcRenderer.invoke('assistant:update', payload),
|
|
||||||
delete: (id: string) => ipcRenderer.invoke('assistant:delete', id),
|
|
||||||
reset: (id: string) => ipcRenderer.invoke('assistant:reset', id),
|
|
||||||
getBuiltinCatalog: () => ipcRenderer.invoke('assistant:getBuiltinCatalog'),
|
|
||||||
getBuiltinToolCatalog: () => ipcRenderer.invoke('assistant:getBuiltinToolCatalog'),
|
|
||||||
importFromMd: (rawMd: string) => ipcRenderer.invoke('assistant:importFromMd', rawMd)
|
|
||||||
})
|
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('skillApi', {
|
|
||||||
getAll: () => ipcRenderer.invoke('skill:getAll'),
|
|
||||||
getConfig: (id: string) => ipcRenderer.invoke('skill:getConfig', id),
|
|
||||||
create: (rawMd: string) => ipcRenderer.invoke('skill:create', rawMd),
|
|
||||||
update: (payload: { id: string; rawMd: string }) => ipcRenderer.invoke('skill:update', payload),
|
|
||||||
delete: (id: string) => ipcRenderer.invoke('skill:delete', id),
|
|
||||||
getBuiltinCatalog: () => ipcRenderer.invoke('skill:getBuiltinCatalog'),
|
|
||||||
importFromMd: (rawMd: string) => ipcRenderer.invoke('skill:importFromMd', rawMd)
|
|
||||||
})
|
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('llmApi', {
|
|
||||||
getConfig: () => ipcRenderer.invoke('llm:getConfig'),
|
|
||||||
setConfig: (payload: { apiBaseUrl?: string; apiKey?: string; model?: string }) => ipcRenderer.invoke('llm:setConfig', payload),
|
|
||||||
listModels: () => ipcRenderer.invoke('llm:listModels')
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,450 +0,0 @@
|
|||||||
import http from 'http'
|
|
||||||
import https from 'https'
|
|
||||||
import { randomUUID } from 'crypto'
|
|
||||||
import { URL } from 'url'
|
|
||||||
import { ConfigService } from './config'
|
|
||||||
import { aiAnalysisService, type AiAnalysisRunEvent } from './aiAnalysisService'
|
|
||||||
|
|
||||||
export interface TokenUsage {
|
|
||||||
promptTokens?: number
|
|
||||||
completionTokens?: number
|
|
||||||
totalTokens?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AgentRuntimeStatus {
|
|
||||||
phase: 'idle' | 'thinking' | 'tool_running' | 'responding' | 'completed' | 'error' | 'aborted'
|
|
||||||
round?: number
|
|
||||||
currentTool?: string
|
|
||||||
toolsUsed?: number
|
|
||||||
updatedAt: number
|
|
||||||
totalUsage?: TokenUsage
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AgentStreamChunk {
|
|
||||||
runId: string
|
|
||||||
conversationId?: string
|
|
||||||
type: 'content' | 'think' | 'tool_start' | 'tool_result' | 'status' | 'done' | 'error'
|
|
||||||
content?: string
|
|
||||||
thinkTag?: string
|
|
||||||
thinkDurationMs?: number
|
|
||||||
toolName?: string
|
|
||||||
toolParams?: Record<string, unknown>
|
|
||||||
toolResult?: unknown
|
|
||||||
error?: string
|
|
||||||
isFinished?: boolean
|
|
||||||
usage?: TokenUsage
|
|
||||||
status?: AgentRuntimeStatus
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AgentRunPayload {
|
|
||||||
mode?: 'chat' | 'sql'
|
|
||||||
conversationId?: string
|
|
||||||
userInput: string
|
|
||||||
assistantId?: string
|
|
||||||
activeSkillId?: string
|
|
||||||
chatScope?: 'group' | 'private'
|
|
||||||
sqlContext?: {
|
|
||||||
schemaText?: string
|
|
||||||
targetHint?: string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ActiveAgentRun {
|
|
||||||
runId: string
|
|
||||||
mode: 'chat' | 'sql'
|
|
||||||
conversationId?: string
|
|
||||||
innerRunId?: string
|
|
||||||
aborted: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeText(value: unknown, fallback = ''): string {
|
|
||||||
const text = String(value ?? '').trim()
|
|
||||||
return text || fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildApiUrl(baseUrl: string, path: string): string {
|
|
||||||
const base = baseUrl.replace(/\/+$/, '')
|
|
||||||
const suffix = path.startsWith('/') ? path : `/${path}`
|
|
||||||
return `${base}${suffix}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function extractSqlText(raw: string): string {
|
|
||||||
const text = normalizeText(raw)
|
|
||||||
if (!text) return ''
|
|
||||||
const fenced = text.match(/```(?:sql)?\s*([\s\S]*?)```/i)
|
|
||||||
if (fenced?.[1]) return fenced[1].trim()
|
|
||||||
return text
|
|
||||||
}
|
|
||||||
|
|
||||||
class AiAgentService {
|
|
||||||
private readonly config = ConfigService.getInstance()
|
|
||||||
private readonly runs = new Map<string, ActiveAgentRun>()
|
|
||||||
|
|
||||||
private getSharedModelConfig(): { apiBaseUrl: string; apiKey: string; model: string } {
|
|
||||||
return {
|
|
||||||
apiBaseUrl: normalizeText(this.config.get('aiModelApiBaseUrl')),
|
|
||||||
apiKey: normalizeText(this.config.get('aiModelApiKey')),
|
|
||||||
model: normalizeText(this.config.get('aiModelApiModel'), 'gpt-4o-mini')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private emitStatus(
|
|
||||||
run: ActiveAgentRun,
|
|
||||||
onChunk: (chunk: AgentStreamChunk) => void,
|
|
||||||
phase: AgentRuntimeStatus['phase'],
|
|
||||||
extra?: Partial<AgentRuntimeStatus>
|
|
||||||
): void {
|
|
||||||
onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'status',
|
|
||||||
status: {
|
|
||||||
phase,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
...extra
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private mapRunEventToChunk(
|
|
||||||
run: ActiveAgentRun,
|
|
||||||
event: AiAnalysisRunEvent
|
|
||||||
): AgentStreamChunk | null {
|
|
||||||
run.innerRunId = event.runId
|
|
||||||
run.conversationId = event.conversationId || run.conversationId
|
|
||||||
if (event.stage === 'llm_round_started') {
|
|
||||||
return {
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'think',
|
|
||||||
content: event.message,
|
|
||||||
thinkTag: 'round'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (event.stage === 'tool_start') {
|
|
||||||
return {
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'tool_start',
|
|
||||||
toolName: event.toolName,
|
|
||||||
toolParams: (event.data || {}) as Record<string, unknown>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (event.stage === 'tool_done' || event.stage === 'tool_error') {
|
|
||||||
return {
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'tool_result',
|
|
||||||
toolName: event.toolName,
|
|
||||||
toolResult: event.data || { status: event.status, durationMs: event.durationMs }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (event.stage === 'completed') {
|
|
||||||
return {
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'status',
|
|
||||||
status: { phase: 'completed', updatedAt: Date.now() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (event.stage === 'aborted') {
|
|
||||||
return {
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'status',
|
|
||||||
status: { phase: 'aborted', updatedAt: Date.now() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (event.stage === 'error') {
|
|
||||||
return {
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'status',
|
|
||||||
status: { phase: 'error', updatedAt: Date.now() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
private async callModel(payload: any, apiBaseUrl: string, apiKey: string): Promise<any> {
|
|
||||||
const endpoint = buildApiUrl(apiBaseUrl, '/chat/completions')
|
|
||||||
const body = JSON.stringify(payload)
|
|
||||||
const urlObj = new URL(endpoint)
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const requestFn = urlObj.protocol === 'https:' ? https.request : http.request
|
|
||||||
const req = requestFn({
|
|
||||||
hostname: urlObj.hostname,
|
|
||||||
port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
|
|
||||||
path: urlObj.pathname + urlObj.search,
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Content-Length': Buffer.byteLength(body).toString(),
|
|
||||||
Authorization: `Bearer ${apiKey}`
|
|
||||||
}
|
|
||||||
}, (res) => {
|
|
||||||
let data = ''
|
|
||||||
res.on('data', (chunk) => { data += String(chunk) })
|
|
||||||
res.on('end', () => {
|
|
||||||
try {
|
|
||||||
resolve(JSON.parse(data || '{}'))
|
|
||||||
} catch (error) {
|
|
||||||
reject(new Error(`AI 响应解析失败: ${String(error)}`))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
req.setTimeout(45_000, () => {
|
|
||||||
req.destroy()
|
|
||||||
reject(new Error('AI 请求超时'))
|
|
||||||
})
|
|
||||||
req.on('error', reject)
|
|
||||||
req.write(body)
|
|
||||||
req.end()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async runStream(
|
|
||||||
payload: AgentRunPayload,
|
|
||||||
runtime: {
|
|
||||||
onChunk: (chunk: AgentStreamChunk) => void
|
|
||||||
onFinished?: (result: { success: boolean; runId: string; conversationId?: string; error?: string }) => void
|
|
||||||
}
|
|
||||||
): Promise<{ success: boolean; runId: string }> {
|
|
||||||
const runId = randomUUID()
|
|
||||||
const mode = payload.mode === 'sql' ? 'sql' : 'chat'
|
|
||||||
const run: ActiveAgentRun = {
|
|
||||||
runId,
|
|
||||||
mode,
|
|
||||||
conversationId: normalizeText(payload.conversationId) || undefined,
|
|
||||||
aborted: false
|
|
||||||
}
|
|
||||||
this.runs.set(runId, run)
|
|
||||||
|
|
||||||
this.execute(run, payload, runtime).catch((error) => {
|
|
||||||
runtime.onChunk({
|
|
||||||
runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'error',
|
|
||||||
error: String((error as Error)?.message || error),
|
|
||||||
isFinished: true
|
|
||||||
})
|
|
||||||
runtime.onFinished?.({
|
|
||||||
success: false,
|
|
||||||
runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
error: String((error as Error)?.message || error)
|
|
||||||
})
|
|
||||||
this.runs.delete(runId)
|
|
||||||
})
|
|
||||||
|
|
||||||
return { success: true, runId }
|
|
||||||
}
|
|
||||||
|
|
||||||
private async execute(
|
|
||||||
run: ActiveAgentRun,
|
|
||||||
payload: AgentRunPayload,
|
|
||||||
runtime: {
|
|
||||||
onChunk: (chunk: AgentStreamChunk) => void
|
|
||||||
onFinished?: (result: { success: boolean; runId: string; conversationId?: string; error?: string }) => void
|
|
||||||
}
|
|
||||||
): Promise<void> {
|
|
||||||
if (run.mode === 'sql') {
|
|
||||||
await this.executeSqlMode(run, payload, runtime)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.emitStatus(run, runtime.onChunk, 'thinking')
|
|
||||||
const result = await aiAnalysisService.sendMessage(
|
|
||||||
normalizeText(payload.conversationId),
|
|
||||||
normalizeText(payload.userInput),
|
|
||||||
{
|
|
||||||
assistantId: normalizeText(payload.assistantId),
|
|
||||||
activeSkillId: normalizeText(payload.activeSkillId),
|
|
||||||
chatScope: payload.chatScope === 'group' ? 'group' : 'private'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onRunEvent: (event) => {
|
|
||||||
const mapped = this.mapRunEventToChunk(run, event)
|
|
||||||
if (mapped) runtime.onChunk(mapped)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
if (run.aborted) {
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'error',
|
|
||||||
error: '任务已取消',
|
|
||||||
isFinished: true
|
|
||||||
})
|
|
||||||
runtime.onFinished?.({
|
|
||||||
success: false,
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
error: '任务已取消'
|
|
||||||
})
|
|
||||||
this.runs.delete(run.runId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (!result.success || !result.result) {
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'error',
|
|
||||||
error: result.error || '执行失败',
|
|
||||||
isFinished: true
|
|
||||||
})
|
|
||||||
runtime.onFinished?.({
|
|
||||||
success: false,
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
error: result.error || '执行失败'
|
|
||||||
})
|
|
||||||
this.runs.delete(run.runId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
run.conversationId = result.result.conversationId || run.conversationId
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'content',
|
|
||||||
content: result.result.assistantText
|
|
||||||
})
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'done',
|
|
||||||
usage: result.result.usage,
|
|
||||||
isFinished: true
|
|
||||||
})
|
|
||||||
runtime.onFinished?.({ success: true, runId: run.runId, conversationId: run.conversationId })
|
|
||||||
this.runs.delete(run.runId)
|
|
||||||
}
|
|
||||||
|
|
||||||
private async executeSqlMode(
|
|
||||||
run: ActiveAgentRun,
|
|
||||||
payload: AgentRunPayload,
|
|
||||||
runtime: {
|
|
||||||
onChunk: (chunk: AgentStreamChunk) => void
|
|
||||||
onFinished?: (result: { success: boolean; runId: string; conversationId?: string; error?: string }) => void
|
|
||||||
}
|
|
||||||
): Promise<void> {
|
|
||||||
const { apiBaseUrl, apiKey, model } = this.getSharedModelConfig()
|
|
||||||
if (!apiBaseUrl || !apiKey) {
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'error',
|
|
||||||
error: '请先在设置 > AI 通用中配置模型',
|
|
||||||
isFinished: true
|
|
||||||
})
|
|
||||||
runtime.onFinished?.({ success: false, runId: run.runId, conversationId: run.conversationId, error: '模型未配置' })
|
|
||||||
this.runs.delete(run.runId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.emitStatus(run, runtime.onChunk, 'thinking')
|
|
||||||
const schemaText = normalizeText(payload.sqlContext?.schemaText)
|
|
||||||
const targetHint = normalizeText(payload.sqlContext?.targetHint)
|
|
||||||
const systemPrompt = [
|
|
||||||
'你是 WeFlow SQL Lab 助手。',
|
|
||||||
'只输出一段只读 SQL。',
|
|
||||||
'禁止输出解释、Markdown、注释、DML、DDL。'
|
|
||||||
].join('\n')
|
|
||||||
const userPrompt = [
|
|
||||||
targetHint ? `目标数据源: ${targetHint}` : '',
|
|
||||||
schemaText ? `可用 Schema:\n${schemaText}` : '',
|
|
||||||
`需求: ${normalizeText(payload.userInput)}`
|
|
||||||
].filter(Boolean).join('\n\n')
|
|
||||||
|
|
||||||
const res = await this.callModel({
|
|
||||||
model,
|
|
||||||
messages: [
|
|
||||||
{ role: 'system', content: systemPrompt },
|
|
||||||
{ role: 'user', content: userPrompt }
|
|
||||||
],
|
|
||||||
temperature: 0.1,
|
|
||||||
stream: false
|
|
||||||
}, apiBaseUrl, apiKey)
|
|
||||||
|
|
||||||
if (run.aborted) {
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'error',
|
|
||||||
error: '任务已取消',
|
|
||||||
isFinished: true
|
|
||||||
})
|
|
||||||
runtime.onFinished?.({ success: false, runId: run.runId, conversationId: run.conversationId, error: '任务已取消' })
|
|
||||||
this.runs.delete(run.runId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const rawContent = normalizeText(res?.choices?.[0]?.message?.content)
|
|
||||||
const sql = extractSqlText(rawContent)
|
|
||||||
const usage: TokenUsage = {
|
|
||||||
promptTokens: Number(res?.usage?.prompt_tokens || 0),
|
|
||||||
completionTokens: Number(res?.usage?.completion_tokens || 0),
|
|
||||||
totalTokens: Number(res?.usage?.total_tokens || 0)
|
|
||||||
}
|
|
||||||
if (!sql) {
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'error',
|
|
||||||
error: 'SQL 生成失败',
|
|
||||||
isFinished: true
|
|
||||||
})
|
|
||||||
runtime.onFinished?.({ success: false, runId: run.runId, conversationId: run.conversationId, error: 'SQL 生成失败' })
|
|
||||||
this.runs.delete(run.runId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for (let i = 0; i < sql.length; i += 36) {
|
|
||||||
if (run.aborted) break
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'content',
|
|
||||||
content: sql.slice(i, i + 36)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
runtime.onChunk({
|
|
||||||
runId: run.runId,
|
|
||||||
conversationId: run.conversationId,
|
|
||||||
type: 'done',
|
|
||||||
usage,
|
|
||||||
isFinished: true
|
|
||||||
})
|
|
||||||
runtime.onFinished?.({ success: true, runId: run.runId, conversationId: run.conversationId })
|
|
||||||
this.runs.delete(run.runId)
|
|
||||||
}
|
|
||||||
|
|
||||||
async abort(payload: { runId?: string; conversationId?: string }): Promise<{ success: boolean }> {
|
|
||||||
const runId = normalizeText(payload.runId)
|
|
||||||
const conversationId = normalizeText(payload.conversationId)
|
|
||||||
if (runId) {
|
|
||||||
const run = this.runs.get(runId)
|
|
||||||
if (run) {
|
|
||||||
run.aborted = true
|
|
||||||
if (run.mode === 'chat') {
|
|
||||||
await aiAnalysisService.abortRun({ runId: run.innerRunId, conversationId: run.conversationId })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { success: true }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (conversationId) {
|
|
||||||
for (const run of this.runs.values()) {
|
|
||||||
if (run.conversationId !== conversationId) continue
|
|
||||||
run.aborted = true
|
|
||||||
if (run.mode === 'chat') {
|
|
||||||
await aiAnalysisService.abortRun({ runId: run.innerRunId, conversationId: run.conversationId })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { success: true }
|
|
||||||
}
|
|
||||||
return { success: true }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const aiAgentService = new AiAgentService()
|
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,30 +0,0 @@
|
|||||||
你是 WeFlow 的 AI 分析助手。
|
|
||||||
|
|
||||||
目标:
|
|
||||||
- 精准完成用户在聊天数据上的查询、总结、分析、回忆任务。
|
|
||||||
- 优先使用本地工具获取证据,禁止猜测或捏造。
|
|
||||||
- 默认输出简洁中文,先给结论,再给关键依据。
|
|
||||||
|
|
||||||
工作原则:
|
|
||||||
- Token 节约优先:默认只请求必要字段,只有用户明确需要或证据不足时再升级 detailLevel。
|
|
||||||
- 先范围后细节:优先定位会话/时间范围,再拉取具体时间轴或消息。
|
|
||||||
- 可解释性:最终结论尽量附带来源范围与统计口径。
|
|
||||||
- 语音消息不能臆测:必须先拿语音 ID,再点名转写,再总结。
|
|
||||||
- 联系人排行题(“谁聊得最多/最常联系”)命中 ai_query_top_contacts 后,必须直接给出“前N名+消息数”。
|
|
||||||
- 除非用户明确要求,联系人排行默认不包含群聊和公众号。
|
|
||||||
- 用户提到“最近/近期/lately/recent”但未给时间窗时,默认按近30天口径统计并写明口径。
|
|
||||||
- 用户提到联系人简称(如“lr”)时,先把它当联系人缩写处理,优先命中个人会话,不要默认落到群聊。
|
|
||||||
- 用户问“我和X聊了什么”时必须交付“主题总结”,不要贴原始逐条聊天流水。
|
|
||||||
|
|
||||||
Agent执行要求:
|
|
||||||
- 用户输入直接进入推理,本地不做关键词分流,你自主决定工具计划。
|
|
||||||
- 当用户说“今天凌晨/昨晚/某段时间的聊天”,优先调用 ai_query_time_window_activity。
|
|
||||||
- 拿到活跃会话后,调用 ai_query_session_glimpse 对多个会话逐个抽样阅读,不要只读一个会话就停止。
|
|
||||||
- 如果初步探索后用户目标仍模糊,主动提出 1 个关键澄清问题继续多轮对话。
|
|
||||||
- 仅当你确认任务完成时,输出结束标记 `[[WF_DONE]]`,并紧跟 `<final_answer>...</final_answer>`。
|
|
||||||
- 若还未完成,不要输出结束标记,继续调用工具。
|
|
||||||
|
|
||||||
语音处理硬规则:
|
|
||||||
- 当用户涉及“语音内容”时,先调用 ai_list_voice_messages。
|
|
||||||
- 让系统返回候选 ID 后,再调用 ai_transcribe_voice_messages 指定 ID。
|
|
||||||
- 未转写成功的语音不可作为事实依据。
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
你会收到 conversation_summary(历史压缩摘要)。
|
|
||||||
|
|
||||||
使用方式:
|
|
||||||
- 默认把摘要作为历史背景,不逐字复述。
|
|
||||||
- 若摘要与最近消息冲突,以最近消息为准。
|
|
||||||
- 若用户追问很久之前的细节,优先重新调用工具检索,不依赖旧记忆。
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
工具:ai_fetch_message_briefs
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 需要核对少量关键消息原文,避免全量展开。
|
|
||||||
|
|
||||||
调用建议:
|
|
||||||
- 只传必要 items(sessionId + localId),每次少量(<=20)。
|
|
||||||
- 默认 minimal;需要上下文再用 standard/full。
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
工具:ai_query_session_candidates
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 用户未明确具体会话,但给了关键词/关系词(如“老婆”“买车”)。
|
|
||||||
|
|
||||||
调用建议:
|
|
||||||
- 首次调用 detailLevel=minimal。
|
|
||||||
- 默认 limit 8~12,避免拉太多候选。
|
|
||||||
- 当候选歧义较大时再升级 detailLevel=standard/full。
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
工具:ai_query_session_glimpse
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 已确定候选会话,需要“先看一点”理解上下文。
|
|
||||||
|
|
||||||
Agent策略:
|
|
||||||
- 每个候选会话先抽样 6~20 条,按时间顺序阅读。
|
|
||||||
- 不要只读一个会话就结束;优先覆盖多会话后再总结。
|
|
||||||
- 如果出现明显分歧场景(工作/家庭/感情)需主动向用户确认分析目标。
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
工具:ai_query_source_refs
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 输出总结或分析后,用于来源说明与可解释卡片。
|
|
||||||
|
|
||||||
调用建议:
|
|
||||||
- 默认 minimal 即可,输出 range/session_count/message_count/db_refs。
|
|
||||||
- 只有排错或审计时再请求 full。
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
工具:ai_query_time_window_activity
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 用户提到“今天凌晨/昨晚/某个时间段”的聊天分析。
|
|
||||||
|
|
||||||
Agent策略:
|
|
||||||
- 第一步必须先扫时间窗活跃会话,不要直接下结论。
|
|
||||||
- 拿到活跃会话后,再调用 ai_query_session_glimpse 逐个会话抽样阅读。
|
|
||||||
- 若用户目标仍不清晰,先追问 1 个关键澄清问题再继续。
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
工具:ai_query_timeline
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 回忆事件经过、梳理时间线、提取关键节点。
|
|
||||||
|
|
||||||
调用建议:
|
|
||||||
- 默认 detailLevel=minimal。
|
|
||||||
- 先小批次 limit(40~120),不够再分页 offset。
|
|
||||||
- 需要引用原文证据时,可搭配 ai_fetch_message_briefs。
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
工具:ai_query_top_contacts
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 用户问“谁联系最密切”“谁聊得最多”“最常联系的是谁”。
|
|
||||||
|
|
||||||
调用建议:
|
|
||||||
- 该问题优先调用本工具,而不是先跑时间轴。
|
|
||||||
- 默认 detailLevel=minimal,limit 5~10。
|
|
||||||
- 需要区分群聊时再设置 includeGroups=true。
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
工具:ai_query_topic_stats
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 用户问“多少、占比、趋势、对比”。
|
|
||||||
|
|
||||||
调用建议:
|
|
||||||
- 仅在统计问题时调用,避免无谓聚合。
|
|
||||||
- 默认 detailLevel=minimal;有统计追问再升到 standard/full。
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
工具:ai_list_voice_messages
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 用户提到“语音里说了什么”。
|
|
||||||
|
|
||||||
调用建议:
|
|
||||||
- 第一步先拿 ID 清单,默认 detailLevel=minimal(仅 IDs)。
|
|
||||||
- 如用户需要挑选依据,再用 standard/full 查看更多元数据。
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
工具:ai_transcribe_voice_messages
|
|
||||||
|
|
||||||
何时用:
|
|
||||||
- 已明确拿到语音 ID,且用户需要读取语音内容。
|
|
||||||
|
|
||||||
调用建议:
|
|
||||||
- 必须显式传 ids 或 items。
|
|
||||||
- 单次控制在小批次(建议 <=5),失败可重试。
|
|
||||||
- 转写成功后再参与总结;失败项单独标注,不混入结论。
|
|
||||||
@@ -1,444 +0,0 @@
|
|||||||
import { randomUUID } from 'crypto'
|
|
||||||
import { existsSync } from 'fs'
|
|
||||||
import { mkdir, readdir, readFile, rm, writeFile } from 'fs/promises'
|
|
||||||
import { join } from 'path'
|
|
||||||
import { ConfigService } from './config'
|
|
||||||
|
|
||||||
export type AssistantChatType = 'group' | 'private'
|
|
||||||
export type AssistantToolCategory = 'core' | 'analysis'
|
|
||||||
|
|
||||||
export interface AssistantSummary {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
systemPrompt: string
|
|
||||||
presetQuestions: string[]
|
|
||||||
allowedBuiltinTools?: string[]
|
|
||||||
builtinId?: string
|
|
||||||
applicableChatTypes?: AssistantChatType[]
|
|
||||||
supportedLocales?: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AssistantConfigFull extends AssistantSummary {}
|
|
||||||
|
|
||||||
export interface BuiltinAssistantInfo {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
systemPrompt: string
|
|
||||||
applicableChatTypes?: AssistantChatType[]
|
|
||||||
supportedLocales?: string[]
|
|
||||||
imported: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
const GENERAL_CN_MD = `---
|
|
||||||
id: general_cn
|
|
||||||
name: 通用分析助手
|
|
||||||
supportedLocales:
|
|
||||||
- zh
|
|
||||||
presetQuestions:
|
|
||||||
- 最近都在聊什么?
|
|
||||||
- 谁是最活跃的人?
|
|
||||||
- 帮我总结一下最近一周的重要聊天
|
|
||||||
- 帮我找一下关于“旅游”的讨论
|
|
||||||
allowedBuiltinTools:
|
|
||||||
- ai_query_time_window_activity
|
|
||||||
- ai_query_session_candidates
|
|
||||||
- ai_query_session_glimpse
|
|
||||||
- ai_query_timeline
|
|
||||||
- ai_fetch_message_briefs
|
|
||||||
- ai_list_voice_messages
|
|
||||||
- ai_transcribe_voice_messages
|
|
||||||
- ai_query_topic_stats
|
|
||||||
- ai_query_source_refs
|
|
||||||
- ai_query_top_contacts
|
|
||||||
---
|
|
||||||
|
|
||||||
你是 WeFlow 的全局聊天分析助手。请使用工具获取证据,给出简洁、准确、可执行的结论。
|
|
||||||
|
|
||||||
输出要求:
|
|
||||||
1. 先结论,再证据。
|
|
||||||
2. 若证据不足,明确说明不足并建议下一步。
|
|
||||||
3. 涉及语音内容时,必须先列语音 ID,再按 ID 转写。
|
|
||||||
4. 默认中文输出,除非用户明确指定其他语言。`
|
|
||||||
|
|
||||||
const GENERAL_EN_MD = `---
|
|
||||||
id: general_en
|
|
||||||
name: General Analysis Assistant
|
|
||||||
supportedLocales:
|
|
||||||
- en
|
|
||||||
presetQuestions:
|
|
||||||
- What have people been discussing recently?
|
|
||||||
- Who are the most active contacts?
|
|
||||||
- Summarize my key chat topics this week
|
|
||||||
allowedBuiltinTools:
|
|
||||||
- ai_query_time_window_activity
|
|
||||||
- ai_query_session_candidates
|
|
||||||
- ai_query_session_glimpse
|
|
||||||
- ai_query_timeline
|
|
||||||
- ai_fetch_message_briefs
|
|
||||||
- ai_list_voice_messages
|
|
||||||
- ai_transcribe_voice_messages
|
|
||||||
- ai_query_topic_stats
|
|
||||||
- ai_query_source_refs
|
|
||||||
- ai_query_top_contacts
|
|
||||||
---
|
|
||||||
|
|
||||||
You are WeFlow's global chat analysis assistant.
|
|
||||||
Always ground your answers in tool evidence, stay concise, and clearly call out uncertainty when data is insufficient.`
|
|
||||||
|
|
||||||
const GENERAL_JA_MD = `---
|
|
||||||
id: general_ja
|
|
||||||
name: 汎用分析アシスタント
|
|
||||||
supportedLocales:
|
|
||||||
- ja
|
|
||||||
presetQuestions:
|
|
||||||
- 最近どんな話題が多い?
|
|
||||||
- 一番アクティブな相手は誰?
|
|
||||||
- 今週の重要な会話を要約して
|
|
||||||
allowedBuiltinTools:
|
|
||||||
- ai_query_time_window_activity
|
|
||||||
- ai_query_session_candidates
|
|
||||||
- ai_query_session_glimpse
|
|
||||||
- ai_query_timeline
|
|
||||||
- ai_fetch_message_briefs
|
|
||||||
- ai_list_voice_messages
|
|
||||||
- ai_transcribe_voice_messages
|
|
||||||
- ai_query_topic_stats
|
|
||||||
- ai_query_source_refs
|
|
||||||
- ai_query_top_contacts
|
|
||||||
---
|
|
||||||
|
|
||||||
あなたは WeFlow のグローバルチャット分析アシスタントです。
|
|
||||||
ツールから得た根拠に基づき、簡潔かつ正確に回答してください。`
|
|
||||||
|
|
||||||
const BUILTIN_ASSISTANTS = [
|
|
||||||
{ id: 'general_cn', raw: GENERAL_CN_MD },
|
|
||||||
{ id: 'general_en', raw: GENERAL_EN_MD },
|
|
||||||
{ id: 'general_ja', raw: GENERAL_JA_MD }
|
|
||||||
] as const
|
|
||||||
|
|
||||||
function normalizeText(value: unknown, fallback = ''): string {
|
|
||||||
const text = String(value ?? '').trim()
|
|
||||||
return text || fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseInlineList(text: string): string[] {
|
|
||||||
const raw = normalizeText(text)
|
|
||||||
if (!raw) return []
|
|
||||||
return raw
|
|
||||||
.split(',')
|
|
||||||
.map((item) => item.trim())
|
|
||||||
.filter(Boolean)
|
|
||||||
}
|
|
||||||
|
|
||||||
function splitFrontmatter(raw: string): { frontmatter: string; body: string } {
|
|
||||||
const normalized = String(raw || '')
|
|
||||||
if (!normalized.startsWith('---')) {
|
|
||||||
return { frontmatter: '', body: normalized.trim() }
|
|
||||||
}
|
|
||||||
const end = normalized.indexOf('\n---', 3)
|
|
||||||
if (end < 0) return { frontmatter: '', body: normalized.trim() }
|
|
||||||
return {
|
|
||||||
frontmatter: normalized.slice(3, end).trim(),
|
|
||||||
body: normalized.slice(end + 4).trim()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseAssistantMarkdown(raw: string): AssistantConfigFull {
|
|
||||||
const { frontmatter, body } = splitFrontmatter(raw)
|
|
||||||
const lines = frontmatter ? frontmatter.split('\n') : []
|
|
||||||
const data: Record<string, unknown> = {}
|
|
||||||
let currentArrayKey = ''
|
|
||||||
for (const line of lines) {
|
|
||||||
const trimmed = line.trim()
|
|
||||||
if (!trimmed) continue
|
|
||||||
const kv = trimmed.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/)
|
|
||||||
if (kv) {
|
|
||||||
const key = kv[1]
|
|
||||||
const value = kv[2]
|
|
||||||
if (!value) {
|
|
||||||
data[key] = []
|
|
||||||
currentArrayKey = key
|
|
||||||
} else {
|
|
||||||
data[key] = value
|
|
||||||
currentArrayKey = ''
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const arr = trimmed.match(/^- (.+)$/)
|
|
||||||
if (arr && currentArrayKey) {
|
|
||||||
const next = Array.isArray(data[currentArrayKey]) ? data[currentArrayKey] as string[] : []
|
|
||||||
next.push(arr[1].trim())
|
|
||||||
data[currentArrayKey] = next
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const id = normalizeText(data.id)
|
|
||||||
const name = normalizeText(data.name, id || 'assistant')
|
|
||||||
const applicableChatTypes = Array.isArray(data.applicableChatTypes)
|
|
||||||
? (data.applicableChatTypes as string[]).filter((item): item is AssistantChatType => item === 'group' || item === 'private')
|
|
||||||
: parseInlineList(String(data.applicableChatTypes || '')).filter((item): item is AssistantChatType => item === 'group' || item === 'private')
|
|
||||||
const supportedLocales = Array.isArray(data.supportedLocales)
|
|
||||||
? (data.supportedLocales as string[]).map((item) => item.trim()).filter(Boolean)
|
|
||||||
: parseInlineList(String(data.supportedLocales || ''))
|
|
||||||
const presetQuestions = Array.isArray(data.presetQuestions)
|
|
||||||
? (data.presetQuestions as string[]).map((item) => item.trim()).filter(Boolean)
|
|
||||||
: parseInlineList(String(data.presetQuestions || ''))
|
|
||||||
const allowedBuiltinTools = Array.isArray(data.allowedBuiltinTools)
|
|
||||||
? (data.allowedBuiltinTools as string[]).map((item) => item.trim()).filter(Boolean)
|
|
||||||
: parseInlineList(String(data.allowedBuiltinTools || ''))
|
|
||||||
const builtinId = normalizeText(data.builtinId)
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
systemPrompt: body,
|
|
||||||
presetQuestions,
|
|
||||||
allowedBuiltinTools,
|
|
||||||
builtinId: builtinId || undefined,
|
|
||||||
applicableChatTypes,
|
|
||||||
supportedLocales
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toMarkdown(config: AssistantConfigFull): string {
|
|
||||||
const lines = [
|
|
||||||
'---',
|
|
||||||
`id: ${config.id}`,
|
|
||||||
`name: ${config.name}`
|
|
||||||
]
|
|
||||||
if (config.builtinId) lines.push(`builtinId: ${config.builtinId}`)
|
|
||||||
if (config.supportedLocales && config.supportedLocales.length > 0) {
|
|
||||||
lines.push('supportedLocales:')
|
|
||||||
config.supportedLocales.forEach((item) => lines.push(` - ${item}`))
|
|
||||||
}
|
|
||||||
if (config.applicableChatTypes && config.applicableChatTypes.length > 0) {
|
|
||||||
lines.push('applicableChatTypes:')
|
|
||||||
config.applicableChatTypes.forEach((item) => lines.push(` - ${item}`))
|
|
||||||
}
|
|
||||||
if (config.presetQuestions && config.presetQuestions.length > 0) {
|
|
||||||
lines.push('presetQuestions:')
|
|
||||||
config.presetQuestions.forEach((item) => lines.push(` - ${item}`))
|
|
||||||
}
|
|
||||||
if (config.allowedBuiltinTools && config.allowedBuiltinTools.length > 0) {
|
|
||||||
lines.push('allowedBuiltinTools:')
|
|
||||||
config.allowedBuiltinTools.forEach((item) => lines.push(` - ${item}`))
|
|
||||||
}
|
|
||||||
lines.push('---')
|
|
||||||
lines.push('')
|
|
||||||
lines.push(config.systemPrompt || '')
|
|
||||||
return lines.join('\n')
|
|
||||||
}
|
|
||||||
|
|
||||||
function defaultBuiltinToolCatalog(): Array<{ name: string; category: AssistantToolCategory }> {
|
|
||||||
return [
|
|
||||||
{ name: 'ai_query_time_window_activity', category: 'core' },
|
|
||||||
{ name: 'ai_query_session_candidates', category: 'core' },
|
|
||||||
{ name: 'ai_query_session_glimpse', category: 'core' },
|
|
||||||
{ name: 'ai_query_timeline', category: 'core' },
|
|
||||||
{ name: 'ai_fetch_message_briefs', category: 'core' },
|
|
||||||
{ name: 'ai_list_voice_messages', category: 'core' },
|
|
||||||
{ name: 'ai_transcribe_voice_messages', category: 'core' },
|
|
||||||
{ name: 'ai_query_topic_stats', category: 'analysis' },
|
|
||||||
{ name: 'ai_query_source_refs', category: 'analysis' },
|
|
||||||
{ name: 'ai_query_top_contacts', category: 'analysis' },
|
|
||||||
{ name: 'activate_skill', category: 'analysis' }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
class AiAssistantService {
|
|
||||||
private readonly config = ConfigService.getInstance()
|
|
||||||
private initialized = false
|
|
||||||
private readonly cache = new Map<string, AssistantConfigFull>()
|
|
||||||
|
|
||||||
private getRootDirCandidates(): string[] {
|
|
||||||
const dbPath = normalizeText(this.config.get('dbPath'))
|
|
||||||
const wxid = normalizeText(this.config.get('myWxid'))
|
|
||||||
const roots: string[] = []
|
|
||||||
if (dbPath && wxid) {
|
|
||||||
roots.push(join(dbPath, wxid, 'db_storage', 'wf_ai_v2'))
|
|
||||||
roots.push(join(dbPath, wxid, 'db_storage', 'wf_ai'))
|
|
||||||
}
|
|
||||||
roots.push(join(process.cwd(), 'data', 'wf_ai_v2'))
|
|
||||||
return roots
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getRootDir(): Promise<string> {
|
|
||||||
const roots = this.getRootDirCandidates()
|
|
||||||
const dir = roots[0]
|
|
||||||
await mkdir(dir, { recursive: true })
|
|
||||||
return dir
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getAssistantsDir(): Promise<string> {
|
|
||||||
const root = await this.getRootDir()
|
|
||||||
const dir = join(root, 'assistants')
|
|
||||||
await mkdir(dir, { recursive: true })
|
|
||||||
return dir
|
|
||||||
}
|
|
||||||
|
|
||||||
private async ensureInitialized(): Promise<void> {
|
|
||||||
if (this.initialized) return
|
|
||||||
const dir = await this.getAssistantsDir()
|
|
||||||
|
|
||||||
for (const builtin of BUILTIN_ASSISTANTS) {
|
|
||||||
const filePath = join(dir, `${builtin.id}.md`)
|
|
||||||
if (!existsSync(filePath)) {
|
|
||||||
const parsed = parseAssistantMarkdown(builtin.raw)
|
|
||||||
const config: AssistantConfigFull = {
|
|
||||||
...parsed,
|
|
||||||
builtinId: parsed.id
|
|
||||||
}
|
|
||||||
await writeFile(filePath, toMarkdown(config), 'utf8')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.cache.clear()
|
|
||||||
const files = await readdir(dir)
|
|
||||||
for (const fileName of files) {
|
|
||||||
if (!fileName.endsWith('.md')) continue
|
|
||||||
const filePath = join(dir, fileName)
|
|
||||||
try {
|
|
||||||
const raw = await readFile(filePath, 'utf8')
|
|
||||||
const parsed = parseAssistantMarkdown(raw)
|
|
||||||
if (!parsed.id) continue
|
|
||||||
this.cache.set(parsed.id, parsed)
|
|
||||||
} catch {
|
|
||||||
// ignore broken file
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.initialized = true
|
|
||||||
}
|
|
||||||
|
|
||||||
async getAll(): Promise<AssistantSummary[]> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
return Array.from(this.cache.values())
|
|
||||||
.sort((a, b) => a.name.localeCompare(b.name, 'zh-Hans-CN'))
|
|
||||||
.map((assistant) => ({ ...assistant }))
|
|
||||||
}
|
|
||||||
|
|
||||||
async getConfig(id: string): Promise<AssistantConfigFull | null> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const key = normalizeText(id)
|
|
||||||
const config = this.cache.get(key)
|
|
||||||
return config ? { ...config } : null
|
|
||||||
}
|
|
||||||
|
|
||||||
async create(
|
|
||||||
payload: Omit<AssistantConfigFull, 'id'> & { id?: string }
|
|
||||||
): Promise<{ success: boolean; id?: string; error?: string }> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const id = normalizeText(payload.id, `custom_${randomUUID().replace(/-/g, '').slice(0, 12)}`)
|
|
||||||
if (this.cache.has(id)) return { success: false, error: '助手 ID 已存在' }
|
|
||||||
const config: AssistantConfigFull = {
|
|
||||||
id,
|
|
||||||
name: normalizeText(payload.name, '新助手'),
|
|
||||||
systemPrompt: normalizeText(payload.systemPrompt),
|
|
||||||
presetQuestions: Array.isArray(payload.presetQuestions) ? payload.presetQuestions.map((item) => normalizeText(item)).filter(Boolean) : [],
|
|
||||||
allowedBuiltinTools: Array.isArray(payload.allowedBuiltinTools) ? payload.allowedBuiltinTools.map((item) => normalizeText(item)).filter(Boolean) : [],
|
|
||||||
builtinId: normalizeText(payload.builtinId) || undefined,
|
|
||||||
applicableChatTypes: Array.isArray(payload.applicableChatTypes) ? payload.applicableChatTypes : [],
|
|
||||||
supportedLocales: Array.isArray(payload.supportedLocales) ? payload.supportedLocales.map((item) => normalizeText(item)).filter(Boolean) : []
|
|
||||||
}
|
|
||||||
const dir = await this.getAssistantsDir()
|
|
||||||
await writeFile(join(dir, `${id}.md`), toMarkdown(config), 'utf8')
|
|
||||||
this.cache.set(id, config)
|
|
||||||
return { success: true, id }
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(
|
|
||||||
id: string,
|
|
||||||
updates: Partial<AssistantConfigFull>
|
|
||||||
): Promise<{ success: boolean; error?: string }> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const key = normalizeText(id)
|
|
||||||
const existing = this.cache.get(key)
|
|
||||||
if (!existing) return { success: false, error: '助手不存在' }
|
|
||||||
const next: AssistantConfigFull = {
|
|
||||||
...existing,
|
|
||||||
...updates,
|
|
||||||
id: key,
|
|
||||||
name: normalizeText(updates.name, existing.name),
|
|
||||||
systemPrompt: updates.systemPrompt == null ? existing.systemPrompt : normalizeText(updates.systemPrompt),
|
|
||||||
presetQuestions: Array.isArray(updates.presetQuestions) ? updates.presetQuestions.map((item) => normalizeText(item)).filter(Boolean) : existing.presetQuestions,
|
|
||||||
allowedBuiltinTools: Array.isArray(updates.allowedBuiltinTools) ? updates.allowedBuiltinTools.map((item) => normalizeText(item)).filter(Boolean) : existing.allowedBuiltinTools,
|
|
||||||
applicableChatTypes: Array.isArray(updates.applicableChatTypes) ? updates.applicableChatTypes : existing.applicableChatTypes,
|
|
||||||
supportedLocales: Array.isArray(updates.supportedLocales) ? updates.supportedLocales.map((item) => normalizeText(item)).filter(Boolean) : existing.supportedLocales
|
|
||||||
}
|
|
||||||
const dir = await this.getAssistantsDir()
|
|
||||||
await writeFile(join(dir, `${key}.md`), toMarkdown(next), 'utf8')
|
|
||||||
this.cache.set(key, next)
|
|
||||||
return { success: true }
|
|
||||||
}
|
|
||||||
|
|
||||||
async delete(id: string): Promise<{ success: boolean; error?: string }> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const key = normalizeText(id)
|
|
||||||
if (key === 'general_cn' || key === 'general_en' || key === 'general_ja') {
|
|
||||||
return { success: false, error: '默认助手不可删除' }
|
|
||||||
}
|
|
||||||
const dir = await this.getAssistantsDir()
|
|
||||||
const filePath = join(dir, `${key}.md`)
|
|
||||||
if (existsSync(filePath)) {
|
|
||||||
await rm(filePath, { force: true })
|
|
||||||
}
|
|
||||||
this.cache.delete(key)
|
|
||||||
return { success: true }
|
|
||||||
}
|
|
||||||
|
|
||||||
async reset(id: string): Promise<{ success: boolean; error?: string }> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const key = normalizeText(id)
|
|
||||||
const existing = this.cache.get(key)
|
|
||||||
if (!existing?.builtinId) {
|
|
||||||
return { success: false, error: '该助手不支持重置' }
|
|
||||||
}
|
|
||||||
const builtin = BUILTIN_ASSISTANTS.find((item) => item.id === existing.builtinId)
|
|
||||||
if (!builtin) return { success: false, error: '内置模板不存在' }
|
|
||||||
const parsed = parseAssistantMarkdown(builtin.raw)
|
|
||||||
const config: AssistantConfigFull = {
|
|
||||||
...parsed,
|
|
||||||
id: key,
|
|
||||||
builtinId: existing.builtinId
|
|
||||||
}
|
|
||||||
const dir = await this.getAssistantsDir()
|
|
||||||
await writeFile(join(dir, `${key}.md`), toMarkdown(config), 'utf8')
|
|
||||||
this.cache.set(key, config)
|
|
||||||
return { success: true }
|
|
||||||
}
|
|
||||||
|
|
||||||
async getBuiltinCatalog(): Promise<BuiltinAssistantInfo[]> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
return BUILTIN_ASSISTANTS.map((builtin) => {
|
|
||||||
const parsed = parseAssistantMarkdown(builtin.raw)
|
|
||||||
const imported = Array.from(this.cache.values()).some((config) => config.builtinId === builtin.id || config.id === builtin.id)
|
|
||||||
return {
|
|
||||||
id: parsed.id,
|
|
||||||
name: parsed.name,
|
|
||||||
systemPrompt: parsed.systemPrompt,
|
|
||||||
applicableChatTypes: parsed.applicableChatTypes,
|
|
||||||
supportedLocales: parsed.supportedLocales,
|
|
||||||
imported
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async getBuiltinToolCatalog(): Promise<Array<{ name: string; category: AssistantToolCategory }>> {
|
|
||||||
return defaultBuiltinToolCatalog()
|
|
||||||
}
|
|
||||||
|
|
||||||
async importFromMd(rawMd: string): Promise<{ success: boolean; id?: string; error?: string }> {
|
|
||||||
try {
|
|
||||||
const parsed = parseAssistantMarkdown(rawMd)
|
|
||||||
if (!parsed.id) return { success: false, error: '缺少 id' }
|
|
||||||
if (this.cache.has(parsed.id)) return { success: false, error: '助手 ID 已存在' }
|
|
||||||
const dir = await this.getAssistantsDir()
|
|
||||||
await writeFile(join(dir, `${parsed.id}.md`), toMarkdown(parsed), 'utf8')
|
|
||||||
this.cache.set(parsed.id, parsed)
|
|
||||||
return { success: true, id: parsed.id }
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: String((error as Error)?.message || error) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const aiAssistantService = new AiAssistantService()
|
|
||||||
@@ -1,395 +0,0 @@
|
|||||||
import { existsSync } from 'fs'
|
|
||||||
import { mkdir, readdir, readFile, rm, writeFile } from 'fs/promises'
|
|
||||||
import { join } from 'path'
|
|
||||||
import { ConfigService } from './config'
|
|
||||||
|
|
||||||
export type SkillChatScope = 'all' | 'group' | 'private'
|
|
||||||
|
|
||||||
export interface SkillSummary {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
description: string
|
|
||||||
tags: string[]
|
|
||||||
chatScope: SkillChatScope
|
|
||||||
tools: string[]
|
|
||||||
builtinId?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SkillDef extends SkillSummary {
|
|
||||||
prompt: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BuiltinSkillInfo extends SkillSummary {
|
|
||||||
imported: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
const SKILL_DEEP_TIMELINE_MD = `---
|
|
||||||
id: deep_timeline
|
|
||||||
name: 深度时间线追踪
|
|
||||||
description: 适合还原某段时间内发生了什么,强调事件顺序与证据引用。
|
|
||||||
tags:
|
|
||||||
- timeline
|
|
||||||
- evidence
|
|
||||||
chatScope: all
|
|
||||||
tools:
|
|
||||||
- ai_query_time_window_activity
|
|
||||||
- ai_query_session_candidates
|
|
||||||
- ai_query_session_glimpse
|
|
||||||
- ai_query_timeline
|
|
||||||
- ai_fetch_message_briefs
|
|
||||||
- ai_query_source_refs
|
|
||||||
---
|
|
||||||
你是“深度时间线追踪”技能。
|
|
||||||
执行步骤:
|
|
||||||
1. 先按时间窗扫描活跃会话,必要时补关键词筛选候选会话。
|
|
||||||
2. 对候选会话先抽样,再拉取时间轴。
|
|
||||||
3. 对关键节点用 ai_fetch_message_briefs 校对原文。
|
|
||||||
4. 最后输出“结论 + 关键节点 + 来源范围”。`
|
|
||||||
|
|
||||||
const SKILL_CONTACT_FOCUS_MD = `---
|
|
||||||
id: contact_focus
|
|
||||||
name: 联系人关系聚焦
|
|
||||||
description: 用于“我和谁聊得最多/关系变化”这类问题,强调联系人维度。
|
|
||||||
tags:
|
|
||||||
- contacts
|
|
||||||
- relation
|
|
||||||
chatScope: private
|
|
||||||
tools:
|
|
||||||
- ai_query_top_contacts
|
|
||||||
- ai_query_topic_stats
|
|
||||||
- ai_query_session_glimpse
|
|
||||||
- ai_query_timeline
|
|
||||||
- ai_query_source_refs
|
|
||||||
---
|
|
||||||
你是“联系人关系聚焦”技能。
|
|
||||||
执行步骤:
|
|
||||||
1. 优先调用 ai_query_top_contacts 得到候选联系人排名。
|
|
||||||
2. 针对 Top 联系人读取抽样消息并补充时间轴。
|
|
||||||
3. 如果用户问题涉及“变化趋势”,补 ai_query_topic_stats。
|
|
||||||
4. 输出时必须给出对比口径(时间窗、样本范围、消息数量)。`
|
|
||||||
|
|
||||||
const SKILL_VOICE_AUDIT_MD = `---
|
|
||||||
id: voice_audit
|
|
||||||
name: 语音证据审计
|
|
||||||
description: 对语音消息进行“先列ID再转写再总结”的合规分析。
|
|
||||||
tags:
|
|
||||||
- voice
|
|
||||||
- audit
|
|
||||||
chatScope: all
|
|
||||||
tools:
|
|
||||||
- ai_list_voice_messages
|
|
||||||
- ai_transcribe_voice_messages
|
|
||||||
- ai_query_source_refs
|
|
||||||
---
|
|
||||||
你是“语音证据审计”技能。
|
|
||||||
硬规则:
|
|
||||||
1. 必须先调用 ai_list_voice_messages 获取语音 ID 清单。
|
|
||||||
2. 仅能转写用户明确指定的 ID,单轮最多 5 条。
|
|
||||||
3. 未转写成功的语音不得作为事实。
|
|
||||||
4. 输出包含“已转写 / 失败 / 待确认”三段。`
|
|
||||||
|
|
||||||
const BUILTIN_SKILLS = [
|
|
||||||
{ id: 'deep_timeline', raw: SKILL_DEEP_TIMELINE_MD },
|
|
||||||
{ id: 'contact_focus', raw: SKILL_CONTACT_FOCUS_MD },
|
|
||||||
{ id: 'voice_audit', raw: SKILL_VOICE_AUDIT_MD }
|
|
||||||
] as const
|
|
||||||
|
|
||||||
function normalizeText(value: unknown, fallback = ''): string {
|
|
||||||
const text = String(value ?? '').trim()
|
|
||||||
return text || fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseInlineList(text: string): string[] {
|
|
||||||
const raw = normalizeText(text)
|
|
||||||
if (!raw) return []
|
|
||||||
return raw
|
|
||||||
.split(',')
|
|
||||||
.map((item) => item.trim())
|
|
||||||
.filter(Boolean)
|
|
||||||
}
|
|
||||||
|
|
||||||
function splitFrontmatter(raw: string): { frontmatter: string; body: string } {
|
|
||||||
const normalized = String(raw || '')
|
|
||||||
if (!normalized.startsWith('---')) {
|
|
||||||
return { frontmatter: '', body: normalized.trim() }
|
|
||||||
}
|
|
||||||
const end = normalized.indexOf('\n---', 3)
|
|
||||||
if (end < 0) return { frontmatter: '', body: normalized.trim() }
|
|
||||||
return {
|
|
||||||
frontmatter: normalized.slice(3, end).trim(),
|
|
||||||
body: normalized.slice(end + 4).trim()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeChatScope(value: unknown): SkillChatScope {
|
|
||||||
const scope = normalizeText(value).toLowerCase()
|
|
||||||
if (scope === 'group' || scope === 'private') return scope
|
|
||||||
return 'all'
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseSkillMarkdown(raw: string): SkillDef {
|
|
||||||
const { frontmatter, body } = splitFrontmatter(raw)
|
|
||||||
const lines = frontmatter ? frontmatter.split('\n') : []
|
|
||||||
const data: Record<string, unknown> = {}
|
|
||||||
let currentArrayKey = ''
|
|
||||||
for (const line of lines) {
|
|
||||||
const trimmed = line.trim()
|
|
||||||
if (!trimmed) continue
|
|
||||||
const kv = trimmed.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/)
|
|
||||||
if (kv) {
|
|
||||||
const key = kv[1]
|
|
||||||
const value = kv[2]
|
|
||||||
if (!value) {
|
|
||||||
data[key] = []
|
|
||||||
currentArrayKey = key
|
|
||||||
} else {
|
|
||||||
data[key] = value
|
|
||||||
currentArrayKey = ''
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const arr = trimmed.match(/^- (.+)$/)
|
|
||||||
if (arr && currentArrayKey) {
|
|
||||||
const next = Array.isArray(data[currentArrayKey]) ? data[currentArrayKey] as string[] : []
|
|
||||||
next.push(arr[1].trim())
|
|
||||||
data[currentArrayKey] = next
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const id = normalizeText(data.id)
|
|
||||||
const name = normalizeText(data.name, id || 'skill')
|
|
||||||
const description = normalizeText(data.description)
|
|
||||||
const tags = Array.isArray(data.tags)
|
|
||||||
? (data.tags as string[]).map((item) => item.trim()).filter(Boolean)
|
|
||||||
: parseInlineList(String(data.tags || ''))
|
|
||||||
const tools = Array.isArray(data.tools)
|
|
||||||
? (data.tools as string[]).map((item) => item.trim()).filter(Boolean)
|
|
||||||
: parseInlineList(String(data.tools || ''))
|
|
||||||
const chatScope = normalizeChatScope(data.chatScope)
|
|
||||||
const builtinId = normalizeText(data.builtinId)
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
description,
|
|
||||||
tags,
|
|
||||||
chatScope,
|
|
||||||
tools,
|
|
||||||
prompt: body,
|
|
||||||
builtinId: builtinId || undefined
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function serializeSkillMarkdown(skill: SkillDef): string {
|
|
||||||
const lines = [
|
|
||||||
'---',
|
|
||||||
`id: ${skill.id}`,
|
|
||||||
`name: ${skill.name}`,
|
|
||||||
`description: ${skill.description}`,
|
|
||||||
`chatScope: ${skill.chatScope}`
|
|
||||||
]
|
|
||||||
if (skill.builtinId) lines.push(`builtinId: ${skill.builtinId}`)
|
|
||||||
if (skill.tags.length > 0) {
|
|
||||||
lines.push('tags:')
|
|
||||||
skill.tags.forEach((tag) => lines.push(` - ${tag}`))
|
|
||||||
}
|
|
||||||
if (skill.tools.length > 0) {
|
|
||||||
lines.push('tools:')
|
|
||||||
skill.tools.forEach((tool) => lines.push(` - ${tool}`))
|
|
||||||
}
|
|
||||||
lines.push('---')
|
|
||||||
lines.push('')
|
|
||||||
lines.push(skill.prompt || '')
|
|
||||||
return lines.join('\n')
|
|
||||||
}
|
|
||||||
|
|
||||||
class AiSkillService {
|
|
||||||
private readonly config = ConfigService.getInstance()
|
|
||||||
private initialized = false
|
|
||||||
private readonly cache = new Map<string, SkillDef>()
|
|
||||||
|
|
||||||
private getRootDirCandidates(): string[] {
|
|
||||||
const dbPath = normalizeText(this.config.get('dbPath'))
|
|
||||||
const wxid = normalizeText(this.config.get('myWxid'))
|
|
||||||
const roots: string[] = []
|
|
||||||
if (dbPath && wxid) {
|
|
||||||
roots.push(join(dbPath, wxid, 'db_storage', 'wf_ai_v2'))
|
|
||||||
roots.push(join(dbPath, wxid, 'db_storage', 'wf_ai'))
|
|
||||||
}
|
|
||||||
roots.push(join(process.cwd(), 'data', 'wf_ai_v2'))
|
|
||||||
return roots
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getRootDir(): Promise<string> {
|
|
||||||
const roots = this.getRootDirCandidates()
|
|
||||||
const dir = roots[0]
|
|
||||||
await mkdir(dir, { recursive: true })
|
|
||||||
return dir
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getSkillsDir(): Promise<string> {
|
|
||||||
const root = await this.getRootDir()
|
|
||||||
const dir = join(root, 'skills')
|
|
||||||
await mkdir(dir, { recursive: true })
|
|
||||||
return dir
|
|
||||||
}
|
|
||||||
|
|
||||||
private async ensureInitialized(): Promise<void> {
|
|
||||||
if (this.initialized) return
|
|
||||||
const dir = await this.getSkillsDir()
|
|
||||||
|
|
||||||
for (const builtin of BUILTIN_SKILLS) {
|
|
||||||
const filePath = join(dir, `${builtin.id}.md`)
|
|
||||||
if (!existsSync(filePath)) {
|
|
||||||
const parsed = parseSkillMarkdown(builtin.raw)
|
|
||||||
const config: SkillDef = {
|
|
||||||
...parsed,
|
|
||||||
builtinId: parsed.id
|
|
||||||
}
|
|
||||||
await writeFile(filePath, serializeSkillMarkdown(config), 'utf8')
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const raw = await readFile(filePath, 'utf8')
|
|
||||||
const parsed = parseSkillMarkdown(raw)
|
|
||||||
if (!parsed.builtinId) {
|
|
||||||
parsed.builtinId = builtin.id
|
|
||||||
await writeFile(filePath, serializeSkillMarkdown(parsed), 'utf8')
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// ignore broken file
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.cache.clear()
|
|
||||||
const files = await readdir(dir)
|
|
||||||
for (const fileName of files) {
|
|
||||||
if (!fileName.endsWith('.md')) continue
|
|
||||||
const filePath = join(dir, fileName)
|
|
||||||
try {
|
|
||||||
const raw = await readFile(filePath, 'utf8')
|
|
||||||
const parsed = parseSkillMarkdown(raw)
|
|
||||||
if (!parsed.id) continue
|
|
||||||
this.cache.set(parsed.id, parsed)
|
|
||||||
} catch {
|
|
||||||
// ignore broken file
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.initialized = true
|
|
||||||
}
|
|
||||||
|
|
||||||
async getAll(): Promise<SkillSummary[]> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
return Array.from(this.cache.values())
|
|
||||||
.sort((a, b) => a.name.localeCompare(b.name, 'zh-Hans-CN'))
|
|
||||||
.map((skill) => ({
|
|
||||||
id: skill.id,
|
|
||||||
name: skill.name,
|
|
||||||
description: skill.description,
|
|
||||||
tags: [...skill.tags],
|
|
||||||
chatScope: skill.chatScope,
|
|
||||||
tools: [...skill.tools],
|
|
||||||
builtinId: skill.builtinId
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
async getConfig(id: string): Promise<SkillDef | null> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const key = normalizeText(id)
|
|
||||||
const value = this.cache.get(key)
|
|
||||||
return value ? {
|
|
||||||
...value,
|
|
||||||
tags: [...value.tags],
|
|
||||||
tools: [...value.tools]
|
|
||||||
} : null
|
|
||||||
}
|
|
||||||
|
|
||||||
async create(rawMd: string): Promise<{ success: boolean; id?: string; error?: string }> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
try {
|
|
||||||
const parsed = parseSkillMarkdown(rawMd)
|
|
||||||
if (!parsed.id) return { success: false, error: '缺少 id' }
|
|
||||||
if (this.cache.has(parsed.id)) return { success: false, error: '技能 ID 已存在' }
|
|
||||||
const dir = await this.getSkillsDir()
|
|
||||||
await writeFile(join(dir, `${parsed.id}.md`), serializeSkillMarkdown(parsed), 'utf8')
|
|
||||||
this.cache.set(parsed.id, parsed)
|
|
||||||
return { success: true, id: parsed.id }
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: String((error as Error)?.message || error) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(id: string, rawMd: string): Promise<{ success: boolean; error?: string }> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const key = normalizeText(id)
|
|
||||||
const existing = this.cache.get(key)
|
|
||||||
if (!existing) return { success: false, error: '技能不存在' }
|
|
||||||
try {
|
|
||||||
const parsed = parseSkillMarkdown(rawMd)
|
|
||||||
parsed.id = key
|
|
||||||
if (existing.builtinId && !parsed.builtinId) parsed.builtinId = existing.builtinId
|
|
||||||
const dir = await this.getSkillsDir()
|
|
||||||
await writeFile(join(dir, `${key}.md`), serializeSkillMarkdown(parsed), 'utf8')
|
|
||||||
this.cache.set(key, parsed)
|
|
||||||
return { success: true }
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: String((error as Error)?.message || error) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async delete(id: string): Promise<{ success: boolean; error?: string }> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const key = normalizeText(id)
|
|
||||||
const dir = await this.getSkillsDir()
|
|
||||||
const filePath = join(dir, `${key}.md`)
|
|
||||||
if (existsSync(filePath)) {
|
|
||||||
await rm(filePath, { force: true })
|
|
||||||
}
|
|
||||||
this.cache.delete(key)
|
|
||||||
return { success: true }
|
|
||||||
}
|
|
||||||
|
|
||||||
async getBuiltinCatalog(): Promise<BuiltinSkillInfo[]> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
return BUILTIN_SKILLS.map((builtin) => {
|
|
||||||
const parsed = parseSkillMarkdown(builtin.raw)
|
|
||||||
const imported = Array.from(this.cache.values()).some((skill) => skill.builtinId === parsed.id || skill.id === parsed.id)
|
|
||||||
return {
|
|
||||||
id: parsed.id,
|
|
||||||
name: parsed.name,
|
|
||||||
description: parsed.description,
|
|
||||||
tags: parsed.tags,
|
|
||||||
chatScope: parsed.chatScope,
|
|
||||||
tools: parsed.tools,
|
|
||||||
imported
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async importFromMd(rawMd: string): Promise<{ success: boolean; id?: string; error?: string }> {
|
|
||||||
return this.create(rawMd)
|
|
||||||
}
|
|
||||||
|
|
||||||
async getAutoSkillMenu(
|
|
||||||
chatScope: SkillChatScope,
|
|
||||||
allowedTools?: string[]
|
|
||||||
): Promise<string | null> {
|
|
||||||
await this.ensureInitialized()
|
|
||||||
const compatible = Array.from(this.cache.values()).filter((skill) => {
|
|
||||||
if (skill.chatScope !== 'all' && skill.chatScope !== chatScope) return false
|
|
||||||
if (!allowedTools || allowedTools.length === 0) return true
|
|
||||||
return skill.tools.every((tool) => allowedTools.includes(tool))
|
|
||||||
})
|
|
||||||
if (compatible.length === 0) return null
|
|
||||||
const lines = compatible.slice(0, 15).map((skill) => `- ${skill.id}: ${skill.name} - ${skill.description}`)
|
|
||||||
return [
|
|
||||||
'你可以按需调用工具 activate_skill 以激活对应技能。',
|
|
||||||
'当用户问题明显匹配某个技能时,先调用 activate_skill 获取执行手册。',
|
|
||||||
'若问题简单或不匹配技能,可直接回答。',
|
|
||||||
'',
|
|
||||||
...lines
|
|
||||||
].join('\n')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const aiSkillService = new AiSkillService()
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -71,19 +71,6 @@ interface ConfigSchema {
|
|||||||
exportWriteLayout: 'A' | 'B' | 'C'
|
exportWriteLayout: 'A' | 'B' | 'C'
|
||||||
|
|
||||||
// AI 见解
|
// AI 见解
|
||||||
aiModelApiBaseUrl: string
|
|
||||||
aiModelApiKey: string
|
|
||||||
aiModelApiModel: string
|
|
||||||
aiAgentMaxMessagesPerRequest: number
|
|
||||||
aiAgentMaxHistoryRounds: number
|
|
||||||
aiAgentEnableAutoSkill: boolean
|
|
||||||
aiAgentSearchContextBefore: number
|
|
||||||
aiAgentSearchContextAfter: number
|
|
||||||
aiAgentPreprocessClean: boolean
|
|
||||||
aiAgentPreprocessMerge: boolean
|
|
||||||
aiAgentPreprocessDenoise: boolean
|
|
||||||
aiAgentPreprocessDesensitize: boolean
|
|
||||||
aiAgentPreprocessAnonymize: boolean
|
|
||||||
aiInsightEnabled: boolean
|
aiInsightEnabled: boolean
|
||||||
aiInsightApiBaseUrl: string
|
aiInsightApiBaseUrl: string
|
||||||
aiInsightApiKey: string
|
aiInsightApiKey: string
|
||||||
@@ -106,21 +93,10 @@ interface ConfigSchema {
|
|||||||
aiInsightTelegramToken: string
|
aiInsightTelegramToken: string
|
||||||
/** Telegram 接收 Chat ID,逗号分隔,支持多个 */
|
/** Telegram 接收 Chat ID,逗号分隔,支持多个 */
|
||||||
aiInsightTelegramChatIds: string
|
aiInsightTelegramChatIds: string
|
||||||
|
|
||||||
// AI 足迹
|
|
||||||
aiFootprintEnabled: boolean
|
|
||||||
aiFootprintSystemPrompt: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 需要 safeStorage 加密的字段(普通模式)
|
// 需要 safeStorage 加密的字段(普通模式)
|
||||||
const ENCRYPTED_STRING_KEYS: Set<string> = new Set([
|
const ENCRYPTED_STRING_KEYS: Set<string> = new Set(['decryptKey', 'imageAesKey', 'authPassword', 'httpApiToken', 'aiInsightApiKey'])
|
||||||
'decryptKey',
|
|
||||||
'imageAesKey',
|
|
||||||
'authPassword',
|
|
||||||
'httpApiToken',
|
|
||||||
'aiModelApiKey',
|
|
||||||
'aiInsightApiKey'
|
|
||||||
])
|
|
||||||
const ENCRYPTED_BOOL_KEYS: Set<string> = new Set(['authEnabled', 'authUseHello'])
|
const ENCRYPTED_BOOL_KEYS: Set<string> = new Set(['authEnabled', 'authUseHello'])
|
||||||
const ENCRYPTED_NUMBER_KEYS: Set<string> = new Set(['imageXorKey'])
|
const ENCRYPTED_NUMBER_KEYS: Set<string> = new Set(['imageXorKey'])
|
||||||
|
|
||||||
@@ -191,19 +167,6 @@ export class ConfigService {
|
|||||||
quoteLayout: 'quote-top',
|
quoteLayout: 'quote-top',
|
||||||
wordCloudExcludeWords: [],
|
wordCloudExcludeWords: [],
|
||||||
exportWriteLayout: 'A',
|
exportWriteLayout: 'A',
|
||||||
aiModelApiBaseUrl: '',
|
|
||||||
aiModelApiKey: '',
|
|
||||||
aiModelApiModel: 'gpt-4o-mini',
|
|
||||||
aiAgentMaxMessagesPerRequest: 120,
|
|
||||||
aiAgentMaxHistoryRounds: 12,
|
|
||||||
aiAgentEnableAutoSkill: true,
|
|
||||||
aiAgentSearchContextBefore: 3,
|
|
||||||
aiAgentSearchContextAfter: 3,
|
|
||||||
aiAgentPreprocessClean: true,
|
|
||||||
aiAgentPreprocessMerge: true,
|
|
||||||
aiAgentPreprocessDenoise: true,
|
|
||||||
aiAgentPreprocessDesensitize: false,
|
|
||||||
aiAgentPreprocessAnonymize: false,
|
|
||||||
aiInsightEnabled: false,
|
aiInsightEnabled: false,
|
||||||
aiInsightApiBaseUrl: '',
|
aiInsightApiBaseUrl: '',
|
||||||
aiInsightApiKey: '',
|
aiInsightApiKey: '',
|
||||||
@@ -218,9 +181,7 @@ export class ConfigService {
|
|||||||
aiInsightSystemPrompt: '',
|
aiInsightSystemPrompt: '',
|
||||||
aiInsightTelegramEnabled: false,
|
aiInsightTelegramEnabled: false,
|
||||||
aiInsightTelegramToken: '',
|
aiInsightTelegramToken: '',
|
||||||
aiInsightTelegramChatIds: '',
|
aiInsightTelegramChatIds: ''
|
||||||
aiFootprintEnabled: false,
|
|
||||||
aiFootprintSystemPrompt: ''
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const storeOptions: any = {
|
const storeOptions: any = {
|
||||||
@@ -252,7 +213,6 @@ export class ConfigService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.migrateAuthFields()
|
this.migrateAuthFields()
|
||||||
this.migrateAiConfig()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// === 状态查询 ===
|
// === 状态查询 ===
|
||||||
@@ -310,9 +270,7 @@ export class ConfigService {
|
|||||||
const inLockMode = this.isLockMode() && this.unlockPassword
|
const inLockMode = this.isLockMode() && this.unlockPassword
|
||||||
|
|
||||||
if (ENCRYPTED_BOOL_KEYS.has(key)) {
|
if (ENCRYPTED_BOOL_KEYS.has(key)) {
|
||||||
const boolValue = value === true || value === 'true'
|
toStore = this.safeEncrypt(String(value)) as ConfigSchema[K]
|
||||||
// `false` 不需要写入 keychain,避免无意义触发 macOS 钥匙串弹窗
|
|
||||||
toStore = (boolValue ? this.safeEncrypt('true') : false) as ConfigSchema[K]
|
|
||||||
} else if (ENCRYPTED_NUMBER_KEYS.has(key)) {
|
} else if (ENCRYPTED_NUMBER_KEYS.has(key)) {
|
||||||
if (inLockMode && LOCKABLE_NUMBER_KEYS.has(key)) {
|
if (inLockMode && LOCKABLE_NUMBER_KEYS.has(key)) {
|
||||||
toStore = this.lockEncrypt(String(value), this.unlockPassword!) as ConfigSchema[K]
|
toStore = this.lockEncrypt(String(value), this.unlockPassword!) as ConfigSchema[K]
|
||||||
@@ -691,7 +649,7 @@ export class ConfigService {
|
|||||||
|
|
||||||
clearHelloSecret(): void {
|
clearHelloSecret(): void {
|
||||||
this.store.set('authHelloSecret', '' as any)
|
this.store.set('authHelloSecret', '' as any)
|
||||||
this.store.set('authUseHello', false as any)
|
this.store.set('authUseHello', this.safeEncrypt('false') as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
// === 迁移 ===
|
// === 迁移 ===
|
||||||
@@ -700,18 +658,13 @@ export class ConfigService {
|
|||||||
// 将旧版明文 auth 字段迁移为 safeStorage 加密格式
|
// 将旧版明文 auth 字段迁移为 safeStorage 加密格式
|
||||||
// 如果已经是 safe: 或 lock: 前缀则跳过
|
// 如果已经是 safe: 或 lock: 前缀则跳过
|
||||||
const rawEnabled: any = this.store.get('authEnabled')
|
const rawEnabled: any = this.store.get('authEnabled')
|
||||||
if (rawEnabled === true || rawEnabled === 'true') {
|
if (typeof rawEnabled === 'boolean') {
|
||||||
this.store.set('authEnabled', this.safeEncrypt('true') as any)
|
this.store.set('authEnabled', this.safeEncrypt(String(rawEnabled)) as any)
|
||||||
} else if (rawEnabled === false || rawEnabled === 'false') {
|
|
||||||
// 保持 false 为明文布尔,避免冷启动访问 keychain
|
|
||||||
this.store.set('authEnabled', false as any)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawUseHello: any = this.store.get('authUseHello')
|
const rawUseHello: any = this.store.get('authUseHello')
|
||||||
if (rawUseHello === true || rawUseHello === 'true') {
|
if (typeof rawUseHello === 'boolean') {
|
||||||
this.store.set('authUseHello', this.safeEncrypt('true') as any)
|
this.store.set('authUseHello', this.safeEncrypt(String(rawUseHello)) as any)
|
||||||
} else if (rawUseHello === false || rawUseHello === 'false') {
|
|
||||||
this.store.set('authUseHello', false as any)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawPassword: any = this.store.get('authPassword')
|
const rawPassword: any = this.store.get('authPassword')
|
||||||
@@ -757,26 +710,6 @@ export class ConfigService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private migrateAiConfig(): void {
|
|
||||||
const sharedBaseUrl = String(this.get('aiModelApiBaseUrl') || '').trim()
|
|
||||||
const sharedApiKey = String(this.get('aiModelApiKey') || '').trim()
|
|
||||||
const sharedModel = String(this.get('aiModelApiModel') || '').trim()
|
|
||||||
|
|
||||||
const legacyBaseUrl = String(this.get('aiInsightApiBaseUrl') || '').trim()
|
|
||||||
const legacyApiKey = String(this.get('aiInsightApiKey') || '').trim()
|
|
||||||
const legacyModel = String(this.get('aiInsightApiModel') || '').trim()
|
|
||||||
|
|
||||||
if (!sharedBaseUrl && legacyBaseUrl) {
|
|
||||||
this.set('aiModelApiBaseUrl', legacyBaseUrl)
|
|
||||||
}
|
|
||||||
if (!sharedApiKey && legacyApiKey) {
|
|
||||||
this.set('aiModelApiKey', legacyApiKey)
|
|
||||||
}
|
|
||||||
if (!sharedModel && legacyModel) {
|
|
||||||
this.set('aiModelApiModel', legacyModel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// === 验证 ===
|
// === 验证 ===
|
||||||
|
|
||||||
verifyAuthEnabled(): boolean {
|
verifyAuthEnabled(): boolean {
|
||||||
@@ -796,7 +729,7 @@ export class ConfigService {
|
|||||||
// === 工具方法 ===
|
// === 工具方法 ===
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取当前 wxid 对应的图片密钥,优先从 wxidConfigs 中取,找不到则回退到全局配置
|
* 获取当前 wxid 对应的图片密钥,优先从 wxidConfigs 中取,找不到则回退到全局<EFBFBD><EFBFBD>置
|
||||||
*/
|
*/
|
||||||
getImageKeysForCurrentWxid(): { xorKey: unknown; aesKey: string } {
|
getImageKeysForCurrentWxid(): { xorKey: unknown; aesKey: string } {
|
||||||
const wxid = this.get('myWxid')
|
const wxid = this.get('myWxid')
|
||||||
|
|||||||
@@ -19,8 +19,7 @@ class ExportRecordService {
|
|||||||
|
|
||||||
private resolveFilePath(): string {
|
private resolveFilePath(): string {
|
||||||
if (this.filePath) return this.filePath
|
if (this.filePath) return this.filePath
|
||||||
const workerUserDataPath = String(process.env.WEFLOW_USER_DATA_PATH || process.env.WEFLOW_CONFIG_CWD || '').trim()
|
const userDataPath = app.getPath('userData')
|
||||||
const userDataPath = workerUserDataPath || app?.getPath?.('userData') || process.cwd()
|
|
||||||
fs.mkdirSync(userDataPath, { recursive: true })
|
fs.mkdirSync(userDataPath, { recursive: true })
|
||||||
this.filePath = path.join(userDataPath, 'weflow-export-records.json')
|
this.filePath = path.join(userDataPath, 'weflow-export-records.json')
|
||||||
return this.filePath
|
return this.filePath
|
||||||
|
|||||||
@@ -949,7 +949,7 @@ export class ImageDecryptService {
|
|||||||
} catch { }
|
} catch { }
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 策略 B: 新版 Session 哈希路径猜测 ---
|
// --- 绛栫暐 B: 鏂扮増 Session 鍝堝笇璺緞鐚滄祴 ---
|
||||||
try {
|
try {
|
||||||
const entries = await fs.readdir(root, { withFileTypes: true })
|
const entries = await fs.readdir(root, { withFileTypes: true })
|
||||||
const sessionDirs = entries
|
const sessionDirs = entries
|
||||||
@@ -1854,7 +1854,7 @@ export class ImageDecryptService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从 wxgf 数据中提取 HEVC NALU 裸流
|
* 浠?wxgf 鏁版嵁涓彁鍙?HEVC NALU 瑁告祦
|
||||||
*/
|
*/
|
||||||
private extractHevcNalu(buffer: Buffer): Buffer | null {
|
private extractHevcNalu(buffer: Buffer): Buffer | null {
|
||||||
const nalUnits: Buffer[] = []
|
const nalUnits: Buffer[] = []
|
||||||
|
|||||||
@@ -39,9 +39,6 @@ const DEFAULT_SILENCE_DAYS = 3
|
|||||||
const INSIGHT_CONFIG_KEYS = new Set([
|
const INSIGHT_CONFIG_KEYS = new Set([
|
||||||
'aiInsightEnabled',
|
'aiInsightEnabled',
|
||||||
'aiInsightScanIntervalHours',
|
'aiInsightScanIntervalHours',
|
||||||
'aiModelApiBaseUrl',
|
|
||||||
'aiModelApiKey',
|
|
||||||
'aiModelApiModel',
|
|
||||||
'dbPath',
|
'dbPath',
|
||||||
'decryptKey',
|
'decryptKey',
|
||||||
'myWxid'
|
'myWxid'
|
||||||
@@ -54,12 +51,6 @@ interface TodayTriggerRecord {
|
|||||||
timestamps: number[]
|
timestamps: number[]
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SharedAiModelConfig {
|
|
||||||
apiBaseUrl: string
|
|
||||||
apiKey: string
|
|
||||||
model: string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── 日志 ─────────────────────────────────────────────────────────────────────
|
// ─── 日志 ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -325,11 +316,13 @@ class InsightService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 测试 API 连接,返回 { success, message }。
|
* 测<EFBFBD><EFBFBD><EFBFBD> API 连接,返回 { success, message }。
|
||||||
* 供设置页"测试连接"按钮调用。
|
* 供设置页"测试连接"按钮调用。
|
||||||
*/
|
*/
|
||||||
async testConnection(): Promise<{ success: boolean; message: string }> {
|
async testConnection(): Promise<{ success: boolean; message: string }> {
|
||||||
const { apiBaseUrl, apiKey, model } = this.getSharedAiModelConfig()
|
const apiBaseUrl = this.config.get('aiInsightApiBaseUrl') as string
|
||||||
|
const apiKey = this.config.get('aiInsightApiKey') as string
|
||||||
|
const model = (this.config.get('aiInsightApiModel') as string) || 'gpt-4o-mini'
|
||||||
|
|
||||||
if (!apiBaseUrl || !apiKey) {
|
if (!apiBaseUrl || !apiKey) {
|
||||||
return { success: false, message: '请先填写 API 地址和 API Key' }
|
return { success: false, message: '请先填写 API 地址和 API Key' }
|
||||||
@@ -355,7 +348,8 @@ class InsightService {
|
|||||||
*/
|
*/
|
||||||
async triggerTest(): Promise<{ success: boolean; message: string }> {
|
async triggerTest(): Promise<{ success: boolean; message: string }> {
|
||||||
insightLog('INFO', '手动触发测试见解...')
|
insightLog('INFO', '手动触发测试见解...')
|
||||||
const { apiBaseUrl, apiKey } = this.getSharedAiModelConfig()
|
const apiBaseUrl = this.config.get('aiInsightApiBaseUrl') as string
|
||||||
|
const apiKey = this.config.get('aiInsightApiKey') as string
|
||||||
if (!apiBaseUrl || !apiKey) {
|
if (!apiBaseUrl || !apiKey) {
|
||||||
return { success: false, message: '请先填写 API 地址和 Key' }
|
return { success: false, message: '请先填写 API 地址和 Key' }
|
||||||
}
|
}
|
||||||
@@ -404,124 +398,12 @@ class InsightService {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
async generateFootprintInsight(params: {
|
|
||||||
rangeLabel: string
|
|
||||||
summary: {
|
|
||||||
private_inbound_people?: number
|
|
||||||
private_replied_people?: number
|
|
||||||
private_outbound_people?: number
|
|
||||||
private_reply_rate?: number
|
|
||||||
mention_count?: number
|
|
||||||
mention_group_count?: number
|
|
||||||
}
|
|
||||||
privateSegments?: Array<{ displayName?: string; session_id?: string; incoming_count?: number; outgoing_count?: number; message_count?: number; replied?: boolean }>
|
|
||||||
mentionGroups?: Array<{ displayName?: string; session_id?: string; count?: number }>
|
|
||||||
}): Promise<{ success: boolean; message: string; insight?: string }> {
|
|
||||||
const enabled = this.config.get('aiFootprintEnabled') === true
|
|
||||||
if (!enabled) {
|
|
||||||
return { success: false, message: '请先在设置中开启「AI 足迹总结」' }
|
|
||||||
}
|
|
||||||
|
|
||||||
const { apiBaseUrl, apiKey, model } = this.getSharedAiModelConfig()
|
|
||||||
if (!apiBaseUrl || !apiKey) {
|
|
||||||
return { success: false, message: '请先填写通用 AI 模型配置(API 地址和 Key)' }
|
|
||||||
}
|
|
||||||
|
|
||||||
const summary = params?.summary || {}
|
|
||||||
const rangeLabel = String(params?.rangeLabel || '').trim() || '当前范围'
|
|
||||||
const privateSegments = Array.isArray(params?.privateSegments) ? params.privateSegments.slice(0, 6) : []
|
|
||||||
const mentionGroups = Array.isArray(params?.mentionGroups) ? params.mentionGroups.slice(0, 6) : []
|
|
||||||
|
|
||||||
const topPrivateText = privateSegments.length > 0
|
|
||||||
? privateSegments
|
|
||||||
.map((item, idx) => {
|
|
||||||
const name = String(item.displayName || item.session_id || `联系人${idx + 1}`).trim()
|
|
||||||
const inbound = Number(item.incoming_count) || 0
|
|
||||||
const outbound = Number(item.outgoing_count) || 0
|
|
||||||
const total = Math.max(Number(item.message_count) || 0, inbound + outbound)
|
|
||||||
return `${idx + 1}. ${name}(收${inbound}/发${outbound}/总${total}${item.replied ? '/已回复' : ''})`
|
|
||||||
})
|
|
||||||
.join('\n')
|
|
||||||
: '无'
|
|
||||||
|
|
||||||
const topMentionText = mentionGroups.length > 0
|
|
||||||
? mentionGroups
|
|
||||||
.map((item, idx) => {
|
|
||||||
const name = String(item.displayName || item.session_id || `群聊${idx + 1}`).trim()
|
|
||||||
const count = Number(item.count) || 0
|
|
||||||
return `${idx + 1}. ${name}(@我 ${count} 次)`
|
|
||||||
})
|
|
||||||
.join('\n')
|
|
||||||
: '无'
|
|
||||||
|
|
||||||
const defaultSystemPrompt = `你是用户的聊天足迹教练,负责基于统计数据给出一段简明复盘。
|
|
||||||
要求:
|
|
||||||
1. 输出 2-3 句,总长度不超过 180 字。
|
|
||||||
2. 必须包含:总体观察 + 一个可执行建议。
|
|
||||||
3. 语气务实,不夸张,不使用 Markdown。`
|
|
||||||
const customPrompt = String(this.config.get('aiFootprintSystemPrompt') || '').trim()
|
|
||||||
const systemPrompt = customPrompt || defaultSystemPrompt
|
|
||||||
|
|
||||||
const userPrompt = `统计范围:${rangeLabel}
|
|
||||||
有聊天的人数:${Number(summary.private_inbound_people) || 0}
|
|
||||||
我有回复的人数:${Number(summary.private_outbound_people) || 0}
|
|
||||||
回复率:${(((Number(summary.private_reply_rate) || 0) * 100)).toFixed(1)}%
|
|
||||||
@我次数:${Number(summary.mention_count) || 0}
|
|
||||||
涉及群聊:${Number(summary.mention_group_count) || 0}
|
|
||||||
|
|
||||||
私聊重点:
|
|
||||||
${topPrivateText}
|
|
||||||
|
|
||||||
群聊@我重点:
|
|
||||||
${topMentionText}
|
|
||||||
|
|
||||||
请给出足迹复盘(2-3句,含建议):`
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await callApi(
|
|
||||||
apiBaseUrl,
|
|
||||||
apiKey,
|
|
||||||
model,
|
|
||||||
[
|
|
||||||
{ role: 'system', content: systemPrompt },
|
|
||||||
{ role: 'user', content: userPrompt }
|
|
||||||
],
|
|
||||||
25_000
|
|
||||||
)
|
|
||||||
const insight = result.trim().slice(0, 400)
|
|
||||||
if (!insight) return { success: false, message: '模型返回为空' }
|
|
||||||
return { success: true, message: '生成成功', insight }
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, message: `生成失败:${(error as Error).message}` }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 私有方法 ────────────────────────────────────────────────────────────────
|
// ── 私有方法 ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
private isEnabled(): boolean {
|
private isEnabled(): boolean {
|
||||||
return this.config.get('aiInsightEnabled') === true
|
return this.config.get('aiInsightEnabled') === true
|
||||||
}
|
}
|
||||||
|
|
||||||
private getSharedAiModelConfig(): SharedAiModelConfig {
|
|
||||||
const apiBaseUrl = String(
|
|
||||||
this.config.get('aiModelApiBaseUrl')
|
|
||||||
|| this.config.get('aiInsightApiBaseUrl')
|
|
||||||
|| ''
|
|
||||||
).trim()
|
|
||||||
const apiKey = String(
|
|
||||||
this.config.get('aiModelApiKey')
|
|
||||||
|| this.config.get('aiInsightApiKey')
|
|
||||||
|| ''
|
|
||||||
).trim()
|
|
||||||
const model = String(
|
|
||||||
this.config.get('aiModelApiModel')
|
|
||||||
|| this.config.get('aiInsightApiModel')
|
|
||||||
|| 'gpt-4o-mini'
|
|
||||||
).trim() || 'gpt-4o-mini'
|
|
||||||
|
|
||||||
return { apiBaseUrl, apiKey, model }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 判断某个会话是否允许触发见解。
|
* 判断某个会话是否允许触发见解。
|
||||||
* 若白名单未启用,则所有私聊会话均允许;
|
* 若白名单未启用,则所有私聊会话均允许;
|
||||||
@@ -593,7 +475,7 @@ ${topMentionText}
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取今日全局已触发次数(所有会话合计),用于 prompt 中告知模型全局上下文。
|
* 获取今日全局已触发次数(所有会话合计),用于 prompt 中告知模<EFBFBD><EFBFBD><EFBFBD>全局上下文。
|
||||||
*/
|
*/
|
||||||
private getTodayTotalTriggerCount(): number {
|
private getTodayTotalTriggerCount(): number {
|
||||||
this.resetIfNewDay()
|
this.resetIfNewDay()
|
||||||
@@ -814,7 +696,9 @@ ${topMentionText}
|
|||||||
if (!sessionId) return
|
if (!sessionId) return
|
||||||
if (!this.isEnabled()) return
|
if (!this.isEnabled()) return
|
||||||
|
|
||||||
const { apiBaseUrl, apiKey, model } = this.getSharedAiModelConfig()
|
const apiBaseUrl = this.config.get('aiInsightApiBaseUrl') as string
|
||||||
|
const apiKey = this.config.get('aiInsightApiKey') as string
|
||||||
|
const model = (this.config.get('aiInsightApiModel') as string) || 'gpt-4o-mini'
|
||||||
const allowContext = this.config.get('aiInsightAllowContext') as boolean
|
const allowContext = this.config.get('aiInsightAllowContext') as boolean
|
||||||
const contextCount = (this.config.get('aiInsightContextCount') as number) || 40
|
const contextCount = (this.config.get('aiInsightContextCount') as number) || 40
|
||||||
|
|
||||||
@@ -825,7 +709,7 @@ ${topMentionText}
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── 构建 prompt ────────────────────────────────────────────────────────────
|
// ── 构建 prompt ─────────────<EFBFBD><EFBFBD><EFBFBD>───────────────────────────────<EFBFBD><EFBFBD><EFBFBD>────────────
|
||||||
|
|
||||||
// 今日触发统计(让模型具备时间与克制感)
|
// 今日触发统计(让模型具备时间与克制感)
|
||||||
const sessionTriggerTimes = this.recordTrigger(sessionId)
|
const sessionTriggerTimes = this.recordTrigger(sessionId)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { app, shell } from 'electron'
|
import { app, shell } from 'electron'
|
||||||
import { join, basename, dirname } from 'path'
|
import { join, basename, dirname } from 'path'
|
||||||
import { existsSync, readdirSync, readFileSync, statSync, chmodSync } from 'fs'
|
import { existsSync, readdirSync, readFileSync, statSync } from 'fs'
|
||||||
import { execFile, spawn } from 'child_process'
|
import { execFile, spawn } from 'child_process'
|
||||||
import { promisify } from 'util'
|
import { promisify } from 'util'
|
||||||
import crypto from 'crypto'
|
import crypto from 'crypto'
|
||||||
@@ -403,71 +403,19 @@ export class KeyServiceMac {
|
|||||||
return `'${String(text).replace(/'/g, `'\\''`)}'`
|
return `'${String(text).replace(/'/g, `'\\''`)}'`
|
||||||
}
|
}
|
||||||
|
|
||||||
private collectMacKeyArtifactPaths(primaryBinaryPath: string): string[] {
|
|
||||||
const baseDir = dirname(primaryBinaryPath)
|
|
||||||
const names = ['xkey_helper', 'image_scan_helper', 'xkey_helper_macos', 'libwx_key.dylib']
|
|
||||||
const unique: string[] = []
|
|
||||||
for (const name of names) {
|
|
||||||
const full = join(baseDir, name)
|
|
||||||
if (!existsSync(full)) continue
|
|
||||||
if (!unique.includes(full)) unique.push(full)
|
|
||||||
}
|
|
||||||
if (existsSync(primaryBinaryPath) && !unique.includes(primaryBinaryPath)) {
|
|
||||||
unique.unshift(primaryBinaryPath)
|
|
||||||
}
|
|
||||||
return unique
|
|
||||||
}
|
|
||||||
|
|
||||||
private ensureExecutableBitsBestEffort(paths: string[]): void {
|
|
||||||
for (const p of paths) {
|
|
||||||
try {
|
|
||||||
const mode = statSync(p).mode
|
|
||||||
if ((mode & 0o111) !== 0) continue
|
|
||||||
chmodSync(p, mode | 0o111)
|
|
||||||
} catch {
|
|
||||||
// ignore: 可能无权限(例如 /Applications 下 root-owned 的 .app)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async ensureExecutableBitsWithElevation(paths: string[], timeoutMs: number): Promise<void> {
|
|
||||||
const existing = paths.filter(p => existsSync(p))
|
|
||||||
if (existing.length === 0) return
|
|
||||||
|
|
||||||
const quotedPaths = existing.map(p => this.shellSingleQuote(p)).join(' ')
|
|
||||||
const timeoutSec = Math.max(30, Math.ceil(timeoutMs / 1000))
|
|
||||||
const scriptLines = [
|
|
||||||
`set chmodCmd to "/bin/chmod +x ${quotedPaths}"`,
|
|
||||||
`set timeoutSec to ${timeoutSec}`,
|
|
||||||
'with timeout of timeoutSec seconds',
|
|
||||||
'do shell script chmodCmd with administrator privileges',
|
|
||||||
'end timeout'
|
|
||||||
]
|
|
||||||
|
|
||||||
await execFileAsync('/usr/bin/osascript', scriptLines.flatMap(line => ['-e', line]), {
|
|
||||||
timeout: timeoutMs + 10_000
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getDbKeyByHelperElevated(
|
private async getDbKeyByHelperElevated(
|
||||||
timeoutMs: number,
|
timeoutMs: number,
|
||||||
onStatus?: (message: string, level: number) => void
|
onStatus?: (message: string, level: number) => void
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const helperPath = this.getHelperPath()
|
const helperPath = this.getHelperPath()
|
||||||
const artifactPaths = this.collectMacKeyArtifactPaths(helperPath)
|
|
||||||
this.ensureExecutableBitsBestEffort(artifactPaths)
|
|
||||||
const waitMs = Math.max(timeoutMs, 30_000)
|
const waitMs = Math.max(timeoutMs, 30_000)
|
||||||
const timeoutSec = Math.ceil(waitMs / 1000) + 30
|
const timeoutSec = Math.ceil(waitMs / 1000) + 30
|
||||||
const pid = await this.getWeChatPid()
|
const pid = await this.getWeChatPid()
|
||||||
const chmodPart = artifactPaths.length > 0
|
|
||||||
? `/bin/chmod +x ${artifactPaths.map(p => this.shellSingleQuote(p)).join(' ')}`
|
|
||||||
: ''
|
|
||||||
const runPart = `${this.shellSingleQuote(helperPath)} ${pid} ${waitMs}`
|
|
||||||
const privilegedCmd = chmodPart ? `${chmodPart} && ${runPart}` : runPart
|
|
||||||
// 用 AppleScript 的 quoted form 组装命令,避免复杂 shell 拼接导致整条失败
|
// 用 AppleScript 的 quoted form 组装命令,避免复杂 shell 拼接导致整条失败
|
||||||
// 通过 try/on error 回传详细错误,避免只看到 "Command failed"
|
// 通过 try/on error 回传详细错误,避免只看到 "Command failed"
|
||||||
const scriptLines = [
|
const scriptLines = [
|
||||||
`set cmd to ${JSON.stringify(privilegedCmd)}`,
|
`set helperPath to ${JSON.stringify(helperPath)}`,
|
||||||
|
`set cmd to quoted form of helperPath & " ${pid} ${waitMs}"`,
|
||||||
`set timeoutSec to ${timeoutSec}`,
|
`set timeoutSec to ${timeoutSec}`,
|
||||||
'try',
|
'try',
|
||||||
'with timeout of timeoutSec seconds',
|
'with timeout of timeoutSec seconds',
|
||||||
@@ -803,12 +751,10 @@ export class KeyServiceMac {
|
|||||||
try {
|
try {
|
||||||
const helperPath = this.getImageScanHelperPath()
|
const helperPath = this.getImageScanHelperPath()
|
||||||
const ciphertextHex = ciphertext.toString('hex')
|
const ciphertextHex = ciphertext.toString('hex')
|
||||||
const artifactPaths = this.collectMacKeyArtifactPaths(helperPath)
|
|
||||||
this.ensureExecutableBitsBestEffort(artifactPaths)
|
|
||||||
|
|
||||||
// 1) 直接运行 helper(有正式签名的 debugger entitlement 时可用)
|
// 1) 直接运行 helper(有正式签名的 debugger entitlement 时可用)
|
||||||
if (!this._needsElevation) {
|
if (!this._needsElevation) {
|
||||||
const direct = await this._spawnScanHelper(helperPath, pid, ciphertextHex, false, artifactPaths)
|
const direct = await this._spawnScanHelper(helperPath, pid, ciphertextHex, false)
|
||||||
if (direct.key) return direct.key
|
if (direct.key) return direct.key
|
||||||
if (direct.permissionError) {
|
if (direct.permissionError) {
|
||||||
console.warn('[KeyServiceMac] task_for_pid 权限不足,切换到 osascript 提权模式')
|
console.warn('[KeyServiceMac] task_for_pid 权限不足,切换到 osascript 提权模式')
|
||||||
@@ -819,12 +765,7 @@ export class KeyServiceMac {
|
|||||||
|
|
||||||
// 2) 通过 osascript 以管理员权限运行 helper(SIP 下 ad-hoc 签名无法获取 task_for_pid)
|
// 2) 通过 osascript 以管理员权限运行 helper(SIP 下 ad-hoc 签名无法获取 task_for_pid)
|
||||||
if (this._needsElevation) {
|
if (this._needsElevation) {
|
||||||
try {
|
const elevated = await this._spawnScanHelper(helperPath, pid, ciphertextHex, true)
|
||||||
await this.ensureExecutableBitsWithElevation(artifactPaths, 45_000)
|
|
||||||
} catch (e: any) {
|
|
||||||
console.warn('[KeyServiceMac] elevated chmod failed before image scan:', e?.message || e)
|
|
||||||
}
|
|
||||||
const elevated = await this._spawnScanHelper(helperPath, pid, ciphertextHex, true, artifactPaths)
|
|
||||||
if (elevated.key) return elevated.key
|
if (elevated.key) return elevated.key
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -927,19 +868,12 @@ export class KeyServiceMac {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _spawnScanHelper(
|
private _spawnScanHelper(
|
||||||
helperPath: string,
|
helperPath: string, pid: number, ciphertextHex: string, elevated: boolean
|
||||||
pid: number,
|
|
||||||
ciphertextHex: string,
|
|
||||||
elevated: boolean,
|
|
||||||
artifactPaths: string[] = []
|
|
||||||
): Promise<{ key: string | null; permissionError: boolean }> {
|
): Promise<{ key: string | null; permissionError: boolean }> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let child: ReturnType<typeof spawn>
|
let child: ReturnType<typeof spawn>
|
||||||
if (elevated) {
|
if (elevated) {
|
||||||
const chmodPart = artifactPaths.length > 0
|
const shellCmd = `'${helperPath}' ${pid} ${ciphertextHex}`
|
||||||
? `/bin/chmod +x ${artifactPaths.map(p => this.shellSingleQuote(p)).join(' ')} && `
|
|
||||||
: ''
|
|
||||||
const shellCmd = `${chmodPart}${this.shellSingleQuote(helperPath)} ${pid} ${ciphertextHex}`
|
|
||||||
child = spawn('/usr/bin/osascript', ['-e', `do shell script ${JSON.stringify(shellCmd)} with administrator privileges`],
|
child = spawn('/usr/bin/osascript', ['-e', `do shell script ${JSON.stringify(shellCmd)} with administrator privileges`],
|
||||||
{ stdio: ['ignore', 'pipe', 'pipe'] })
|
{ stdio: ['ignore', 'pipe', 'pipe'] })
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -58,7 +58,6 @@ export class WcdbCore {
|
|||||||
private wcdbGetAnnualReportExtras: any = null
|
private wcdbGetAnnualReportExtras: any = null
|
||||||
private wcdbGetDualReportStats: any = null
|
private wcdbGetDualReportStats: any = null
|
||||||
private wcdbGetGroupStats: any = null
|
private wcdbGetGroupStats: any = null
|
||||||
private wcdbGetMyFootprintStats: any = null
|
|
||||||
private wcdbGetMessageDates: any = null
|
private wcdbGetMessageDates: any = null
|
||||||
private wcdbOpenMessageCursor: any = null
|
private wcdbOpenMessageCursor: any = null
|
||||||
private wcdbOpenMessageCursorLite: any = null
|
private wcdbOpenMessageCursorLite: any = null
|
||||||
@@ -85,10 +84,6 @@ export class WcdbCore {
|
|||||||
private wcdbScanMediaStream: any = null
|
private wcdbScanMediaStream: any = null
|
||||||
private wcdbGetHeadImageBuffers: any = null
|
private wcdbGetHeadImageBuffers: any = null
|
||||||
private wcdbSearchMessages: any = null
|
private wcdbSearchMessages: any = null
|
||||||
private wcdbAiQuerySessionCandidates: any = null
|
|
||||||
private wcdbAiQueryTimeline: any = null
|
|
||||||
private wcdbAiQueryTopicStats: any = null
|
|
||||||
private wcdbAiQuerySourceRefs: any = null
|
|
||||||
private wcdbGetSnsTimeline: any = null
|
private wcdbGetSnsTimeline: any = null
|
||||||
private wcdbGetSnsAnnualStats: any = null
|
private wcdbGetSnsAnnualStats: any = null
|
||||||
private wcdbGetSnsUsernames: any = null
|
private wcdbGetSnsUsernames: any = null
|
||||||
@@ -132,8 +127,6 @@ export class WcdbCore {
|
|||||||
private logTimer: NodeJS.Timeout | null = null
|
private logTimer: NodeJS.Timeout | null = null
|
||||||
private lastLogTail: string | null = null
|
private lastLogTail: string | null = null
|
||||||
private lastResolvedLogPath: string | null = null
|
private lastResolvedLogPath: string | null = null
|
||||||
private lastCursorForceReopenAt = 0
|
|
||||||
private readonly cursorForceReopenCooldownMs = 15000
|
|
||||||
|
|
||||||
setPaths(resourcesPath: string, userDataPath: string): void {
|
setPaths(resourcesPath: string, userDataPath: string): void {
|
||||||
this.resourcesPath = resourcesPath
|
this.resourcesPath = resourcesPath
|
||||||
@@ -930,13 +923,6 @@ export class WcdbCore {
|
|||||||
this.wcdbGetGroupStats = null
|
this.wcdbGetGroupStats = null
|
||||||
}
|
}
|
||||||
|
|
||||||
// wcdb_status wcdb_get_my_footprint_stats(wcdb_handle handle, const char* options_json, char** out_json)
|
|
||||||
try {
|
|
||||||
this.wcdbGetMyFootprintStats = this.lib.func('int32 wcdb_get_my_footprint_stats(int64 handle, const char* optionsJson, _Out_ void** outJson)')
|
|
||||||
} catch {
|
|
||||||
this.wcdbGetMyFootprintStats = null
|
|
||||||
}
|
|
||||||
|
|
||||||
// wcdb_status wcdb_get_message_dates(wcdb_handle handle, const char* session_id, char** out_json)
|
// wcdb_status wcdb_get_message_dates(wcdb_handle handle, const char* session_id, char** out_json)
|
||||||
try {
|
try {
|
||||||
this.wcdbGetMessageDates = this.lib.func('int32 wcdb_get_message_dates(int64 handle, const char* sessionId, _Out_ void** outJson)')
|
this.wcdbGetMessageDates = this.lib.func('int32 wcdb_get_message_dates(int64 handle, const char* sessionId, _Out_ void** outJson)')
|
||||||
@@ -1064,26 +1050,6 @@ export class WcdbCore {
|
|||||||
} catch {
|
} catch {
|
||||||
this.wcdbSearchMessages = null
|
this.wcdbSearchMessages = null
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
this.wcdbAiQuerySessionCandidates = this.lib.func('int32 wcdb_ai_query_session_candidates(int64 handle, const char* optionsJson, _Out_ void** outJson)')
|
|
||||||
} catch {
|
|
||||||
this.wcdbAiQuerySessionCandidates = null
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
this.wcdbAiQueryTimeline = this.lib.func('int32 wcdb_ai_query_timeline(int64 handle, const char* optionsJson, _Out_ void** outJson)')
|
|
||||||
} catch {
|
|
||||||
this.wcdbAiQueryTimeline = null
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
this.wcdbAiQueryTopicStats = this.lib.func('int32 wcdb_ai_query_topic_stats(int64 handle, const char* optionsJson, _Out_ void** outJson)')
|
|
||||||
} catch {
|
|
||||||
this.wcdbAiQueryTopicStats = null
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
this.wcdbAiQuerySourceRefs = this.lib.func('int32 wcdb_ai_query_source_refs(int64 handle, const char* optionsJson, _Out_ void** outJson)')
|
|
||||||
} catch {
|
|
||||||
this.wcdbAiQuerySourceRefs = null
|
|
||||||
}
|
|
||||||
|
|
||||||
// wcdb_status wcdb_get_sns_timeline(wcdb_handle handle, int32_t limit, int32_t offset, const char* username, const char* keyword, int32_t start_time, int32_t end_time, char** out_json)
|
// wcdb_status wcdb_get_sns_timeline(wcdb_handle handle, int32_t limit, int32_t offset, const char* username, const char* keyword, int32_t start_time, int32_t end_time, char** out_json)
|
||||||
try {
|
try {
|
||||||
@@ -3132,65 +3098,6 @@ export class WcdbCore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getMyFootprintStats(options: {
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
myWxid?: string
|
|
||||||
privateSessionIds?: string[]
|
|
||||||
groupSessionIds?: string[]
|
|
||||||
mentionLimit?: number
|
|
||||||
privateLimit?: number
|
|
||||||
mentionMode?: 'text_at_me' | string
|
|
||||||
}): Promise<{ success: boolean; data?: any; error?: string }> {
|
|
||||||
if (!this.ensureReady()) {
|
|
||||||
return { success: false, error: 'WCDB 未连接' }
|
|
||||||
}
|
|
||||||
if (!this.wcdbGetMyFootprintStats) {
|
|
||||||
return { success: false, error: '接口未就绪' }
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const normalizedPrivateSessions = Array.from(new Set(
|
|
||||||
(options?.privateSessionIds || [])
|
|
||||||
.map((value) => String(value || '').trim())
|
|
||||||
.filter(Boolean)
|
|
||||||
))
|
|
||||||
const normalizedGroupSessions = Array.from(new Set(
|
|
||||||
(options?.groupSessionIds || [])
|
|
||||||
.map((value) => String(value || '').trim())
|
|
||||||
.filter(Boolean)
|
|
||||||
))
|
|
||||||
const mentionLimitRaw = Number(options?.mentionLimit ?? 0)
|
|
||||||
const privateLimitRaw = Number(options?.privateLimit ?? 0)
|
|
||||||
const mentionLimit = Number.isFinite(mentionLimitRaw) && mentionLimitRaw >= 0 ? Math.floor(mentionLimitRaw) : 0
|
|
||||||
const privateLimit = Number.isFinite(privateLimitRaw) && privateLimitRaw >= 0 ? Math.floor(privateLimitRaw) : 0
|
|
||||||
|
|
||||||
const payload = JSON.stringify({
|
|
||||||
begin: this.normalizeTimestamp(options?.beginTimestamp || 0),
|
|
||||||
end: this.normalizeTimestamp(options?.endTimestamp || 0),
|
|
||||||
my_wxid: String(options?.myWxid || '').trim(),
|
|
||||||
private_session_ids: normalizedPrivateSessions,
|
|
||||||
group_session_ids: normalizedGroupSessions,
|
|
||||||
mention_limit: mentionLimit,
|
|
||||||
private_limit: privateLimit,
|
|
||||||
mention_mode: options?.mentionMode || 'text_at_me'
|
|
||||||
})
|
|
||||||
|
|
||||||
const outPtr = [null as any]
|
|
||||||
const result = this.wcdbGetMyFootprintStats(this.handle, payload, outPtr)
|
|
||||||
if (result !== 0 || !outPtr[0]) {
|
|
||||||
return { success: false, error: `获取我的足迹统计失败: ${result}` }
|
|
||||||
}
|
|
||||||
const jsonStr = this.decodeJsonPtr(outPtr[0])
|
|
||||||
if (!jsonStr) {
|
|
||||||
return { success: false, error: '解析我的足迹统计失败' }
|
|
||||||
}
|
|
||||||
return { success: true, data: JSON.parse(jsonStr) || {} }
|
|
||||||
} catch (e) {
|
|
||||||
return { success: false, error: String(e) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 强制重新打开账号连接(绕过路径缓存),用于微信重装后消息数据库刷新失败时的自动恢复。
|
* 强制重新打开账号连接(绕过路径缓存),用于微信重装后消息数据库刷新失败时的自动恢复。
|
||||||
* 返回重新打开是否成功。
|
* 返回重新打开是否成功。
|
||||||
@@ -3212,15 +3119,6 @@ export class WcdbCore {
|
|||||||
return this.open(path, key, wxid)
|
return this.open(path, key, wxid)
|
||||||
}
|
}
|
||||||
|
|
||||||
private shouldRetryCursorAfterNoDb(): boolean {
|
|
||||||
const now = Date.now()
|
|
||||||
if (now - this.lastCursorForceReopenAt < this.cursorForceReopenCooldownMs) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
this.lastCursorForceReopenAt = now
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
async openMessageCursor(sessionId: string, batchSize: number, ascending: boolean, beginTimestamp: number, endTimestamp: number): Promise<{ success: boolean; cursor?: number; error?: string }> {
|
async openMessageCursor(sessionId: string, batchSize: number, ascending: boolean, beginTimestamp: number, endTimestamp: number): Promise<{ success: boolean; cursor?: number; error?: string }> {
|
||||||
if (!this.ensureReady()) {
|
if (!this.ensureReady()) {
|
||||||
return { success: false, error: 'WCDB 未连接' }
|
return { success: false, error: 'WCDB 未连接' }
|
||||||
@@ -3238,7 +3136,7 @@ export class WcdbCore {
|
|||||||
)
|
)
|
||||||
// result=-3 表示 WCDB_STATUS_NO_MESSAGE_DB:消息数据库缓存为空(常见于微信重装后)
|
// result=-3 表示 WCDB_STATUS_NO_MESSAGE_DB:消息数据库缓存为空(常见于微信重装后)
|
||||||
// 自动强制重连并重试一次
|
// 自动强制重连并重试一次
|
||||||
if (result === -3 && outCursor[0] <= 0 && this.shouldRetryCursorAfterNoDb()) {
|
if (result === -3 && outCursor[0] <= 0) {
|
||||||
this.writeLog('openMessageCursor: result=-3 (no message db), attempting forceReopen...', true)
|
this.writeLog('openMessageCursor: result=-3 (no message db), attempting forceReopen...', true)
|
||||||
const reopened = await this.forceReopen()
|
const reopened = await this.forceReopen()
|
||||||
if (reopened && this.handle !== null) {
|
if (reopened && this.handle !== null) {
|
||||||
@@ -3258,13 +3156,11 @@ export class WcdbCore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (result !== 0 || outCursor[0] <= 0) {
|
if (result !== 0 || outCursor[0] <= 0) {
|
||||||
if (result !== -3) {
|
await this.printLogs(true)
|
||||||
await this.printLogs(true)
|
this.writeLog(
|
||||||
this.writeLog(
|
`openMessageCursor failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`,
|
||||||
`openMessageCursor failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`,
|
true
|
||||||
true
|
)
|
||||||
)
|
|
||||||
}
|
|
||||||
const hint = result === -3
|
const hint = result === -3
|
||||||
? `创建游标失败: ${result}(消息数据库未找到)。如果你最近重装过微信,请尝试重新指定数据目录后重试`
|
? `创建游标失败: ${result}(消息数据库未找到)。如果你最近重装过微信,请尝试重新指定数据目录后重试`
|
||||||
: result === -7
|
: result === -7
|
||||||
@@ -3301,7 +3197,7 @@ export class WcdbCore {
|
|||||||
|
|
||||||
// result=-3 表示 WCDB_STATUS_NO_MESSAGE_DB:消息数据库缓存为空
|
// result=-3 表示 WCDB_STATUS_NO_MESSAGE_DB:消息数据库缓存为空
|
||||||
// 自动强制重连并重试一次
|
// 自动强制重连并重试一次
|
||||||
if (result === -3 && outCursor[0] <= 0 && this.shouldRetryCursorAfterNoDb()) {
|
if (result === -3 && outCursor[0] <= 0) {
|
||||||
this.writeLog('openMessageCursorLite: result=-3 (no message db), attempting forceReopen...', true)
|
this.writeLog('openMessageCursorLite: result=-3 (no message db), attempting forceReopen...', true)
|
||||||
const reopened = await this.forceReopen()
|
const reopened = await this.forceReopen()
|
||||||
if (reopened && this.handle !== null) {
|
if (reopened && this.handle !== null) {
|
||||||
@@ -3322,13 +3218,11 @@ export class WcdbCore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (result !== 0 || outCursor[0] <= 0) {
|
if (result !== 0 || outCursor[0] <= 0) {
|
||||||
if (result !== -3) {
|
await this.printLogs(true)
|
||||||
await this.printLogs(true)
|
this.writeLog(
|
||||||
this.writeLog(
|
`openMessageCursorLite failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`,
|
||||||
`openMessageCursorLite failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`,
|
true
|
||||||
true
|
)
|
||||||
)
|
|
||||||
}
|
|
||||||
if (result === -7) {
|
if (result === -7) {
|
||||||
return { success: false, error: 'message schema mismatch:当前账号消息表结构与程序要求不一致' }
|
return { success: false, error: 'message schema mismatch:当前账号消息表结构与程序要求不一致' }
|
||||||
}
|
}
|
||||||
@@ -3394,204 +3288,6 @@ export class WcdbCore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeSqlIdentifier(name: string): string {
|
|
||||||
return `"${String(name || '').replace(/"/g, '""')}"`
|
|
||||||
}
|
|
||||||
|
|
||||||
private stripSqlComments(sql: string): string {
|
|
||||||
return String(sql || '')
|
|
||||||
.replace(/\/\*[\s\S]*?\*\//g, ' ')
|
|
||||||
.replace(/--[^\n\r]*/g, ' ')
|
|
||||||
.trim()
|
|
||||||
}
|
|
||||||
|
|
||||||
private isSqlLabReadOnly(sql: string): boolean {
|
|
||||||
const normalized = this.stripSqlComments(sql).trim()
|
|
||||||
if (!normalized) return false
|
|
||||||
if (normalized.includes('\u0000')) return false
|
|
||||||
const hasMultipleStatements = /;[\s\r\n]*\S/.test(normalized)
|
|
||||||
if (hasMultipleStatements) return false
|
|
||||||
const lower = normalized.toLowerCase()
|
|
||||||
if (/(insert|update|delete|drop|alter|create|attach|detach|replace|truncate|reindex|vacuum|analyze|begin|commit|rollback|savepoint|release)\b/.test(lower)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if (/pragma\s+.*(writable_schema|journal_mode|locking_mode|foreign_keys)\s*=/.test(lower)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return /^(select|with|pragma|explain)\b/.test(lower)
|
|
||||||
}
|
|
||||||
|
|
||||||
private async sqlLabListTablesForSource(
|
|
||||||
kind: 'message' | 'contact' | 'biz',
|
|
||||||
path: string | null,
|
|
||||||
maxTables: number = 60,
|
|
||||||
maxColumns: number = 120
|
|
||||||
): Promise<Array<{ name: string; columns: string[] }>> {
|
|
||||||
const tableRows = await this.execQuery(
|
|
||||||
kind,
|
|
||||||
path,
|
|
||||||
`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name LIMIT ${Math.max(1, maxTables)}`
|
|
||||||
)
|
|
||||||
if (!tableRows.success || !Array.isArray(tableRows.rows)) return []
|
|
||||||
|
|
||||||
const tables: Array<{ name: string; columns: string[] }> = []
|
|
||||||
for (const row of tableRows.rows) {
|
|
||||||
const tableName = String((row as any)?.name || '').trim()
|
|
||||||
if (!tableName) continue
|
|
||||||
const pragma = await this.execQuery(kind, path, `PRAGMA table_info(${this.normalizeSqlIdentifier(tableName)})`)
|
|
||||||
const columns = pragma.success && Array.isArray(pragma.rows)
|
|
||||||
? pragma.rows
|
|
||||||
.map((item: any) => String(item?.name || '').trim())
|
|
||||||
.filter(Boolean)
|
|
||||||
.slice(0, maxColumns)
|
|
||||||
: []
|
|
||||||
tables.push({ name: tableName, columns })
|
|
||||||
}
|
|
||||||
|
|
||||||
return tables
|
|
||||||
}
|
|
||||||
|
|
||||||
async sqlLabGetSchema(payload?: { sessionId?: string }): Promise<{
|
|
||||||
success: boolean
|
|
||||||
schema?: {
|
|
||||||
generatedAt: number
|
|
||||||
sources: Array<{
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path: string | null
|
|
||||||
label: string
|
|
||||||
tables: Array<{ name: string; columns: string[] }>
|
|
||||||
}>
|
|
||||||
}
|
|
||||||
schemaText?: string
|
|
||||||
error?: string
|
|
||||||
}> {
|
|
||||||
if (!this.ensureReady()) {
|
|
||||||
return { success: false, error: 'WCDB 未连接' }
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const sessionId = String(payload?.sessionId || '').trim()
|
|
||||||
const sources: Array<{
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path: string | null
|
|
||||||
label: string
|
|
||||||
tables: Array<{ name: string; columns: string[] }>
|
|
||||||
}> = []
|
|
||||||
|
|
||||||
if (sessionId) {
|
|
||||||
const tableStats = await this.getMessageTableStats(sessionId)
|
|
||||||
const tableEntries = tableStats.success && Array.isArray(tableStats.tables) ? tableStats.tables : []
|
|
||||||
const dbPathSet = new Set<string>()
|
|
||||||
for (const entry of tableEntries) {
|
|
||||||
const dbPath = String((entry as any)?.db_path || '').trim()
|
|
||||||
if (!dbPath) continue
|
|
||||||
dbPathSet.add(dbPath)
|
|
||||||
}
|
|
||||||
for (const dbPath of Array.from(dbPathSet).slice(0, 8)) {
|
|
||||||
sources.push({
|
|
||||||
kind: 'message',
|
|
||||||
path: dbPath,
|
|
||||||
label: dbPath.split(/[\\/]/).pop() || dbPath,
|
|
||||||
tables: await this.sqlLabListTablesForSource('message', dbPath)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const messageDbs = await this.listMessageDbs()
|
|
||||||
const paths = messageDbs.success && Array.isArray(messageDbs.data) ? messageDbs.data : []
|
|
||||||
for (const dbPath of paths.slice(0, 8)) {
|
|
||||||
sources.push({
|
|
||||||
kind: 'message',
|
|
||||||
path: dbPath,
|
|
||||||
label: dbPath.split(/[\\/]/).pop() || dbPath,
|
|
||||||
tables: await this.sqlLabListTablesForSource('message', dbPath)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sources.push({
|
|
||||||
kind: 'contact',
|
|
||||||
path: null,
|
|
||||||
label: 'contact',
|
|
||||||
tables: await this.sqlLabListTablesForSource('contact', null)
|
|
||||||
})
|
|
||||||
sources.push({
|
|
||||||
kind: 'biz',
|
|
||||||
path: null,
|
|
||||||
label: 'biz',
|
|
||||||
tables: await this.sqlLabListTablesForSource('biz', null)
|
|
||||||
})
|
|
||||||
|
|
||||||
const schemaText = sources
|
|
||||||
.map((source) => {
|
|
||||||
const tableLines = source.tables
|
|
||||||
.map((table) => `- ${table.name} (${table.columns.join(', ')})`)
|
|
||||||
.join('\n')
|
|
||||||
return `[${source.kind}] ${source.label}\n${tableLines}`
|
|
||||||
})
|
|
||||||
.join('\n\n')
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
schema: {
|
|
||||||
generatedAt: Date.now(),
|
|
||||||
sources
|
|
||||||
},
|
|
||||||
schemaText
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
return { success: false, error: String(e) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async sqlLabExecuteReadonly(payload: {
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path?: string | null
|
|
||||||
sql: string
|
|
||||||
limit?: number
|
|
||||||
}): Promise<{
|
|
||||||
success: boolean
|
|
||||||
rows?: any[]
|
|
||||||
columns?: string[]
|
|
||||||
total?: number
|
|
||||||
error?: string
|
|
||||||
}> {
|
|
||||||
if (!this.ensureReady()) {
|
|
||||||
return { success: false, error: 'WCDB 未连接' }
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const sql = String(payload?.sql || '').trim()
|
|
||||||
if (!this.isSqlLabReadOnly(sql)) {
|
|
||||||
return { success: false, error: '仅允许只读 SQL(SELECT/WITH/PRAGMA/EXPLAIN)' }
|
|
||||||
}
|
|
||||||
|
|
||||||
const kind = payload?.kind === 'contact' || payload?.kind === 'biz' ? payload.kind : 'message'
|
|
||||||
const path = kind === 'message'
|
|
||||||
? (payload?.path == null ? null : String(payload.path))
|
|
||||||
: null
|
|
||||||
const limit = Math.max(1, Math.min(1000, Number(payload?.limit || 200)))
|
|
||||||
const sqlNoTail = sql.replace(/;+\s*$/, '')
|
|
||||||
const lower = sqlNoTail.toLowerCase()
|
|
||||||
const executable = /^(select|with)\b/.test(lower)
|
|
||||||
? `SELECT * FROM (${sqlNoTail}) LIMIT ${limit}`
|
|
||||||
: sqlNoTail
|
|
||||||
|
|
||||||
const result = await this.execQuery(kind, path, executable)
|
|
||||||
if (!result.success) {
|
|
||||||
return { success: false, error: result.error || '执行 SQL 失败' }
|
|
||||||
}
|
|
||||||
const rows = Array.isArray(result.rows) ? result.rows : []
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
rows,
|
|
||||||
columns: rows[0] && typeof rows[0] === 'object' ? Object.keys(rows[0] as Record<string, unknown>) : [],
|
|
||||||
total: rows.length
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
return { success: false, error: String(e) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async execQuery(kind: string, path: string | null, sql: string, params: any[] = []): Promise<{ success: boolean; rows?: any[]; error?: string }> {
|
async execQuery(kind: string, path: string | null, sql: string, params: any[] = []): Promise<{ success: boolean; rows?: any[]; error?: string }> {
|
||||||
if (!this.ensureReady()) {
|
if (!this.ensureReady()) {
|
||||||
return { success: false, error: 'WCDB 未连接' }
|
return { success: false, error: 'WCDB 未连接' }
|
||||||
@@ -4201,110 +3897,6 @@ export class WcdbCore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async aiQuerySessionCandidates(options: {
|
|
||||||
keyword: string
|
|
||||||
limit?: number
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
}): Promise<{ success: boolean; rows?: any[]; error?: string }> {
|
|
||||||
if (!this.ensureReady()) return { success: false, error: 'WCDB 未连接' }
|
|
||||||
if (!this.wcdbAiQuerySessionCandidates) return { success: false, error: '当前数据服务版本不支持 AI 候选会话查询' }
|
|
||||||
try {
|
|
||||||
const outPtr = [null as any]
|
|
||||||
const result = this.wcdbAiQuerySessionCandidates(this.handle, JSON.stringify({
|
|
||||||
keyword: options.keyword || '',
|
|
||||||
limit: options.limit || 12,
|
|
||||||
begin_timestamp: options.beginTimestamp || 0,
|
|
||||||
end_timestamp: options.endTimestamp || 0
|
|
||||||
}), outPtr)
|
|
||||||
if (result !== 0 || !outPtr[0]) return { success: false, error: `AI 候选会话查询失败: ${result}` }
|
|
||||||
const jsonStr = this.decodeJsonPtr(outPtr[0])
|
|
||||||
if (!jsonStr) return { success: false, error: '解析 AI 候选会话结果失败' }
|
|
||||||
const rows = JSON.parse(jsonStr)
|
|
||||||
return { success: true, rows: Array.isArray(rows) ? rows : [] }
|
|
||||||
} catch (e) {
|
|
||||||
return { success: false, error: String(e) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async aiQueryTimeline(options: {
|
|
||||||
sessionId?: string
|
|
||||||
keyword: string
|
|
||||||
limit?: number
|
|
||||||
offset?: number
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
}): Promise<{ success: boolean; rows?: any[]; error?: string }> {
|
|
||||||
if (!this.ensureReady()) return { success: false, error: 'WCDB 未连接' }
|
|
||||||
if (!this.wcdbAiQueryTimeline) return { success: false, error: '当前数据服务版本不支持 AI 时间轴查询' }
|
|
||||||
try {
|
|
||||||
const outPtr = [null as any]
|
|
||||||
const result = this.wcdbAiQueryTimeline(this.handle, JSON.stringify({
|
|
||||||
session_id: options.sessionId || '',
|
|
||||||
keyword: options.keyword || '',
|
|
||||||
limit: options.limit || 120,
|
|
||||||
offset: options.offset || 0,
|
|
||||||
begin_timestamp: options.beginTimestamp || 0,
|
|
||||||
end_timestamp: options.endTimestamp || 0
|
|
||||||
}), outPtr)
|
|
||||||
if (result !== 0 || !outPtr[0]) return { success: false, error: `AI 时间轴查询失败: ${result}` }
|
|
||||||
const jsonStr = this.decodeJsonPtr(outPtr[0])
|
|
||||||
if (!jsonStr) return { success: false, error: '解析 AI 时间轴结果失败' }
|
|
||||||
const rows = this.parseMessageJson(jsonStr)
|
|
||||||
return { success: true, rows }
|
|
||||||
} catch (e) {
|
|
||||||
return { success: false, error: String(e) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async aiQueryTopicStats(options: {
|
|
||||||
sessionIds: string[]
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
}): Promise<{ success: boolean; data?: any; error?: string }> {
|
|
||||||
if (!this.ensureReady()) return { success: false, error: 'WCDB 未连接' }
|
|
||||||
if (!this.wcdbAiQueryTopicStats) return { success: false, error: '当前数据服务版本不支持 AI 主题统计' }
|
|
||||||
try {
|
|
||||||
const outPtr = [null as any]
|
|
||||||
const result = this.wcdbAiQueryTopicStats(this.handle, JSON.stringify({
|
|
||||||
session_ids_json: JSON.stringify(options.sessionIds || []),
|
|
||||||
begin_timestamp: options.beginTimestamp || 0,
|
|
||||||
end_timestamp: options.endTimestamp || 0
|
|
||||||
}), outPtr)
|
|
||||||
if (result !== 0 || !outPtr[0]) return { success: false, error: `AI 主题统计失败: ${result}` }
|
|
||||||
const jsonStr = this.decodeJsonPtr(outPtr[0])
|
|
||||||
if (!jsonStr) return { success: false, error: '解析 AI 主题统计失败' }
|
|
||||||
const data = JSON.parse(jsonStr)
|
|
||||||
return { success: true, data }
|
|
||||||
} catch (e) {
|
|
||||||
return { success: false, error: String(e) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async aiQuerySourceRefs(options: {
|
|
||||||
sessionIds: string[]
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
}): Promise<{ success: boolean; data?: any; error?: string }> {
|
|
||||||
if (!this.ensureReady()) return { success: false, error: 'WCDB 未连接' }
|
|
||||||
if (!this.wcdbAiQuerySourceRefs) return { success: false, error: '当前数据服务版本不支持 AI 来源引用查询' }
|
|
||||||
try {
|
|
||||||
const outPtr = [null as any]
|
|
||||||
const result = this.wcdbAiQuerySourceRefs(this.handle, JSON.stringify({
|
|
||||||
session_ids_json: JSON.stringify(options.sessionIds || []),
|
|
||||||
begin_timestamp: options.beginTimestamp || 0,
|
|
||||||
end_timestamp: options.endTimestamp || 0
|
|
||||||
}), outPtr)
|
|
||||||
if (result !== 0 || !outPtr[0]) return { success: false, error: `AI 来源引用查询失败: ${result}` }
|
|
||||||
const jsonStr = this.decodeJsonPtr(outPtr[0])
|
|
||||||
if (!jsonStr) return { success: false, error: '解析 AI 来源引用查询失败' }
|
|
||||||
const data = JSON.parse(jsonStr)
|
|
||||||
return { success: true, data }
|
|
||||||
} catch (e) {
|
|
||||||
return { success: false, error: String(e) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getSnsTimeline(limit: number, offset: number, usernames?: string[], keyword?: string, startTime?: number, endTime?: number): Promise<{ success: boolean; timeline?: any[]; error?: string }> {
|
async getSnsTimeline(limit: number, offset: number, usernames?: string[], keyword?: string, startTime?: number, endTime?: number): Promise<{ success: boolean; timeline?: any[]; error?: string }> {
|
||||||
if (!this.ensureReady()) return { success: false, error: 'WCDB 未连接' }
|
if (!this.ensureReady()) return { success: false, error: 'WCDB 未连接' }
|
||||||
if (!this.wcdbGetSnsTimeline) return { success: false, error: '当前数据服务版本不支持获取朋友圈' }
|
if (!this.wcdbGetSnsTimeline) return { success: false, error: '当前数据服务版本不支持获取朋友圈' }
|
||||||
|
|||||||
@@ -448,19 +448,6 @@ export class WcdbService {
|
|||||||
return this.callWorker('getGroupStats', { chatroomId, beginTimestamp, endTimestamp })
|
return this.callWorker('getGroupStats', { chatroomId, beginTimestamp, endTimestamp })
|
||||||
}
|
}
|
||||||
|
|
||||||
async getMyFootprintStats(options: {
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
myWxid?: string
|
|
||||||
privateSessionIds?: string[]
|
|
||||||
groupSessionIds?: string[]
|
|
||||||
mentionLimit?: number
|
|
||||||
privateLimit?: number
|
|
||||||
mentionMode?: 'text_at_me' | string
|
|
||||||
}): Promise<{ success: boolean; data?: any; error?: string }> {
|
|
||||||
return this.callWorker('getMyFootprintStats', { options })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 打开消息游标
|
* 打开消息游标
|
||||||
*/
|
*/
|
||||||
@@ -489,44 +476,6 @@ export class WcdbService {
|
|||||||
return this.callWorker('closeMessageCursor', { cursor })
|
return this.callWorker('closeMessageCursor', { cursor })
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* SQL Lab: 获取多数据源 Schema 摘要
|
|
||||||
*/
|
|
||||||
async sqlLabGetSchema(payload?: { sessionId?: string }): Promise<{
|
|
||||||
success: boolean
|
|
||||||
schema?: {
|
|
||||||
generatedAt: number
|
|
||||||
sources: Array<{
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path: string | null
|
|
||||||
label: string
|
|
||||||
tables: Array<{ name: string; columns: string[] }>
|
|
||||||
}>
|
|
||||||
}
|
|
||||||
schemaText?: string
|
|
||||||
error?: string
|
|
||||||
}> {
|
|
||||||
return this.callWorker('sqlLabGetSchema', payload || {})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SQL Lab: 执行只读 SQL
|
|
||||||
*/
|
|
||||||
async sqlLabExecuteReadonly(payload: {
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path?: string | null
|
|
||||||
sql: string
|
|
||||||
limit?: number
|
|
||||||
}): Promise<{
|
|
||||||
success: boolean
|
|
||||||
rows?: any[]
|
|
||||||
columns?: string[]
|
|
||||||
total?: number
|
|
||||||
error?: string
|
|
||||||
}> {
|
|
||||||
return this.callWorker('sqlLabExecuteReadonly', payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行 SQL 查询(仅主进程内部使用:fallback/diagnostic/低频兼容)
|
* 执行 SQL 查询(仅主进程内部使用:fallback/diagnostic/低频兼容)
|
||||||
*/
|
*/
|
||||||
@@ -580,42 +529,6 @@ export class WcdbService {
|
|||||||
return this.callWorker('searchMessages', { keyword, sessionId, limit, offset, beginTimestamp, endTimestamp })
|
return this.callWorker('searchMessages', { keyword, sessionId, limit, offset, beginTimestamp, endTimestamp })
|
||||||
}
|
}
|
||||||
|
|
||||||
async aiQuerySessionCandidates(options: {
|
|
||||||
keyword: string
|
|
||||||
limit?: number
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
}): Promise<{ success: boolean; rows?: any[]; error?: string }> {
|
|
||||||
return this.callWorker('aiQuerySessionCandidates', { options })
|
|
||||||
}
|
|
||||||
|
|
||||||
async aiQueryTimeline(options: {
|
|
||||||
sessionId?: string
|
|
||||||
keyword: string
|
|
||||||
limit?: number
|
|
||||||
offset?: number
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
}): Promise<{ success: boolean; rows?: any[]; error?: string }> {
|
|
||||||
return this.callWorker('aiQueryTimeline', { options })
|
|
||||||
}
|
|
||||||
|
|
||||||
async aiQueryTopicStats(options: {
|
|
||||||
sessionIds: string[]
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
}): Promise<{ success: boolean; data?: any; error?: string }> {
|
|
||||||
return this.callWorker('aiQueryTopicStats', { options })
|
|
||||||
}
|
|
||||||
|
|
||||||
async aiQuerySourceRefs(options: {
|
|
||||||
sessionIds: string[]
|
|
||||||
beginTimestamp?: number
|
|
||||||
endTimestamp?: number
|
|
||||||
}): Promise<{ success: boolean; data?: any; error?: string }> {
|
|
||||||
return this.callWorker('aiQuerySourceRefs', { options })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取语音数据
|
* 获取语音数据
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -158,9 +158,6 @@ if (parentPort) {
|
|||||||
case 'getGroupStats':
|
case 'getGroupStats':
|
||||||
result = await core.getGroupStats(payload.chatroomId, payload.beginTimestamp, payload.endTimestamp)
|
result = await core.getGroupStats(payload.chatroomId, payload.beginTimestamp, payload.endTimestamp)
|
||||||
break
|
break
|
||||||
case 'getMyFootprintStats':
|
|
||||||
result = await core.getMyFootprintStats(payload.options || {})
|
|
||||||
break
|
|
||||||
case 'openMessageCursor':
|
case 'openMessageCursor':
|
||||||
result = await core.openMessageCursor(payload.sessionId, payload.batchSize, payload.ascending, payload.beginTimestamp, payload.endTimestamp)
|
result = await core.openMessageCursor(payload.sessionId, payload.batchSize, payload.ascending, payload.beginTimestamp, payload.endTimestamp)
|
||||||
break
|
break
|
||||||
@@ -173,12 +170,6 @@ if (parentPort) {
|
|||||||
case 'closeMessageCursor':
|
case 'closeMessageCursor':
|
||||||
result = await core.closeMessageCursor(payload.cursor)
|
result = await core.closeMessageCursor(payload.cursor)
|
||||||
break
|
break
|
||||||
case 'sqlLabGetSchema':
|
|
||||||
result = await core.sqlLabGetSchema(payload)
|
|
||||||
break
|
|
||||||
case 'sqlLabExecuteReadonly':
|
|
||||||
result = await core.sqlLabExecuteReadonly(payload)
|
|
||||||
break
|
|
||||||
case 'execQuery':
|
case 'execQuery':
|
||||||
result = await core.execQuery(payload.kind, payload.path, payload.sql, payload.params)
|
result = await core.execQuery(payload.kind, payload.path, payload.sql, payload.params)
|
||||||
break
|
break
|
||||||
@@ -203,18 +194,6 @@ if (parentPort) {
|
|||||||
case 'searchMessages':
|
case 'searchMessages':
|
||||||
result = await core.searchMessages(payload.keyword, payload.sessionId, payload.limit, payload.offset, payload.beginTimestamp, payload.endTimestamp)
|
result = await core.searchMessages(payload.keyword, payload.sessionId, payload.limit, payload.offset, payload.beginTimestamp, payload.endTimestamp)
|
||||||
break
|
break
|
||||||
case 'aiQuerySessionCandidates':
|
|
||||||
result = await core.aiQuerySessionCandidates(payload.options || {})
|
|
||||||
break
|
|
||||||
case 'aiQueryTimeline':
|
|
||||||
result = await core.aiQueryTimeline(payload.options || {})
|
|
||||||
break
|
|
||||||
case 'aiQueryTopicStats':
|
|
||||||
result = await core.aiQueryTopicStats(payload.options || {})
|
|
||||||
break
|
|
||||||
case 'aiQuerySourceRefs':
|
|
||||||
result = await core.aiQuerySourceRefs(payload.options || {})
|
|
||||||
break
|
|
||||||
case 'getVoiceData':
|
case 'getVoiceData':
|
||||||
result = await core.getVoiceData(payload.sessionId, payload.createTime, payload.candidates, payload.localId, payload.svrId)
|
result = await core.getVoiceData(payload.sessionId, payload.createTime, payload.candidates, payload.localId, payload.svrId)
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
|
|||||||
@@ -115,14 +115,12 @@ export async function showNotification(data: any) {
|
|||||||
// 检查会话过滤
|
// 检查会话过滤
|
||||||
const filterMode = config.get("notificationFilterMode") || "all";
|
const filterMode = config.get("notificationFilterMode") || "all";
|
||||||
const filterList = config.get("notificationFilterList") || [];
|
const filterList = config.get("notificationFilterList") || [];
|
||||||
const sessionId = typeof data.sessionId === "string" ? data.sessionId : "";
|
const sessionId = data.sessionId;
|
||||||
// 系统通知(如 "WeFlow 准备就绪")不是聊天消息,不应受会话白/黑名单影响
|
|
||||||
const isSystemNotification = sessionId.startsWith("weflow-");
|
|
||||||
|
|
||||||
if (!isSystemNotification && filterMode !== "all") {
|
if (sessionId && filterMode !== "all" && filterList.length > 0) {
|
||||||
const isInList = sessionId !== "" && filterList.includes(sessionId);
|
const isInList = filterList.includes(sessionId);
|
||||||
if (filterMode === "whitelist" && !isInList) {
|
if (filterMode === "whitelist" && !isInList) {
|
||||||
// 白名单模式:不在列表中则不显示(空列表视为全部拦截)
|
// 白名单模式:不在列表中则不显示
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (filterMode === "blacklist" && isInList) {
|
if (filterMode === "blacklist" && isInList) {
|
||||||
|
|||||||
8
package-lock.json
generated
8
package-lock.json
generated
@@ -38,7 +38,7 @@
|
|||||||
"@types/react": "^19.1.0",
|
"@types/react": "^19.1.0",
|
||||||
"@types/react-dom": "^19.1.0",
|
"@types/react-dom": "^19.1.0",
|
||||||
"@vitejs/plugin-react": "^4.3.4",
|
"@vitejs/plugin-react": "^4.3.4",
|
||||||
"electron": "^41.1.1",
|
"electron": "^41.2.0",
|
||||||
"electron-builder": "^26.8.1",
|
"electron-builder": "^26.8.1",
|
||||||
"sass": "^1.99.0",
|
"sass": "^1.99.0",
|
||||||
"sharp": "^0.34.5",
|
"sharp": "^0.34.5",
|
||||||
@@ -4884,9 +4884,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/electron": {
|
"node_modules/electron": {
|
||||||
"version": "41.1.1",
|
"version": "41.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/electron/-/electron-41.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/electron/-/electron-41.2.0.tgz",
|
||||||
"integrity": "sha512-8bgvDhBjli+3Z2YCKgzzoBPh6391pr7Xv2h/tTJG4ETgvPvUxZomObbZLs31mUzYb6VrlcDDd9cyWyNKtPm3tA==",
|
"integrity": "sha512-0OKLiymqfV0WK68RBXqAm3Myad2TpI5wwxLCBEUcH5Nugo3YfSk7p1Js/AL9266qTz5xZioUnxt9hG8FFwax0g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|||||||
@@ -52,7 +52,7 @@
|
|||||||
"@types/react": "^19.1.0",
|
"@types/react": "^19.1.0",
|
||||||
"@types/react-dom": "^19.1.0",
|
"@types/react-dom": "^19.1.0",
|
||||||
"@vitejs/plugin-react": "^4.3.4",
|
"@vitejs/plugin-react": "^4.3.4",
|
||||||
"electron": "^41.1.1",
|
"electron": "^41.2.0",
|
||||||
"electron-builder": "^26.8.1",
|
"electron-builder": "^26.8.1",
|
||||||
"sass": "^1.99.0",
|
"sass": "^1.99.0",
|
||||||
"sharp": "^0.34.5",
|
"sharp": "^0.34.5",
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -6,7 +6,6 @@ import RouteGuard from './components/RouteGuard'
|
|||||||
import WelcomePage from './pages/WelcomePage'
|
import WelcomePage from './pages/WelcomePage'
|
||||||
import HomePage from './pages/HomePage'
|
import HomePage from './pages/HomePage'
|
||||||
import ChatPage from './pages/ChatPage'
|
import ChatPage from './pages/ChatPage'
|
||||||
import AiAnalysisPage from './pages/AiAnalysisPage'
|
|
||||||
import AnalyticsPage from './pages/AnalyticsPage'
|
import AnalyticsPage from './pages/AnalyticsPage'
|
||||||
import AnalyticsWelcomePage from './pages/AnalyticsWelcomePage'
|
import AnalyticsWelcomePage from './pages/AnalyticsWelcomePage'
|
||||||
import ChatAnalyticsHubPage from './pages/ChatAnalyticsHubPage'
|
import ChatAnalyticsHubPage from './pages/ChatAnalyticsHubPage'
|
||||||
@@ -18,7 +17,6 @@ import AgreementPage from './pages/AgreementPage'
|
|||||||
import GroupAnalyticsPage from './pages/GroupAnalyticsPage'
|
import GroupAnalyticsPage from './pages/GroupAnalyticsPage'
|
||||||
import SettingsPage from './pages/SettingsPage'
|
import SettingsPage from './pages/SettingsPage'
|
||||||
import ExportPage from './pages/ExportPage'
|
import ExportPage from './pages/ExportPage'
|
||||||
import MyFootprintPage from './pages/MyFootprintPage'
|
|
||||||
import VideoWindow from './pages/VideoWindow'
|
import VideoWindow from './pages/VideoWindow'
|
||||||
import ImageWindow from './pages/ImageWindow'
|
import ImageWindow from './pages/ImageWindow'
|
||||||
import SnsPage from './pages/SnsPage'
|
import SnsPage from './pages/SnsPage'
|
||||||
@@ -680,7 +678,6 @@ function App() {
|
|||||||
<Route path="/" element={<HomePage />} />
|
<Route path="/" element={<HomePage />} />
|
||||||
<Route path="/home" element={<HomePage />} />
|
<Route path="/home" element={<HomePage />} />
|
||||||
<Route path="/chat" element={<ChatPage />} />
|
<Route path="/chat" element={<ChatPage />} />
|
||||||
<Route path="/ai-analysis" element={<AiAnalysisPage />} />
|
|
||||||
|
|
||||||
<Route path="/analytics" element={<ChatAnalyticsHubPage />} />
|
<Route path="/analytics" element={<ChatAnalyticsHubPage />} />
|
||||||
<Route path="/analytics/private" element={<AnalyticsWelcomePage />} />
|
<Route path="/analytics/private" element={<AnalyticsWelcomePage />} />
|
||||||
@@ -692,7 +689,6 @@ function App() {
|
|||||||
<Route path="/annual-report/view" element={<AnnualReportWindow />} />
|
<Route path="/annual-report/view" element={<AnnualReportWindow />} />
|
||||||
<Route path="/dual-report" element={<DualReportPage />} />
|
<Route path="/dual-report" element={<DualReportPage />} />
|
||||||
<Route path="/dual-report/view" element={<DualReportWindow />} />
|
<Route path="/dual-report/view" element={<DualReportWindow />} />
|
||||||
<Route path="/footprint" element={<MyFootprintPage />} />
|
|
||||||
|
|
||||||
<Route path="/export" element={<div className="export-route-anchor" aria-hidden="true" />} />
|
<Route path="/export" element={<div className="export-route-anchor" aria-hidden="true" />} />
|
||||||
<Route path="/sns" element={<SnsPage />} />
|
<Route path="/sns" element={<SnsPage />} />
|
||||||
|
|||||||
@@ -54,11 +54,10 @@
|
|||||||
position: absolute;
|
position: absolute;
|
||||||
top: calc(100% + 8px);
|
top: calc(100% + 8px);
|
||||||
right: 0;
|
right: 0;
|
||||||
background: var(--bg-secondary-solid, var(--bg-primary, var(--card-bg)));
|
background: var(--card-bg);
|
||||||
border-radius: 16px;
|
border-radius: 16px;
|
||||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);
|
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
|
||||||
backdrop-filter: none;
|
backdrop-filter: blur(20px);
|
||||||
-webkit-backdrop-filter: none;
|
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
z-index: 1000;
|
z-index: 1000;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -289,4 +288,4 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,20 +29,6 @@ function DateRangePicker({ startDate, endDate, onStartDateChange, onEndDateChang
|
|||||||
const [showYearMonthPicker, setShowYearMonthPicker] = useState(false)
|
const [showYearMonthPicker, setShowYearMonthPicker] = useState(false)
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
const containerRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
const [internalStart, setInternalStart] = useState(startDate)
|
|
||||||
const [internalEnd, setInternalEnd] = useState(endDate)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setInternalStart(startDate)
|
|
||||||
setInternalEnd(endDate)
|
|
||||||
}, [startDate, endDate])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (isOpen) {
|
|
||||||
setSelectingStart(true)
|
|
||||||
}
|
|
||||||
}, [isOpen])
|
|
||||||
|
|
||||||
// 点击外部关闭
|
// 点击外部关闭
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleClickOutside = (e: MouseEvent) => {
|
const handleClickOutside = (e: MouseEvent) => {
|
||||||
@@ -77,10 +63,8 @@ function DateRangePicker({ startDate, endDate, onStartDateChange, onEndDateChang
|
|||||||
const end = new Date()
|
const end = new Date()
|
||||||
const start = new Date()
|
const start = new Date()
|
||||||
start.setDate(start.getDate() - days)
|
start.setDate(start.getDate() - days)
|
||||||
const startStr = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`
|
onStartDateChange(start.toISOString().split('T')[0])
|
||||||
const endStr = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')}`
|
onEndDateChange(end.toISOString().split('T')[0])
|
||||||
onStartDateChange(startStr)
|
|
||||||
onEndDateChange(endStr)
|
|
||||||
}
|
}
|
||||||
setIsOpen(false)
|
setIsOpen(false)
|
||||||
setTimeout(() => onRangeComplete?.(), 0)
|
setTimeout(() => onRangeComplete?.(), 0)
|
||||||
@@ -105,46 +89,38 @@ function DateRangePicker({ startDate, endDate, onStartDateChange, onEndDateChang
|
|||||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||||
|
|
||||||
if (selectingStart) {
|
if (selectingStart) {
|
||||||
setInternalStart(dateStr)
|
onStartDateChange(dateStr)
|
||||||
if (internalEnd && dateStr > internalEnd) {
|
if (endDate && dateStr > endDate) {
|
||||||
setInternalEnd('')
|
onEndDateChange('')
|
||||||
}
|
}
|
||||||
setSelectingStart(false)
|
setSelectingStart(false)
|
||||||
} else {
|
} else {
|
||||||
let finalStart = internalStart
|
if (dateStr < startDate) {
|
||||||
let finalEnd = dateStr
|
onStartDateChange(dateStr)
|
||||||
|
onEndDateChange(startDate)
|
||||||
if (dateStr < internalStart) {
|
} else {
|
||||||
finalStart = dateStr
|
onEndDateChange(dateStr)
|
||||||
finalEnd = internalStart
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setInternalStart(finalStart)
|
|
||||||
setInternalEnd(finalEnd)
|
|
||||||
|
|
||||||
setSelectingStart(true)
|
setSelectingStart(true)
|
||||||
setIsOpen(false)
|
setIsOpen(false)
|
||||||
|
|
||||||
onStartDateChange(finalStart)
|
|
||||||
onEndDateChange(finalEnd)
|
|
||||||
setTimeout(() => onRangeComplete?.(), 0)
|
setTimeout(() => onRangeComplete?.(), 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const isInRange = (day: number) => {
|
const isInRange = (day: number) => {
|
||||||
if (!internalStart || !internalEnd) return false
|
if (!startDate || !endDate) return false
|
||||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||||
return dateStr >= internalStart && dateStr <= internalEnd
|
return dateStr >= startDate && dateStr <= endDate
|
||||||
}
|
}
|
||||||
|
|
||||||
const isStartDate = (day: number) => {
|
const isStartDate = (day: number) => {
|
||||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||||
return dateStr === internalStart
|
return dateStr === startDate
|
||||||
}
|
}
|
||||||
|
|
||||||
const isEndDate = (day: number) => {
|
const isEndDate = (day: number) => {
|
||||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||||
return dateStr === internalEnd
|
return dateStr === endDate
|
||||||
}
|
}
|
||||||
|
|
||||||
const isToday = (day: number) => {
|
const isToday = (day: number) => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState, useEffect, useRef } from 'react'
|
import { useState, useEffect, useRef } from 'react'
|
||||||
import { NavLink, useLocation, useNavigate } from 'react-router-dom'
|
import { NavLink, useLocation, useNavigate } from 'react-router-dom'
|
||||||
import { Home, MessageSquare, BarChart3, FileText, Settings, Download, Aperture, UserCircle, Lock, LockOpen, ChevronUp, RefreshCw, FolderClosed, Footprints, Sparkles } from 'lucide-react'
|
import { Home, MessageSquare, BarChart3, FileText, Settings, Download, Aperture, UserCircle, Lock, LockOpen, ChevronUp, RefreshCw, FolderClosed } from 'lucide-react'
|
||||||
import { useAppStore } from '../stores/appStore'
|
import { useAppStore } from '../stores/appStore'
|
||||||
import { useChatStore } from '../stores/chatStore'
|
import { useChatStore } from '../stores/chatStore'
|
||||||
import { useAnalyticsStore } from '../stores/analyticsStore'
|
import { useAnalyticsStore } from '../stores/analyticsStore'
|
||||||
@@ -409,16 +409,6 @@ function Sidebar({ collapsed }: SidebarProps) {
|
|||||||
<span className="nav-label">聊天</span>
|
<span className="nav-label">聊天</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
|
||||||
{/* AI分析 */}
|
|
||||||
<NavLink
|
|
||||||
to="/ai-analysis"
|
|
||||||
className={`nav-item ${isActive('/ai-analysis') ? 'active' : ''}`}
|
|
||||||
title={collapsed ? 'AI分析' : undefined}
|
|
||||||
>
|
|
||||||
<span className="nav-icon"><Sparkles size={20} /></span>
|
|
||||||
<span className="nav-label">AI分析</span>
|
|
||||||
</NavLink>
|
|
||||||
|
|
||||||
{/* 朋友圈 */}
|
{/* 朋友圈 */}
|
||||||
<NavLink
|
<NavLink
|
||||||
to="/sns"
|
to="/sns"
|
||||||
@@ -469,16 +459,6 @@ function Sidebar({ collapsed }: SidebarProps) {
|
|||||||
<span className="nav-label">年度报告</span>
|
<span className="nav-label">年度报告</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
|
||||||
{/* 我的足迹 */}
|
|
||||||
<NavLink
|
|
||||||
to="/footprint"
|
|
||||||
className={`nav-item ${isActive('/footprint') ? 'active' : ''}`}
|
|
||||||
title={collapsed ? '我的足迹' : undefined}
|
|
||||||
>
|
|
||||||
<span className="nav-icon"><Footprints size={20} /></span>
|
|
||||||
<span className="nav-label">我的足迹</span>
|
|
||||||
</NavLink>
|
|
||||||
|
|
||||||
{/* 导出 */}
|
{/* 导出 */}
|
||||||
<NavLink
|
<NavLink
|
||||||
to="/export"
|
to="/export"
|
||||||
|
|||||||
@@ -1,680 +0,0 @@
|
|||||||
.ai-analysis-v2 {
|
|
||||||
--ai-surface: color-mix(in srgb, var(--card-bg) 92%, #ffffff 8%);
|
|
||||||
--ai-surface-soft: color-mix(in srgb, var(--card-bg) 86%, #cbd5e1 14%);
|
|
||||||
--ai-border: color-mix(in srgb, var(--border-color) 85%, #94a3b8 15%);
|
|
||||||
--ai-accent: #0f766e;
|
|
||||||
--ai-accent-soft: color-mix(in srgb, #0f766e 16%, transparent);
|
|
||||||
|
|
||||||
height: 100%;
|
|
||||||
min-height: 0;
|
|
||||||
display: grid;
|
|
||||||
grid-template-rows: auto minmax(0, 1fr);
|
|
||||||
gap: 12px;
|
|
||||||
padding: 16px;
|
|
||||||
background:
|
|
||||||
radial-gradient(1200px 380px at 8% -15%, color-mix(in srgb, #22c55e 20%, transparent), transparent 70%),
|
|
||||||
radial-gradient(1000px 320px at 96% -10%, color-mix(in srgb, #06b6d4 15%, transparent), transparent 68%),
|
|
||||||
var(--bg-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.ai-header {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 16px;
|
|
||||||
background: var(--ai-surface);
|
|
||||||
padding: 12px 14px;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 12px;
|
|
||||||
|
|
||||||
.left {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
min-width: 0;
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
span {
|
|
||||||
color: var(--text-secondary);
|
|
||||||
font-size: 12px;
|
|
||||||
white-space: nowrap;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tabs {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
|
|
||||||
button {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
border-radius: 10px;
|
|
||||||
padding: 6px 10px;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.active {
|
|
||||||
background: var(--ai-accent-soft);
|
|
||||||
color: var(--text-primary);
|
|
||||||
border-color: color-mix(in srgb, var(--ai-accent) 58%, transparent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-layout,
|
|
||||||
.sql-layout,
|
|
||||||
.tool-layout {
|
|
||||||
min-height: 0;
|
|
||||||
display: grid;
|
|
||||||
gap: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-layout {
|
|
||||||
grid-template-columns: 300px minmax(0, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.conversation-panel,
|
|
||||||
.chat-main,
|
|
||||||
.schema-panel,
|
|
||||||
.sql-main,
|
|
||||||
.tool-catalog,
|
|
||||||
.tool-main {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 16px;
|
|
||||||
background: var(--ai-surface);
|
|
||||||
min-height: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.panel-head {
|
|
||||||
padding: 10px 12px;
|
|
||||||
border-bottom: 1px solid var(--ai-border);
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
|
|
||||||
h3 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
width: 28px;
|
|
||||||
height: 28px;
|
|
||||||
border-radius: 9px;
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.conversation-list {
|
|
||||||
padding: 10px;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 8px;
|
|
||||||
overflow: auto;
|
|
||||||
max-height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.conversation-item {
|
|
||||||
border: 1px solid transparent;
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 10px;
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 2%, transparent);
|
|
||||||
text-align: left;
|
|
||||||
cursor: pointer;
|
|
||||||
color: var(--text-primary);
|
|
||||||
|
|
||||||
.main {
|
|
||||||
display: grid;
|
|
||||||
gap: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
strong {
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
small {
|
|
||||||
font-size: 11px;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.ops {
|
|
||||||
margin-top: 8px;
|
|
||||||
display: flex;
|
|
||||||
gap: 10px;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
font-size: 12px;
|
|
||||||
|
|
||||||
span {
|
|
||||||
cursor: pointer;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 4px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.conversation-item.active {
|
|
||||||
border-color: color-mix(in srgb, var(--ai-accent) 52%, transparent);
|
|
||||||
background: color-mix(in srgb, var(--ai-accent) 10%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-main {
|
|
||||||
display: grid;
|
|
||||||
grid-template-rows: auto minmax(0, 1fr) auto auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-toolbar {
|
|
||||||
border-bottom: 1px solid var(--ai-border);
|
|
||||||
padding: 10px 12px;
|
|
||||||
display: grid;
|
|
||||||
gap: 8px;
|
|
||||||
|
|
||||||
.row {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
label {
|
|
||||||
font-size: 12px;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
}
|
|
||||||
|
|
||||||
select,
|
|
||||||
input {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
background: var(--ai-surface-soft);
|
|
||||||
color: var(--text-primary);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 6px 8px;
|
|
||||||
font-size: 12px;
|
|
||||||
min-width: 120px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.preset-row {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 6px;
|
|
||||||
|
|
||||||
button {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
background: color-mix(in srgb, var(--ai-accent) 8%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
border-radius: 999px;
|
|
||||||
padding: 4px 10px;
|
|
||||||
font-size: 12px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.message-panel {
|
|
||||||
min-height: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.message-list {
|
|
||||||
height: 100%;
|
|
||||||
overflow: auto;
|
|
||||||
padding: 12px;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.msg {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 12px;
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 2%, transparent);
|
|
||||||
padding: 10px;
|
|
||||||
|
|
||||||
.head {
|
|
||||||
font-size: 12px;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.body {
|
|
||||||
margin-top: 6px;
|
|
||||||
font-size: 13px;
|
|
||||||
line-height: 1.65;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
word-break: break-word;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.msg.user {
|
|
||||||
background: color-mix(in srgb, #0f766e 14%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.runtime-cards {
|
|
||||||
display: grid;
|
|
||||||
gap: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chunk {
|
|
||||||
border: 1px dashed var(--ai-border);
|
|
||||||
border-radius: 10px;
|
|
||||||
padding: 8px;
|
|
||||||
font-size: 12px;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
|
|
||||||
strong {
|
|
||||||
margin-right: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
pre {
|
|
||||||
margin: 6px 0 0;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.err {
|
|
||||||
color: #dc2626;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.footer-actions {
|
|
||||||
border-top: 1px solid var(--ai-border);
|
|
||||||
padding: 8px 12px;
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
|
|
||||||
.ghost {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
border-radius: 9px;
|
|
||||||
padding: 6px 10px;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.input-panel {
|
|
||||||
border-top: 1px solid var(--ai-border);
|
|
||||||
padding: 10px 12px;
|
|
||||||
display: grid;
|
|
||||||
gap: 8px;
|
|
||||||
|
|
||||||
textarea {
|
|
||||||
width: 100%;
|
|
||||||
min-height: 80px;
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 10px;
|
|
||||||
background: var(--ai-surface-soft);
|
|
||||||
color: var(--text-primary);
|
|
||||||
padding: 10px;
|
|
||||||
resize: vertical;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.suggestions {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 6px;
|
|
||||||
|
|
||||||
button {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 999px;
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
padding: 4px 10px;
|
|
||||||
font-size: 12px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.input-actions {
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
|
|
||||||
button {
|
|
||||||
border-radius: 9px;
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
padding: 7px 12px;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.primary {
|
|
||||||
background: color-mix(in srgb, var(--ai-accent) 18%, transparent);
|
|
||||||
color: var(--text-primary);
|
|
||||||
border-color: color-mix(in srgb, var(--ai-accent) 52%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.danger {
|
|
||||||
background: color-mix(in srgb, #ef4444 12%, transparent);
|
|
||||||
color: var(--text-primary);
|
|
||||||
border-color: color-mix(in srgb, #ef4444 45%, transparent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.sql-layout {
|
|
||||||
grid-template-columns: 300px minmax(0, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.schema-panel {
|
|
||||||
display: grid;
|
|
||||||
grid-template-rows: auto minmax(0, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.schema-list {
|
|
||||||
overflow: auto;
|
|
||||||
padding: 10px;
|
|
||||||
display: grid;
|
|
||||||
gap: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.schema-source {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 8px;
|
|
||||||
|
|
||||||
h4 {
|
|
||||||
margin: 0 0 8px;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
ul {
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
list-style: none;
|
|
||||||
display: grid;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
li {
|
|
||||||
display: grid;
|
|
||||||
gap: 4px;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
small {
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.sql-main {
|
|
||||||
min-height: 0;
|
|
||||||
display: grid;
|
|
||||||
grid-template-rows: auto auto auto minmax(0, 1fr) auto;
|
|
||||||
gap: 8px;
|
|
||||||
padding: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sql-bar {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
|
|
||||||
select,
|
|
||||||
button {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 9px;
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
padding: 6px 10px;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
cursor: pointer;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.sql-prompt,
|
|
||||||
.sql-generated,
|
|
||||||
.tool-args {
|
|
||||||
width: 100%;
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 10px;
|
|
||||||
background: var(--ai-surface-soft);
|
|
||||||
color: var(--text-primary);
|
|
||||||
padding: 10px;
|
|
||||||
font-size: 12px;
|
|
||||||
min-height: 90px;
|
|
||||||
resize: vertical;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sql-generated {
|
|
||||||
min-height: 120px;
|
|
||||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sql-table-wrap {
|
|
||||||
min-height: 0;
|
|
||||||
overflow: auto;
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sql-table {
|
|
||||||
width: 100%;
|
|
||||||
border-collapse: collapse;
|
|
||||||
|
|
||||||
th,
|
|
||||||
td {
|
|
||||||
border-bottom: 1px solid var(--ai-border);
|
|
||||||
border-right: 1px solid var(--ai-border);
|
|
||||||
padding: 7px 8px;
|
|
||||||
font-size: 12px;
|
|
||||||
text-align: left;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
th {
|
|
||||||
cursor: pointer;
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 5%, transparent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.pager {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 8px;
|
|
||||||
padding: 8px;
|
|
||||||
|
|
||||||
button {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 4px 8px;
|
|
||||||
font-size: 12px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.sql-history {
|
|
||||||
border-top: 1px solid var(--ai-border);
|
|
||||||
padding-top: 8px;
|
|
||||||
|
|
||||||
h4 {
|
|
||||||
margin: 0 0 8px;
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.history-list {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 6px;
|
|
||||||
|
|
||||||
button {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 5px 8px;
|
|
||||||
font-size: 12px;
|
|
||||||
cursor: pointer;
|
|
||||||
max-width: 100%;
|
|
||||||
text-align: left;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tool-layout {
|
|
||||||
grid-template-columns: 320px minmax(0, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.tool-catalog {
|
|
||||||
padding: 12px;
|
|
||||||
overflow: auto;
|
|
||||||
|
|
||||||
h3,
|
|
||||||
h4 {
|
|
||||||
margin: 0 0 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
h4 {
|
|
||||||
margin-top: 14px;
|
|
||||||
font-size: 12px;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tool-list {
|
|
||||||
display: grid;
|
|
||||||
gap: 6px;
|
|
||||||
|
|
||||||
button {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 7px 8px;
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 3%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
text-align: left;
|
|
||||||
font-size: 12px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.active {
|
|
||||||
border-color: color-mix(in srgb, var(--ai-accent) 52%, transparent);
|
|
||||||
background: color-mix(in srgb, var(--ai-accent) 12%, transparent);
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tool-main {
|
|
||||||
display: grid;
|
|
||||||
grid-template-rows: auto auto minmax(0, 1fr);
|
|
||||||
gap: 8px;
|
|
||||||
padding: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tool-top {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 12px;
|
|
||||||
|
|
||||||
h3 {
|
|
||||||
margin: 0 0 6px;
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
p {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 12px;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.actions {
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
|
|
||||||
button {
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 8px;
|
|
||||||
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
padding: 6px 9px;
|
|
||||||
font-size: 12px;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tool-output {
|
|
||||||
margin: 0;
|
|
||||||
border: 1px solid var(--ai-border);
|
|
||||||
border-radius: 10px;
|
|
||||||
background: var(--ai-surface-soft);
|
|
||||||
padding: 10px;
|
|
||||||
min-height: 160px;
|
|
||||||
overflow: auto;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.empty {
|
|
||||||
padding: 14px;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
font-size: 12px;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.error,
|
|
||||||
.global-error {
|
|
||||||
border: 1px solid color-mix(in srgb, #dc2626 55%, transparent);
|
|
||||||
background: color-mix(in srgb, #dc2626 12%, transparent);
|
|
||||||
color: color-mix(in srgb, #dc2626 85%, #111827 15%);
|
|
||||||
border-radius: 10px;
|
|
||||||
padding: 8px 10px;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.spin {
|
|
||||||
animation: ai-spin 1s linear infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes ai-spin {
|
|
||||||
from { transform: rotate(0deg); }
|
|
||||||
to { transform: rotate(360deg); }
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 1100px) {
|
|
||||||
.chat-layout,
|
|
||||||
.sql-layout,
|
|
||||||
.tool-layout {
|
|
||||||
grid-template-columns: minmax(0, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.conversation-panel,
|
|
||||||
.schema-panel,
|
|
||||||
.tool-catalog {
|
|
||||||
max-height: 260px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,881 +0,0 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
||||||
import {
|
|
||||||
Bot,
|
|
||||||
Braces,
|
|
||||||
CircleStop,
|
|
||||||
Database,
|
|
||||||
Download,
|
|
||||||
Loader2,
|
|
||||||
Play,
|
|
||||||
RefreshCw,
|
|
||||||
Search,
|
|
||||||
Send,
|
|
||||||
Sparkles,
|
|
||||||
SquareTerminal,
|
|
||||||
Trash2,
|
|
||||||
Wrench
|
|
||||||
} from 'lucide-react'
|
|
||||||
import type {
|
|
||||||
AiConversation,
|
|
||||||
AiMessageRecord,
|
|
||||||
AssistantSummary,
|
|
||||||
SkillSummary,
|
|
||||||
SqlResultPayload,
|
|
||||||
SqlSchemaPayload,
|
|
||||||
ToolCatalogEntry
|
|
||||||
} from '../types/aiAnalysis'
|
|
||||||
import { useAiRuntimeStore } from '../stores/aiRuntimeStore'
|
|
||||||
import type { AgentStreamChunk } from '../types/electron'
|
|
||||||
import './AiAnalysisPage.scss'
|
|
||||||
|
|
||||||
type MainTab = 'chat' | 'sql' | 'tool'
|
|
||||||
type ScopeMode = 'global' | 'contact' | 'session'
|
|
||||||
|
|
||||||
function formatDateTime(ts: number): string {
|
|
||||||
if (!ts) return '--'
|
|
||||||
const d = new Date(ts)
|
|
||||||
const y = d.getFullYear()
|
|
||||||
const m = `${d.getMonth() + 1}`.padStart(2, '0')
|
|
||||||
const day = `${d.getDate()}`.padStart(2, '0')
|
|
||||||
const hh = `${d.getHours()}`.padStart(2, '0')
|
|
||||||
const mm = `${d.getMinutes()}`.padStart(2, '0')
|
|
||||||
return `${y}-${m}-${day} ${hh}:${mm}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeText(value: unknown, fallback = ''): string {
|
|
||||||
const text = String(value ?? '').trim()
|
|
||||||
return text || fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
function extractSqlTarget(schema: SqlSchemaPayload | null, key: string): { kind: 'message' | 'contact' | 'biz'; path: string | null } | null {
|
|
||||||
if (!schema) return null
|
|
||||||
for (const source of schema.sources) {
|
|
||||||
const sourceKey = `${source.kind}:${source.path || ''}`
|
|
||||||
if (sourceKey === key) return { kind: source.kind, path: source.path }
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
function toCsv(rows: Record<string, unknown>[], columns: string[]): string {
|
|
||||||
const esc = (value: unknown) => {
|
|
||||||
const text = String(value ?? '')
|
|
||||||
if (/[",\n\r]/.test(text)) return `"${text.replace(/"/g, '""')}"`
|
|
||||||
return text
|
|
||||||
}
|
|
||||||
const header = columns.map((column) => esc(column)).join(',')
|
|
||||||
const body = rows.map((row) => columns.map((column) => esc(row[column])).join(',')).join('\n')
|
|
||||||
return `${header}\n${body}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function AiAnalysisPage() {
|
|
||||||
const aiApi = window.electronAPI.aiApi
|
|
||||||
const agentApi = window.electronAPI.agentApi
|
|
||||||
const assistantApi = window.electronAPI.assistantApi
|
|
||||||
const skillApi = window.electronAPI.skillApi
|
|
||||||
const [activeTab, setActiveTab] = useState<MainTab>('chat')
|
|
||||||
const [scopeMode, setScopeMode] = useState<ScopeMode>('global')
|
|
||||||
const [scopeTarget, setScopeTarget] = useState('')
|
|
||||||
const [conversations, setConversations] = useState<AiConversation[]>([])
|
|
||||||
const [currentConversationId, setCurrentConversationId] = useState('')
|
|
||||||
const [messages, setMessages] = useState<AiMessageRecord[]>([])
|
|
||||||
const [assistants, setAssistants] = useState<AssistantSummary[]>([])
|
|
||||||
const [selectedAssistantId, setSelectedAssistantId] = useState('general_cn')
|
|
||||||
const [skills, setSkills] = useState<SkillSummary[]>([])
|
|
||||||
const [selectedSkillId, setSelectedSkillId] = useState('')
|
|
||||||
const [contacts, setContacts] = useState<Array<{ username: string; displayName: string }>>([])
|
|
||||||
const [input, setInput] = useState('')
|
|
||||||
const [loadingConversations, setLoadingConversations] = useState(false)
|
|
||||||
const [loadingMessages, setLoadingMessages] = useState(false)
|
|
||||||
const [errorText, setErrorText] = useState('')
|
|
||||||
|
|
||||||
const [sqlPrompt, setSqlPrompt] = useState('')
|
|
||||||
const [sqlGenerated, setSqlGenerated] = useState('')
|
|
||||||
const [sqlGenerating, setSqlGenerating] = useState(false)
|
|
||||||
const [sqlSchema, setSqlSchema] = useState<SqlSchemaPayload | null>(null)
|
|
||||||
const [sqlSchemaText, setSqlSchemaText] = useState('')
|
|
||||||
const [sqlTargetKey, setSqlTargetKey] = useState('message:')
|
|
||||||
const [sqlResult, setSqlResult] = useState<SqlResultPayload | null>(null)
|
|
||||||
const [sqlError, setSqlError] = useState('')
|
|
||||||
const [sqlHistory, setSqlHistory] = useState<string[]>([])
|
|
||||||
const [sqlSortBy, setSqlSortBy] = useState('')
|
|
||||||
const [sqlSortOrder, setSqlSortOrder] = useState<'asc' | 'desc'>('asc')
|
|
||||||
const [sqlPage, setSqlPage] = useState(1)
|
|
||||||
const [sqlPageSize] = useState(50)
|
|
||||||
|
|
||||||
const [toolCatalog, setToolCatalog] = useState<ToolCatalogEntry[]>([])
|
|
||||||
const [toolName, setToolName] = useState('')
|
|
||||||
const [toolArgsText, setToolArgsText] = useState('{}')
|
|
||||||
const [toolRunning, setToolRunning] = useState(false)
|
|
||||||
const [toolOutput, setToolOutput] = useState('')
|
|
||||||
|
|
||||||
const sqlRunIdRef = useRef('')
|
|
||||||
const sqlGeneratedRef = useRef('')
|
|
||||||
const messageEndRef = useRef<HTMLDivElement | null>(null)
|
|
||||||
|
|
||||||
const activeRunId = useAiRuntimeStore((state) => state.activeRunId)
|
|
||||||
const runtimeState = useAiRuntimeStore((state) => (
|
|
||||||
currentConversationId ? state.states[currentConversationId] : undefined
|
|
||||||
))
|
|
||||||
const startRun = useAiRuntimeStore((state) => state.startRun)
|
|
||||||
const appendChunk = useAiRuntimeStore((state) => state.appendChunk)
|
|
||||||
const finishRun = useAiRuntimeStore((state) => state.finishRun)
|
|
||||||
|
|
||||||
const selectedAssistant = useMemo(
|
|
||||||
() => assistants.find((assistant) => assistant.id === selectedAssistantId) || null,
|
|
||||||
[assistants, selectedAssistantId]
|
|
||||||
)
|
|
||||||
|
|
||||||
const slashSuggestions = useMemo(() => {
|
|
||||||
const text = normalizeText(input)
|
|
||||||
if (!text.startsWith('/')) return []
|
|
||||||
const key = text.slice(1).toLowerCase()
|
|
||||||
return skills.filter((skill) => !key || skill.id.includes(key) || skill.name.toLowerCase().includes(key)).slice(0, 8)
|
|
||||||
}, [input, skills])
|
|
||||||
|
|
||||||
const mentionSuggestions = useMemo(() => {
|
|
||||||
const match = input.match(/@([^\s@]*)$/)
|
|
||||||
if (!match) return []
|
|
||||||
const keyword = match[1].toLowerCase()
|
|
||||||
return contacts
|
|
||||||
.filter((contact) => !keyword || contact.displayName.toLowerCase().includes(keyword) || contact.username.toLowerCase().includes(keyword))
|
|
||||||
.slice(0, 8)
|
|
||||||
}, [contacts, input])
|
|
||||||
|
|
||||||
const sqlTargetOptions = useMemo(() => {
|
|
||||||
if (!sqlSchema) return []
|
|
||||||
return sqlSchema.sources.map((source) => ({
|
|
||||||
key: `${source.kind}:${source.path || ''}`,
|
|
||||||
label: `[${source.kind}] ${source.label}`
|
|
||||||
}))
|
|
||||||
}, [sqlSchema])
|
|
||||||
|
|
||||||
const sqlSortedRows = useMemo(() => {
|
|
||||||
const rows = sqlResult?.rows || []
|
|
||||||
if (!sqlSortBy) return rows
|
|
||||||
const copied = [...rows]
|
|
||||||
copied.sort((a, b) => {
|
|
||||||
const left = String(a[sqlSortBy] ?? '')
|
|
||||||
const right = String(b[sqlSortBy] ?? '')
|
|
||||||
if (left === right) return 0
|
|
||||||
return sqlSortOrder === 'asc' ? (left > right ? 1 : -1) : (left > right ? -1 : 1)
|
|
||||||
})
|
|
||||||
return copied
|
|
||||||
}, [sqlResult, sqlSortBy, sqlSortOrder])
|
|
||||||
|
|
||||||
const sqlPagedRows = useMemo(() => {
|
|
||||||
const start = (sqlPage - 1) * sqlPageSize
|
|
||||||
return sqlSortedRows.slice(start, start + sqlPageSize)
|
|
||||||
}, [sqlPage, sqlPageSize, sqlSortedRows])
|
|
||||||
|
|
||||||
const loadConversations = useCallback(async () => {
|
|
||||||
setLoadingConversations(true)
|
|
||||||
try {
|
|
||||||
const res = await aiApi.listConversations({ page: 1, pageSize: 200 })
|
|
||||||
if (!res.success) {
|
|
||||||
setErrorText(res.error || '加载会话失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const list = res.conversations || []
|
|
||||||
setConversations(list)
|
|
||||||
if (!currentConversationId && list.length > 0) setCurrentConversationId(list[0].conversationId)
|
|
||||||
} finally {
|
|
||||||
setLoadingConversations(false)
|
|
||||||
}
|
|
||||||
}, [aiApi, currentConversationId])
|
|
||||||
|
|
||||||
const loadMessages = useCallback(async (conversationId: string) => {
|
|
||||||
if (!conversationId) return
|
|
||||||
setLoadingMessages(true)
|
|
||||||
try {
|
|
||||||
const res = await aiApi.listMessages({ conversationId, limit: 1200 })
|
|
||||||
if (!res.success) {
|
|
||||||
setErrorText(res.error || '加载消息失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setMessages((res.messages || []).filter((message) => normalizeText(message.role) !== 'tool'))
|
|
||||||
} finally {
|
|
||||||
setLoadingMessages(false)
|
|
||||||
}
|
|
||||||
}, [aiApi])
|
|
||||||
|
|
||||||
const loadAssistantsAndSkills = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const [assistantList, skillList] = await Promise.all([
|
|
||||||
assistantApi.getAll(),
|
|
||||||
skillApi.getAll()
|
|
||||||
])
|
|
||||||
setAssistants(assistantList || [])
|
|
||||||
setSkills(skillList || [])
|
|
||||||
if (assistantList && assistantList.length > 0 && !assistantList.some((item) => item.id === selectedAssistantId)) {
|
|
||||||
setSelectedAssistantId(assistantList[0].id)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
setErrorText(String((error as Error)?.message || error))
|
|
||||||
}
|
|
||||||
}, [assistantApi, skillApi, selectedAssistantId])
|
|
||||||
|
|
||||||
const loadContacts = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const res = await window.electronAPI.chat.getContacts({ lite: true })
|
|
||||||
if (!res.success || !res.contacts) return
|
|
||||||
const list = res.contacts
|
|
||||||
.map((contact) => ({
|
|
||||||
username: normalizeText(contact.username),
|
|
||||||
displayName: normalizeText(contact.displayName || contact.remark || contact.nickname || contact.username)
|
|
||||||
}))
|
|
||||||
.filter((contact) => contact.username && contact.displayName)
|
|
||||||
.slice(0, 300)
|
|
||||||
setContacts(list)
|
|
||||||
} catch {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const loadToolCatalog = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const catalog = await aiApi.getToolCatalog()
|
|
||||||
setToolCatalog(Array.isArray(catalog) ? catalog : [])
|
|
||||||
if (!toolName && Array.isArray(catalog) && catalog.length > 0) {
|
|
||||||
setToolName(catalog[0].name)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
setErrorText(String((error as Error)?.message || error))
|
|
||||||
}
|
|
||||||
}, [aiApi, toolName])
|
|
||||||
|
|
||||||
const loadSchema = useCallback(async () => {
|
|
||||||
const res = await window.electronAPI.chat.getSchema({})
|
|
||||||
if (!res.success || !res.schema) {
|
|
||||||
setSqlError(res.error || 'Schema 加载失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setSqlSchema(res.schema)
|
|
||||||
setSqlSchemaText(res.schemaText || '')
|
|
||||||
if (res.schema.sources.length > 0) {
|
|
||||||
setSqlTargetKey(`${res.schema.sources[0].kind}:${res.schema.sources[0].path || ''}`)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
void loadConversations()
|
|
||||||
void loadAssistantsAndSkills()
|
|
||||||
void loadContacts()
|
|
||||||
}, [loadConversations, loadAssistantsAndSkills, loadContacts])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!currentConversationId) return
|
|
||||||
void loadMessages(currentConversationId)
|
|
||||||
}, [currentConversationId, loadMessages])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (activeTab === 'sql' && !sqlSchema) void loadSchema()
|
|
||||||
if (activeTab === 'tool' && toolCatalog.length === 0) void loadToolCatalog()
|
|
||||||
}, [activeTab, sqlSchema, loadSchema, toolCatalog.length, loadToolCatalog])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const off = agentApi.onStream((chunk: AgentStreamChunk) => {
|
|
||||||
if (sqlRunIdRef.current && chunk.runId === sqlRunIdRef.current) {
|
|
||||||
if (chunk.type === 'content') {
|
|
||||||
setSqlGenerated((prev) => {
|
|
||||||
const next = `${prev}${chunk.content || ''}`
|
|
||||||
sqlGeneratedRef.current = next
|
|
||||||
return next
|
|
||||||
})
|
|
||||||
} else if (chunk.type === 'done') {
|
|
||||||
setSqlGenerating(false)
|
|
||||||
if (normalizeText(sqlGeneratedRef.current)) {
|
|
||||||
setSqlHistory((prev) => [sqlGeneratedRef.current.trim(), ...prev].slice(0, 30))
|
|
||||||
}
|
|
||||||
sqlRunIdRef.current = ''
|
|
||||||
} else if (chunk.type === 'error') {
|
|
||||||
setSqlGenerating(false)
|
|
||||||
setSqlError(chunk.error || 'SQL 生成失败')
|
|
||||||
sqlRunIdRef.current = ''
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const conversationId = normalizeText(chunk.conversationId, currentConversationId)
|
|
||||||
if (!conversationId) return
|
|
||||||
appendChunk(conversationId, chunk)
|
|
||||||
if (chunk.type === 'done' || chunk.type === 'error' || chunk.isFinished) {
|
|
||||||
finishRun(conversationId)
|
|
||||||
void loadMessages(conversationId)
|
|
||||||
void loadConversations()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return () => off()
|
|
||||||
}, [agentApi, appendChunk, currentConversationId, finishRun, loadConversations, loadMessages])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
messageEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' })
|
|
||||||
}, [messages, runtimeState?.draft, runtimeState?.chunks.length])
|
|
||||||
|
|
||||||
const ensureConversation = useCallback(async (): Promise<string> => {
|
|
||||||
if (currentConversationId) return currentConversationId
|
|
||||||
const created = await aiApi.createConversation({ title: '新的 AI 对话' })
|
|
||||||
if (!created.success || !created.conversationId) throw new Error(created.error || '创建会话失败')
|
|
||||||
setCurrentConversationId(created.conversationId)
|
|
||||||
await loadConversations()
|
|
||||||
return created.conversationId
|
|
||||||
}, [aiApi, currentConversationId, loadConversations])
|
|
||||||
|
|
||||||
const handleCreateConversation = async () => {
|
|
||||||
const created = await aiApi.createConversation({ title: '新的 AI 对话' })
|
|
||||||
if (!created.success || !created.conversationId) {
|
|
||||||
setErrorText(created.error || '创建会话失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setCurrentConversationId(created.conversationId)
|
|
||||||
setMessages([])
|
|
||||||
setErrorText('')
|
|
||||||
await loadConversations()
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleRenameConversation = async (conversationId: string) => {
|
|
||||||
const current = conversations.find((item) => item.conversationId === conversationId)
|
|
||||||
const nextTitle = window.prompt('请输入新的会话标题', current?.title || '新的 AI 对话')
|
|
||||||
if (!nextTitle) return
|
|
||||||
const result = await aiApi.renameConversation({ conversationId, title: nextTitle })
|
|
||||||
if (!result.success) {
|
|
||||||
setErrorText(result.error || '重命名失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
await loadConversations()
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDeleteConversation = async (conversationId: string) => {
|
|
||||||
const ok = window.confirm('确认删除该会话吗?')
|
|
||||||
if (!ok) return
|
|
||||||
const result = await aiApi.deleteConversation(conversationId)
|
|
||||||
if (!result.success) {
|
|
||||||
setErrorText(result.error || '删除失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (currentConversationId === conversationId) {
|
|
||||||
setCurrentConversationId('')
|
|
||||||
setMessages([])
|
|
||||||
}
|
|
||||||
await loadConversations()
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSend = async () => {
|
|
||||||
const text = normalizeText(input)
|
|
||||||
if (!text) return
|
|
||||||
setErrorText('')
|
|
||||||
const conversationId = await ensureConversation()
|
|
||||||
setMessages((prev) => ([
|
|
||||||
...prev,
|
|
||||||
{
|
|
||||||
messageId: `temp-${Date.now()}`,
|
|
||||||
conversationId,
|
|
||||||
role: 'user',
|
|
||||||
content: text,
|
|
||||||
intentType: '',
|
|
||||||
components: [],
|
|
||||||
toolTrace: [],
|
|
||||||
createdAt: Date.now()
|
|
||||||
}
|
|
||||||
]))
|
|
||||||
setInput('')
|
|
||||||
const run = await agentApi.runStream({
|
|
||||||
mode: 'chat',
|
|
||||||
conversationId,
|
|
||||||
userInput: text,
|
|
||||||
assistantId: selectedAssistantId,
|
|
||||||
activeSkillId: selectedSkillId || undefined,
|
|
||||||
chatScope: scopeMode === 'session' ? 'private' : 'private'
|
|
||||||
})
|
|
||||||
if (!run.success || !run.runId) {
|
|
||||||
setErrorText('启动失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
startRun(conversationId, run.runId)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleStop = async () => {
|
|
||||||
if (!currentConversationId) return
|
|
||||||
await agentApi.abort({ runId: activeRunId || undefined, conversationId: currentConversationId })
|
|
||||||
finishRun(currentConversationId)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleExportConversation = async () => {
|
|
||||||
if (!currentConversationId) return
|
|
||||||
const result = await aiApi.exportConversation({ conversationId: currentConversationId })
|
|
||||||
if (!result.success || !result.markdown) {
|
|
||||||
setErrorText(result.error || '导出失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
await navigator.clipboard.writeText(result.markdown)
|
|
||||||
window.alert('会话 Markdown 已复制到剪贴板')
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleOpenLog = async () => {
|
|
||||||
const logPath = await window.electronAPI.log.getPath()
|
|
||||||
await window.electronAPI.shell.openPath(logPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleGenerateSql = async () => {
|
|
||||||
const prompt = normalizeText(sqlPrompt)
|
|
||||||
if (!prompt) return
|
|
||||||
setSqlGenerating(true)
|
|
||||||
setSqlGenerated('')
|
|
||||||
sqlGeneratedRef.current = ''
|
|
||||||
setSqlError('')
|
|
||||||
const target = extractSqlTarget(sqlSchema, sqlTargetKey)
|
|
||||||
const run = await agentApi.runStream({
|
|
||||||
mode: 'sql',
|
|
||||||
userInput: prompt,
|
|
||||||
sqlContext: {
|
|
||||||
schemaText: sqlSchemaText,
|
|
||||||
targetHint: target ? `${target.kind}:${target.path || ''}` : ''
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if (!run.success || !run.runId) {
|
|
||||||
setSqlGenerating(false)
|
|
||||||
setSqlError('SQL 生成失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
sqlRunIdRef.current = run.runId
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleExecuteSql = async () => {
|
|
||||||
const sql = normalizeText(sqlGenerated)
|
|
||||||
if (!sql) return
|
|
||||||
const target = extractSqlTarget(sqlSchema, sqlTargetKey)
|
|
||||||
if (!target) {
|
|
||||||
setSqlError('请选择 SQL 数据源')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const result = await window.electronAPI.chat.executeSQL({
|
|
||||||
kind: target.kind,
|
|
||||||
path: target.path,
|
|
||||||
sql,
|
|
||||||
limit: 500
|
|
||||||
})
|
|
||||||
if (!result.success || !result.rows || !result.columns) {
|
|
||||||
setSqlError(result.error || '执行失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setSqlError('')
|
|
||||||
setSqlResult({
|
|
||||||
rows: result.rows,
|
|
||||||
columns: result.columns,
|
|
||||||
total: result.total || result.rows.length
|
|
||||||
})
|
|
||||||
setSqlHistory((prev) => [sql, ...prev].slice(0, 30))
|
|
||||||
setSqlPage(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleExportSqlRows = () => {
|
|
||||||
if (!sqlResult || sqlResult.rows.length === 0) return
|
|
||||||
const csv = toCsv(sqlResult.rows, sqlResult.columns)
|
|
||||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
|
|
||||||
const url = URL.createObjectURL(blob)
|
|
||||||
const link = document.createElement('a')
|
|
||||||
link.href = url
|
|
||||||
link.download = `sql-result-${Date.now()}.csv`
|
|
||||||
link.click()
|
|
||||||
URL.revokeObjectURL(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleRunTool = async () => {
|
|
||||||
setToolRunning(true)
|
|
||||||
try {
|
|
||||||
const args = JSON.parse(toolArgsText || '{}')
|
|
||||||
const result = await aiApi.executeTool({ name: toolName, args })
|
|
||||||
setToolOutput(JSON.stringify(result, null, 2))
|
|
||||||
} catch (error) {
|
|
||||||
setToolOutput(String((error as Error)?.message || error))
|
|
||||||
} finally {
|
|
||||||
setToolRunning(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const groupedTools = useMemo(() => ({
|
|
||||||
core: toolCatalog.filter((item) => item.category === 'core'),
|
|
||||||
analysis: toolCatalog.filter((item) => item.category === 'analysis')
|
|
||||||
}), [toolCatalog])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="ai-analysis-v2">
|
|
||||||
<header className="ai-header">
|
|
||||||
<div className="left">
|
|
||||||
<Sparkles size={18} />
|
|
||||||
<h1>AI Analysis</h1>
|
|
||||||
<span>Chat Explorer + SQL Lab + Tool Test</span>
|
|
||||||
</div>
|
|
||||||
<div className="tabs">
|
|
||||||
<button type="button" className={activeTab === 'chat' ? 'active' : ''} onClick={() => setActiveTab('chat')}>
|
|
||||||
<Bot size={14} />
|
|
||||||
Chat Explorer
|
|
||||||
</button>
|
|
||||||
<button type="button" className={activeTab === 'sql' ? 'active' : ''} onClick={() => setActiveTab('sql')}>
|
|
||||||
<Database size={14} />
|
|
||||||
SQL Lab
|
|
||||||
</button>
|
|
||||||
<button type="button" className={activeTab === 'tool' ? 'active' : ''} onClick={() => setActiveTab('tool')}>
|
|
||||||
<SquareTerminal size={14} />
|
|
||||||
Tool Test
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{activeTab === 'chat' && (
|
|
||||||
<div className="chat-layout">
|
|
||||||
<aside className="conversation-panel">
|
|
||||||
<div className="panel-head">
|
|
||||||
<h3>会话</h3>
|
|
||||||
<button type="button" onClick={() => void handleCreateConversation()} title="新建">+</button>
|
|
||||||
</div>
|
|
||||||
{loadingConversations ? (
|
|
||||||
<div className="empty"><Loader2 className="spin" size={14} /> 加载中...</div>
|
|
||||||
) : (
|
|
||||||
<div className="conversation-list">
|
|
||||||
{conversations.map((conversation) => (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
key={conversation.conversationId}
|
|
||||||
className={`conversation-item ${currentConversationId === conversation.conversationId ? 'active' : ''}`}
|
|
||||||
onClick={() => setCurrentConversationId(conversation.conversationId)}
|
|
||||||
>
|
|
||||||
<div className="main">
|
|
||||||
<strong>{conversation.title || '新的 AI 对话'}</strong>
|
|
||||||
<small>{formatDateTime(conversation.updatedAt)}</small>
|
|
||||||
</div>
|
|
||||||
<div className="ops">
|
|
||||||
<span onClick={(event) => { event.stopPropagation(); void handleRenameConversation(conversation.conversationId) }}>重命名</span>
|
|
||||||
<span onClick={(event) => { event.stopPropagation(); void handleDeleteConversation(conversation.conversationId) }}><Trash2 size={12} /></span>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
{conversations.length === 0 && <div className="empty">暂无会话</div>}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
<section className="chat-main">
|
|
||||||
<div className="chat-toolbar">
|
|
||||||
<div className="row">
|
|
||||||
<label>助手</label>
|
|
||||||
<select value={selectedAssistantId} onChange={(event) => setSelectedAssistantId(event.target.value)}>
|
|
||||||
{assistants.map((assistant) => (
|
|
||||||
<option key={assistant.id} value={assistant.id}>{assistant.name}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<label>技能</label>
|
|
||||||
<select value={selectedSkillId} onChange={(event) => setSelectedSkillId(event.target.value)}>
|
|
||||||
<option value="">无</option>
|
|
||||||
{skills.map((skill) => (
|
|
||||||
<option key={skill.id} value={skill.id}>{skill.name}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<label>范围</label>
|
|
||||||
<select value={scopeMode} onChange={(event) => setScopeMode(event.target.value as ScopeMode)}>
|
|
||||||
<option value="global">全局</option>
|
|
||||||
<option value="contact">联系人</option>
|
|
||||||
<option value="session">会话</option>
|
|
||||||
</select>
|
|
||||||
{scopeMode !== 'global' && (
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={scopeTarget}
|
|
||||||
onChange={(event) => setScopeTarget(event.target.value)}
|
|
||||||
placeholder={scopeMode === 'contact' ? '联系人昵称/账号' : '会话ID'}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{selectedAssistant?.presetQuestions?.length ? (
|
|
||||||
<div className="preset-row">
|
|
||||||
{selectedAssistant.presetQuestions.slice(0, 8).map((question) => (
|
|
||||||
<button key={question} type="button" onClick={() => setInput(question)}>{question}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="message-panel">
|
|
||||||
{loadingMessages ? (
|
|
||||||
<div className="empty"><Loader2 className="spin" size={14} /> 加载消息...</div>
|
|
||||||
) : (
|
|
||||||
<div className="message-list">
|
|
||||||
{messages.map((message) => (
|
|
||||||
<div key={message.messageId} className={`msg ${message.role === 'user' ? 'user' : message.role}`}>
|
|
||||||
<div className="head">{message.role === 'user' ? '你' : message.role === 'assistant' ? '助手' : message.role}</div>
|
|
||||||
<div className="body">{message.content || '(空)'}</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{runtimeState?.running && runtimeState?.chunks?.length ? (
|
|
||||||
<div className="runtime-cards">
|
|
||||||
{runtimeState.chunks
|
|
||||||
.filter((chunk) => chunk.type === 'tool_start' || chunk.type === 'tool_result' || chunk.type === 'error')
|
|
||||||
.slice(-16)
|
|
||||||
.map((chunk, index) => (
|
|
||||||
<div key={`${chunk.runId}-${index}`} className={`chunk ${chunk.type}`}>
|
|
||||||
<strong>{chunk.type}</strong>
|
|
||||||
{chunk.toolName ? <span>{chunk.toolName}</span> : null}
|
|
||||||
{chunk.content ? <pre>{chunk.content}</pre> : null}
|
|
||||||
{chunk.type === 'tool_result' && chunk.toolResult !== undefined ? (
|
|
||||||
<pre>{JSON.stringify(chunk.toolResult, null, 2)}</pre>
|
|
||||||
) : null}
|
|
||||||
{chunk.error ? <span className="err">{chunk.error}</span> : null}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{runtimeState?.draft ? (
|
|
||||||
<div className="msg assistant draft">
|
|
||||||
<div className="head">助手(流式)</div>
|
|
||||||
<div className="body">{runtimeState.draft}</div>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<div ref={messageEndRef} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="footer-actions">
|
|
||||||
<button type="button" className="ghost" onClick={() => void loadConversations()}>
|
|
||||||
<RefreshCw size={14} />
|
|
||||||
刷新
|
|
||||||
</button>
|
|
||||||
<button type="button" className="ghost" onClick={() => void handleExportConversation()}>
|
|
||||||
<Download size={14} />
|
|
||||||
导出会话
|
|
||||||
</button>
|
|
||||||
<button type="button" className="ghost" onClick={() => void handleOpenLog()}>
|
|
||||||
<Search size={14} />
|
|
||||||
打开日志
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="input-panel">
|
|
||||||
<textarea
|
|
||||||
value={input}
|
|
||||||
onChange={(event) => setInput(event.target.value)}
|
|
||||||
placeholder="输入问题,支持 /技能 和 @成员"
|
|
||||||
onKeyDown={(event) => {
|
|
||||||
if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
|
|
||||||
event.preventDefault()
|
|
||||||
void handleSend()
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{slashSuggestions.length > 0 && (
|
|
||||||
<div className="suggestions">
|
|
||||||
{slashSuggestions.map((skill) => (
|
|
||||||
<button key={skill.id} type="button" onClick={() => { setSelectedSkillId(skill.id); setInput('') }}>
|
|
||||||
/{skill.id} · {skill.name}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{mentionSuggestions.length > 0 && (
|
|
||||||
<div className="suggestions">
|
|
||||||
{mentionSuggestions.map((contact) => (
|
|
||||||
<button
|
|
||||||
key={contact.username}
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
setInput((prev) => prev.replace(/@([^\s@]*)$/, `@${contact.displayName} `))
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
@{contact.displayName}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="input-actions">
|
|
||||||
<button type="button" className="primary" onClick={() => void handleSend()} disabled={runtimeState?.running}>
|
|
||||||
{runtimeState?.running ? <Loader2 className="spin" size={14} /> : <Send size={14} />}
|
|
||||||
发送
|
|
||||||
</button>
|
|
||||||
<button type="button" className="danger" onClick={() => void handleStop()} disabled={!runtimeState?.running}>
|
|
||||||
<CircleStop size={14} />
|
|
||||||
停止
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{activeTab === 'sql' && (
|
|
||||||
<div className="sql-layout">
|
|
||||||
<aside className="schema-panel">
|
|
||||||
<div className="panel-head">
|
|
||||||
<h3>Schema</h3>
|
|
||||||
<button type="button" onClick={() => void loadSchema()}><RefreshCw size={13} /></button>
|
|
||||||
</div>
|
|
||||||
<div className="schema-list">
|
|
||||||
{sqlSchema?.sources.map((source) => (
|
|
||||||
<div key={`${source.kind}:${source.path || ''}`} className="schema-source">
|
|
||||||
<h4>[{source.kind}] {source.label}</h4>
|
|
||||||
<ul>
|
|
||||||
{source.tables.slice(0, 24).map((table) => (
|
|
||||||
<li key={table.name}>
|
|
||||||
<strong>{table.name}</strong>
|
|
||||||
<small>{table.columns.slice(0, 10).join(', ')}</small>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
<section className="sql-main">
|
|
||||||
<div className="sql-bar">
|
|
||||||
<select value={sqlTargetKey} onChange={(event) => setSqlTargetKey(event.target.value)}>
|
|
||||||
{sqlTargetOptions.map((option) => <option key={option.key} value={option.key}>{option.label}</option>)}
|
|
||||||
</select>
|
|
||||||
<button type="button" onClick={() => void handleGenerateSql()} disabled={sqlGenerating}>
|
|
||||||
{sqlGenerating ? <Loader2 className="spin" size={14} /> : <Braces size={14} />}
|
|
||||||
生成 SQL
|
|
||||||
</button>
|
|
||||||
<button type="button" onClick={() => void handleExecuteSql()}>
|
|
||||||
<Play size={14} />
|
|
||||||
执行 SQL
|
|
||||||
</button>
|
|
||||||
<button type="button" onClick={handleExportSqlRows} disabled={!sqlResult?.rows?.length}>
|
|
||||||
<Download size={14} />
|
|
||||||
导出结果
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<textarea
|
|
||||||
className="sql-prompt"
|
|
||||||
value={sqlPrompt}
|
|
||||||
onChange={(event) => setSqlPrompt(event.target.value)}
|
|
||||||
placeholder="输入需求,例如:统计过去7天最活跃的10个联系人"
|
|
||||||
/>
|
|
||||||
<textarea
|
|
||||||
className="sql-generated"
|
|
||||||
value={sqlGenerated}
|
|
||||||
onChange={(event) => {
|
|
||||||
setSqlGenerated(event.target.value)
|
|
||||||
sqlGeneratedRef.current = event.target.value
|
|
||||||
}}
|
|
||||||
placeholder="生成的 SQL 将显示在这里"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{sqlError ? <div className="error">{sqlError}</div> : null}
|
|
||||||
|
|
||||||
<div className="sql-table-wrap">
|
|
||||||
{sqlResult?.rows?.length ? (
|
|
||||||
<>
|
|
||||||
<table className="sql-table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
{sqlResult.columns.map((column) => (
|
|
||||||
<th
|
|
||||||
key={column}
|
|
||||||
onClick={() => {
|
|
||||||
if (sqlSortBy === column) {
|
|
||||||
setSqlSortOrder((prev) => prev === 'asc' ? 'desc' : 'asc')
|
|
||||||
} else {
|
|
||||||
setSqlSortBy(column)
|
|
||||||
setSqlSortOrder('asc')
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{column}
|
|
||||||
</th>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{sqlPagedRows.map((row, rowIndex) => (
|
|
||||||
<tr key={`row-${rowIndex}`}>
|
|
||||||
{sqlResult.columns.map((column) => (
|
|
||||||
<td key={`${rowIndex}-${column}`}>{String(row[column] ?? '')}</td>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<div className="pager">
|
|
||||||
<span>共 {sqlResult.total} 行</span>
|
|
||||||
<button type="button" onClick={() => setSqlPage((prev) => Math.max(1, prev - 1))}>上一页</button>
|
|
||||||
<span>{sqlPage}</span>
|
|
||||||
<button type="button" onClick={() => setSqlPage((prev) => prev + 1)}>下一页</button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<div className="empty">暂无执行结果</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="sql-history">
|
|
||||||
<h4>历史 SQL</h4>
|
|
||||||
<div className="history-list">
|
|
||||||
{sqlHistory.map((sql, index) => (
|
|
||||||
<button key={`sql-${index}`} type="button" onClick={() => setSqlGenerated(sql)}>
|
|
||||||
{sql.slice(0, 120)}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{activeTab === 'tool' && (
|
|
||||||
<div className="tool-layout">
|
|
||||||
<aside className="tool-catalog">
|
|
||||||
<h3>工具目录</h3>
|
|
||||||
<h4>Core</h4>
|
|
||||||
<div className="tool-list">
|
|
||||||
{groupedTools.core.map((tool) => (
|
|
||||||
<button key={tool.name} type="button" className={toolName === tool.name ? 'active' : ''} onClick={() => setToolName(tool.name)}>
|
|
||||||
{tool.name}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<h4>Analysis</h4>
|
|
||||||
<div className="tool-list">
|
|
||||||
{groupedTools.analysis.map((tool) => (
|
|
||||||
<button key={tool.name} type="button" className={toolName === tool.name ? 'active' : ''} onClick={() => setToolName(tool.name)}>
|
|
||||||
{tool.name}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
<section className="tool-main">
|
|
||||||
<div className="tool-top">
|
|
||||||
<div>
|
|
||||||
<h3>{toolName || '请选择工具'}</h3>
|
|
||||||
<p>{toolCatalog.find((tool) => tool.name === toolName)?.description || '暂无描述'}</p>
|
|
||||||
</div>
|
|
||||||
<div className="actions">
|
|
||||||
<button type="button" onClick={() => void handleRunTool()} disabled={!toolName || toolRunning}>
|
|
||||||
{toolRunning ? <Loader2 className="spin" size={14} /> : <Wrench size={14} />}
|
|
||||||
执行
|
|
||||||
</button>
|
|
||||||
<button type="button" onClick={() => void aiApi.cancelToolTest({})}>
|
|
||||||
<CircleStop size={14} />
|
|
||||||
取消
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<textarea
|
|
||||||
className="tool-args"
|
|
||||||
value={toolArgsText}
|
|
||||||
onChange={(event) => setToolArgsText(event.target.value)}
|
|
||||||
placeholder='{"keyword":"买车","limit":10}'
|
|
||||||
/>
|
|
||||||
<pre className="tool-output">{toolOutput || '执行结果会显示在这里(超长内容可滚动查看)'}</pre>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{errorText ? <div className="global-error">{errorText}</div> : null}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default AiAnalysisPage
|
|
||||||
@@ -46,12 +46,6 @@ interface PendingInSessionSearchPayload {
|
|||||||
results: Message[]
|
results: Message[]
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PendingFootprintJumpPayload {
|
|
||||||
sessionId: string
|
|
||||||
localId: number
|
|
||||||
createTime: number
|
|
||||||
}
|
|
||||||
|
|
||||||
type GlobalMsgSearchPhase = 'idle' | 'seed' | 'backfill' | 'done'
|
type GlobalMsgSearchPhase = 'idle' | 'seed' | 'backfill' | 'done'
|
||||||
type GlobalMsgSearchResult = Message & { sessionId: string }
|
type GlobalMsgSearchResult = Message & { sessionId: string }
|
||||||
|
|
||||||
@@ -1369,7 +1363,6 @@ function ChatPage(props: ChatPageProps) {
|
|||||||
const [globalMsgAuthoritativeSessionCount, setGlobalMsgAuthoritativeSessionCount] = useState(0)
|
const [globalMsgAuthoritativeSessionCount, setGlobalMsgAuthoritativeSessionCount] = useState(0)
|
||||||
const [globalMsgSearchError, setGlobalMsgSearchError] = useState<string | null>(null)
|
const [globalMsgSearchError, setGlobalMsgSearchError] = useState<string | null>(null)
|
||||||
const pendingInSessionSearchRef = useRef<PendingInSessionSearchPayload | null>(null)
|
const pendingInSessionSearchRef = useRef<PendingInSessionSearchPayload | null>(null)
|
||||||
const pendingFootprintJumpRef = useRef<PendingFootprintJumpPayload | null>(null)
|
|
||||||
const pendingGlobalMsgSearchReplayRef = useRef<string | null>(null)
|
const pendingGlobalMsgSearchReplayRef = useRef<string | null>(null)
|
||||||
const globalMsgPrefixCacheRef = useRef<GlobalMsgPrefixCacheEntry | null>(null)
|
const globalMsgPrefixCacheRef = useRef<GlobalMsgPrefixCacheEntry | null>(null)
|
||||||
|
|
||||||
@@ -5358,89 +5351,18 @@ function ChatPage(props: ChatPageProps) {
|
|||||||
selectSessionById
|
selectSessionById
|
||||||
])
|
])
|
||||||
|
|
||||||
// 监听 URL 参数中的会话/锚点(通知跳转 + 足迹锚点定位)
|
// 监听URL参数中的sessionId,用于通知点击导航
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (standaloneSessionWindow) return // standalone模式由上面的useEffect处理
|
if (standaloneSessionWindow) return // standalone模式由上面的useEffect处理
|
||||||
const params = new URLSearchParams(location.search)
|
const params = new URLSearchParams(location.search)
|
||||||
const urlSessionId = String(params.get('sessionId') || '').trim()
|
const urlSessionId = params.get('sessionId')
|
||||||
if (!urlSessionId) return
|
if (!urlSessionId) return
|
||||||
if (!isConnected || isConnecting) return
|
if (!isConnected || isConnecting) return
|
||||||
const jumpSource = String(params.get('jumpSource') || '').trim()
|
if (currentSessionId === urlSessionId) return
|
||||||
const jumpLocalId = Number.parseInt(String(params.get('jumpLocalId') || ''), 10)
|
selectSessionById(urlSessionId)
|
||||||
const jumpCreateTime = Number.parseInt(String(params.get('jumpCreateTime') || ''), 10)
|
|
||||||
const hasFootprintAnchor = jumpSource === 'footprint'
|
|
||||||
&& Number.isFinite(jumpLocalId)
|
|
||||||
&& jumpLocalId > 0
|
|
||||||
&& Number.isFinite(jumpCreateTime)
|
|
||||||
&& jumpCreateTime > 0
|
|
||||||
|
|
||||||
if (hasFootprintAnchor) {
|
|
||||||
pendingFootprintJumpRef.current = {
|
|
||||||
sessionId: urlSessionId,
|
|
||||||
localId: jumpLocalId,
|
|
||||||
createTime: jumpCreateTime
|
|
||||||
}
|
|
||||||
if (currentSessionId !== urlSessionId) {
|
|
||||||
selectSessionById(urlSessionId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const messageStub: Message = {
|
|
||||||
messageKey: `footprint:${urlSessionId}:${jumpCreateTime}:${jumpLocalId}`,
|
|
||||||
localId: jumpLocalId,
|
|
||||||
serverId: 0,
|
|
||||||
localType: 0,
|
|
||||||
createTime: jumpCreateTime,
|
|
||||||
sortSeq: jumpCreateTime,
|
|
||||||
isSend: null,
|
|
||||||
senderUsername: null,
|
|
||||||
parsedContent: '',
|
|
||||||
rawContent: ''
|
|
||||||
}
|
|
||||||
handleInSessionResultJump(messageStub)
|
|
||||||
pendingFootprintJumpRef.current = null
|
|
||||||
navigate('/chat', { replace: true })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
pendingFootprintJumpRef.current = null
|
|
||||||
if (currentSessionId !== urlSessionId) {
|
|
||||||
selectSessionById(urlSessionId)
|
|
||||||
}
|
|
||||||
// 选中后清除URL参数,避免影响后续用户手动切换会话
|
// 选中后清除URL参数,避免影响后续用户手动切换会话
|
||||||
navigate('/chat', { replace: true })
|
navigate('/chat', { replace: true })
|
||||||
}, [
|
}, [standaloneSessionWindow, location.search, isConnected, isConnecting, currentSessionId, selectSessionById, navigate])
|
||||||
standaloneSessionWindow,
|
|
||||||
location.search,
|
|
||||||
isConnected,
|
|
||||||
isConnecting,
|
|
||||||
currentSessionId,
|
|
||||||
selectSessionById,
|
|
||||||
handleInSessionResultJump,
|
|
||||||
navigate
|
|
||||||
])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const pending = pendingFootprintJumpRef.current
|
|
||||||
if (!pending) return
|
|
||||||
if (!isConnected || isConnecting) return
|
|
||||||
if (currentSessionId !== pending.sessionId) return
|
|
||||||
|
|
||||||
const messageStub: Message = {
|
|
||||||
messageKey: `footprint:${pending.sessionId}:${pending.createTime}:${pending.localId}`,
|
|
||||||
localId: pending.localId,
|
|
||||||
serverId: 0,
|
|
||||||
localType: 0,
|
|
||||||
createTime: pending.createTime,
|
|
||||||
sortSeq: pending.createTime,
|
|
||||||
isSend: null,
|
|
||||||
senderUsername: null,
|
|
||||||
parsedContent: '',
|
|
||||||
rawContent: ''
|
|
||||||
}
|
|
||||||
handleInSessionResultJump(messageStub)
|
|
||||||
pendingFootprintJumpRef.current = null
|
|
||||||
navigate('/chat', { replace: true })
|
|
||||||
}, [isConnected, isConnecting, currentSessionId, handleInSessionResultJump, navigate])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!standaloneSessionWindow || !normalizedInitialSessionId) return
|
if (!standaloneSessionWindow || !normalizedInitialSessionId) return
|
||||||
|
|||||||
@@ -1,825 +0,0 @@
|
|||||||
.my-footprint-page {
|
|
||||||
--timeline-mention: #f59e0b; /* muted orange */
|
|
||||||
--timeline-private: #3b82f6; /* muted blue */
|
|
||||||
|
|
||||||
min-height: 100%;
|
|
||||||
margin: -24px -24px 0;
|
|
||||||
padding: 32px 40px;
|
|
||||||
background: var(--bg-primary); /* Pure minimal background */
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 24px;
|
|
||||||
overflow-y: auto;
|
|
||||||
overflow-x: hidden;
|
|
||||||
animation: footprintPageEnter 0.4s ease-out;
|
|
||||||
|
|
||||||
.card-surface {
|
|
||||||
/* Removing border and strong shadows, just subtle background if any */
|
|
||||||
background: transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
.spin {
|
|
||||||
animation: footprintSpin 1s linear infinite;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-header {
|
|
||||||
position: relative;
|
|
||||||
z-index: 30;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 20px;
|
|
||||||
padding: 10px 0 20px 0;
|
|
||||||
border-bottom: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
|
||||||
animation: footprintFadeSlideUp 0.3s ease both;
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-title-wrap {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 8px;
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 26px;
|
|
||||||
font-weight: 600;
|
|
||||||
line-height: 1.3;
|
|
||||||
letter-spacing: -0.3px;
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
p {
|
|
||||||
margin: 0;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-title-badge {
|
|
||||||
display: none; /* Removed for minimal design */
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-toolbar {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.range-preset-group {
|
|
||||||
display: flex;
|
|
||||||
gap: 4px;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
|
||||||
padding: 4px;
|
|
||||||
border-radius: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.preset-chip {
|
|
||||||
background: transparent;
|
|
||||||
border: none;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 6px 14px;
|
|
||||||
font-size: 13px;
|
|
||||||
font-weight: 500;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
&.active {
|
|
||||||
color: var(--text-primary);
|
|
||||||
background: var(--bg-primary);
|
|
||||||
box-shadow: 0 1px 3px rgba(0,0,0,0.05);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.custom-range-row {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px;
|
|
||||||
|
|
||||||
span {
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
font-size: 13px;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
input[type="date"] {
|
|
||||||
font-family: inherit;
|
|
||||||
border: 1px solid transparent;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 6%, transparent);
|
|
||||||
color: var(--text-primary);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 6px 10px;
|
|
||||||
font-size: 13px;
|
|
||||||
font-weight: 500;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
cursor: pointer;
|
|
||||||
box-shadow: 0 1px 2px rgba(0,0,0,0.02) inset;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 12%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: none;
|
|
||||||
background: color-mix(in srgb, var(--primary) 4%, transparent);
|
|
||||||
border-color: color-mix(in srgb, var(--primary) 30%, transparent);
|
|
||||||
color: var(--primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
&::-webkit-calendar-picker-indicator {
|
|
||||||
cursor: pointer;
|
|
||||||
opacity: 0.5;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
padding: 4px;
|
|
||||||
margin-left: 4px;
|
|
||||||
margin-right: -4px;
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
&::-webkit-calendar-picker-indicator:hover {
|
|
||||||
opacity: 0.9;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 12%, transparent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.toolbar-actions {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-input {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
border: none;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 8px 12px;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
|
|
||||||
&:focus-within {
|
|
||||||
background: color-mix(in srgb, var(--primary) 8%, transparent);
|
|
||||||
color: var(--primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
input {
|
|
||||||
min-width: 180px;
|
|
||||||
border: none;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--text-primary);
|
|
||||||
font-size: 13px;
|
|
||||||
|
|
||||||
&::placeholder {
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
}
|
|
||||||
&:focus {
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.action-btn,
|
|
||||||
.jump-btn {
|
|
||||||
border: none;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
|
||||||
color: var(--text-secondary);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 8px 12px;
|
|
||||||
font-size: 13px;
|
|
||||||
font-weight: 500;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 15%, transparent);
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
&:disabled {
|
|
||||||
opacity: 0.4;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.kpi-grid {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
|
||||||
gap: 20px;
|
|
||||||
padding: 20px 0;
|
|
||||||
border-bottom: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.kpi-card {
|
|
||||||
border: none;
|
|
||||||
background: transparent;
|
|
||||||
padding: 0;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: flex-start;
|
|
||||||
gap: 8px;
|
|
||||||
text-align: left;
|
|
||||||
color: var(--text-primary);
|
|
||||||
animation: footprintKpiIn 0.3s ease both;
|
|
||||||
transition: opacity 0.2s ease;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
opacity: 0.7;
|
|
||||||
}
|
|
||||||
|
|
||||||
strong {
|
|
||||||
font-size: 32px;
|
|
||||||
font-weight: 300;
|
|
||||||
line-height: 1;
|
|
||||||
color: var(--text-primary);
|
|
||||||
letter-spacing: -0.5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
small {
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.kpi-icon {
|
|
||||||
display: none; /* Minimalistic, hide icon in KPI */
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-ai-result {
|
|
||||||
border-radius: 10px;
|
|
||||||
padding: 14px 16px;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
|
||||||
border: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
|
||||||
|
|
||||||
.footprint-ai-head {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 8px;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
|
|
||||||
strong {
|
|
||||||
font-size: 14px;
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
span {
|
|
||||||
font-size: 12px;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
p {
|
|
||||||
margin: 0;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
line-height: 1.6;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
&.footprint-ai-result-error {
|
|
||||||
border-color: color-mix(in srgb, #ef4444 50%, transparent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.kpi-label {
|
|
||||||
font-size: 13px;
|
|
||||||
font-weight: 500;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.kpi-diagnostics {
|
|
||||||
cursor: default;
|
|
||||||
&:hover { opacity: 1; }
|
|
||||||
border-left: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
|
||||||
padding-left: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-timeline {
|
|
||||||
animation: timelineSwitchFade 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
|
|
||||||
--timeline-time-col-width: 64px;
|
|
||||||
--timeline-dot-col-width: 20px;
|
|
||||||
--timeline-gap: 24px;
|
|
||||||
|
|
||||||
flex: 1;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 24px;
|
|
||||||
padding: 10px 0;
|
|
||||||
|
|
||||||
&.timeline-time-month_day_clock {
|
|
||||||
--timeline-time-col-width: 86px;
|
|
||||||
}
|
|
||||||
|
|
||||||
&.timeline-time-full_date_clock {
|
|
||||||
--timeline-time-col-width: 124px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-head {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
margin-bottom: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-head-left h2 {
|
|
||||||
display: none; /* the minimalist approach relies on content, we skip this redundant title */
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-head-left p {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-mode-row {
|
|
||||||
display: flex;
|
|
||||||
gap: 4px;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 6%, transparent);
|
|
||||||
padding: 3px;
|
|
||||||
border-radius: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-mode-chip {
|
|
||||||
border: none;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
font-size: 13px;
|
|
||||||
font-weight: 500;
|
|
||||||
padding: 6px 12px;
|
|
||||||
border-radius: 6px;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
&.active {
|
|
||||||
color: var(--text-primary);
|
|
||||||
background: var(--bg-primary);
|
|
||||||
box-shadow: 0 1px 3px rgba(0,0,0,0.04);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-stream {
|
|
||||||
position: relative;
|
|
||||||
padding-bottom: 40px;
|
|
||||||
|
|
||||||
&::before {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
left: calc(var(--timeline-time-col-width) + var(--timeline-gap) + 9px);
|
|
||||||
top: 0;
|
|
||||||
bottom: 0;
|
|
||||||
width: 2px;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 20%, transparent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-item {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: var(--timeline-time-col-width) var(--timeline-dot-col-width) minmax(0, 1fr);
|
|
||||||
column-gap: var(--timeline-gap);
|
|
||||||
align-items: stretch;
|
|
||||||
margin-bottom: 38px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-time {
|
|
||||||
font-size: 13px;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
text-align: right;
|
|
||||||
padding-top: 5px;
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-time-private {
|
|
||||||
padding-top: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-time-range {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: flex-end;
|
|
||||||
justify-content: space-between;
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-time-main,
|
|
||||||
.timeline-time-end {
|
|
||||||
color: var(--text-secondary);
|
|
||||||
font-weight: 500;
|
|
||||||
line-height: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-time-sep {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-col {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
padding-top: 9px;
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot {
|
|
||||||
width: 8px;
|
|
||||||
height: 8px;
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--text-tertiary);
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-mention {
|
|
||||||
background: var(--timeline-mention);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-private {
|
|
||||||
background: var(--timeline-private);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-private-inbound_only {
|
|
||||||
background: var(--timeline-mention);
|
|
||||||
border: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-private-outbound_only {
|
|
||||||
background: #22c55e;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-private-both {
|
|
||||||
background: var(--timeline-private);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-start,
|
|
||||||
.timeline-dot-end {
|
|
||||||
background: transparent;
|
|
||||||
border: 1.5px solid var(--text-tertiary);
|
|
||||||
width: 10px;
|
|
||||||
height: 10px;
|
|
||||||
margin-top: -1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-range {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
height: 100%;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-range-line {
|
|
||||||
width: 2px;
|
|
||||||
flex: 1;
|
|
||||||
margin: 4px 0;
|
|
||||||
background: color-mix(in srgb, var(--timeline-private) 30%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-range-line-inbound_only {
|
|
||||||
background: color-mix(in srgb, var(--timeline-mention) 55%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-range-line-outbound_only {
|
|
||||||
background: #22c55e;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-dot-range-line-both {
|
|
||||||
background: color-mix(in srgb, var(--timeline-private) 55%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-content-wrap {
|
|
||||||
padding-top: 2px;
|
|
||||||
padding-bottom: 6px;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
justify-content: space-between;
|
|
||||||
min-height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-boundary {
|
|
||||||
font-size: 13px;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
padding: 4px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-card {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 8px;
|
|
||||||
|
|
||||||
/* completely clean out the old card style */
|
|
||||||
border: none;
|
|
||||||
background: transparent;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-card-head {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-identity {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-avatar {
|
|
||||||
width: 28px;
|
|
||||||
height: 28px;
|
|
||||||
border-radius: 50%; /* Modern circle avatars */
|
|
||||||
overflow: hidden;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 10%, transparent);
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
|
|
||||||
img {
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
object-fit: cover;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-avatar-private {
|
|
||||||
color: var(--timeline-private);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-title-group {
|
|
||||||
display: flex;
|
|
||||||
align-items: baseline;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-title {
|
|
||||||
font-size: 14px;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-subtitle {
|
|
||||||
font-size: 13px;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-right-tools {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-count-badge {
|
|
||||||
font-size: 12px;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-jump-btn {
|
|
||||||
padding: 4px 10px;
|
|
||||||
font-size: 12px;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 10%, transparent);
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-message {
|
|
||||||
font-size: 13px;
|
|
||||||
line-height: 1.5;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
padding: 0;
|
|
||||||
margin-top: 4px;
|
|
||||||
background: transparent;
|
|
||||||
border-radius: 0;
|
|
||||||
word-break: break-word;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mention-message {
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.private-message {
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes timelineSwitchFade {
|
|
||||||
from {
|
|
||||||
opacity: 0;
|
|
||||||
transform: translateY(12px);
|
|
||||||
}
|
|
||||||
to {
|
|
||||||
opacity: 1;
|
|
||||||
transform: translateY(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
.mention-token {
|
|
||||||
color: var(--timeline-mention);
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.panel-empty-state {
|
|
||||||
text-align: center;
|
|
||||||
padding: 60px 0;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-loading {
|
|
||||||
padding: 40px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.kpi-skeleton-grid {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
|
||||||
gap: 20px;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.kpi-skeleton-card {
|
|
||||||
height: 60px;
|
|
||||||
border-radius: 8px;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 6%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-skeleton-list {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.timeline-skeleton-item {
|
|
||||||
height: 80px;
|
|
||||||
border-radius: 8px;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 6%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-export-modal-mask {
|
|
||||||
position: fixed;
|
|
||||||
inset: 0;
|
|
||||||
z-index: 1200;
|
|
||||||
background: color-mix(in srgb, #000 36%, transparent);
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
padding: 24px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.footprint-export-modal {
|
|
||||||
width: min(520px, 100%);
|
|
||||||
border-radius: 16px;
|
|
||||||
background: var(--bg-primary);
|
|
||||||
border: 1px solid color-mix(in srgb, var(--border-color) 60%, transparent);
|
|
||||||
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.2);
|
|
||||||
padding: 22px 22px 18px;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 10px;
|
|
||||||
animation: footprintFadeSlideUp 0.2s ease both;
|
|
||||||
|
|
||||||
h3 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 18px;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
p {
|
|
||||||
margin: 0;
|
|
||||||
color: var(--text-secondary);
|
|
||||||
font-size: 14px;
|
|
||||||
line-height: 1.5;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-modal-icon {
|
|
||||||
width: 34px;
|
|
||||||
height: 34px;
|
|
||||||
border-radius: 10px;
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-modal-icon-progress {
|
|
||||||
color: var(--primary);
|
|
||||||
background: color-mix(in srgb, var(--primary) 16%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-modal-icon-success {
|
|
||||||
color: #16a34a;
|
|
||||||
background: color-mix(in srgb, #16a34a 18%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-modal-icon-error {
|
|
||||||
color: #ef4444;
|
|
||||||
background: color-mix(in srgb, #ef4444 18%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-modal-path {
|
|
||||||
display: block;
|
|
||||||
margin-top: 2px;
|
|
||||||
padding: 10px 12px;
|
|
||||||
border-radius: 10px;
|
|
||||||
font-family: inherit;
|
|
||||||
font-weight: 500;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.4;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
|
||||||
border: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
|
||||||
white-space: pre-wrap;
|
|
||||||
word-break: break-all;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-modal-actions {
|
|
||||||
display: flex;
|
|
||||||
justify-content: flex-end;
|
|
||||||
margin-top: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.skeleton-shimmer {
|
|
||||||
position: relative;
|
|
||||||
overflow: hidden;
|
|
||||||
|
|
||||||
&::after {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
inset: 0;
|
|
||||||
background: linear-gradient(
|
|
||||||
90deg,
|
|
||||||
transparent,
|
|
||||||
color-mix(in srgb, var(--bg-primary) 50%, transparent),
|
|
||||||
transparent
|
|
||||||
);
|
|
||||||
transform: translateX(-100%);
|
|
||||||
animation: footprintShimmer 1.5s infinite;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Animations */
|
|
||||||
@keyframes footprintPageEnter {
|
|
||||||
from { opacity: 0; transform: translateY(10px); }
|
|
||||||
to { opacity: 1; transform: translateY(0); }
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes footprintFadeSlideUp {
|
|
||||||
from { opacity: 0; transform: translateY(5px); }
|
|
||||||
to { opacity: 1; transform: translateY(0); }
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes footprintKpiIn {
|
|
||||||
from { opacity: 0; transform: translateY(8px); }
|
|
||||||
to { opacity: 1; transform: translateY(0); }
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes footprintTimelineItemIn {
|
|
||||||
from { opacity: 0; transform: translateY(10px); }
|
|
||||||
to { opacity: 1; transform: translateY(0); }
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes footprintSpin {
|
|
||||||
100% { transform: rotate(360deg); }
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes footprintShimmer {
|
|
||||||
100% { transform: translateX(100%); }
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 1100px) {
|
|
||||||
.kpi-grid,
|
|
||||||
.kpi-skeleton-grid {
|
|
||||||
grid-template-columns: repeat(3, 1fr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 800px) {
|
|
||||||
.my-footprint-page {
|
|
||||||
padding: 20px;
|
|
||||||
}
|
|
||||||
.kpi-grid,
|
|
||||||
.kpi-skeleton-grid {
|
|
||||||
grid-template-columns: repeat(2, 1fr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,983 +0,0 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
|
||||||
import { useNavigate } from 'react-router-dom'
|
|
||||||
import { AlertCircle, AtSign, CheckCircle2, Download, Loader2, MessageCircle, RefreshCw, Search, Sparkles, Users } from 'lucide-react'
|
|
||||||
import DateRangePicker from '../components/DateRangePicker'
|
|
||||||
import './MyFootprintPage.scss'
|
|
||||||
|
|
||||||
type RangePreset = 'today' | 'yesterday' | 'this_week' | 'last_week' | 'custom'
|
|
||||||
type TimelineMode = 'all' | 'mention' | 'private'
|
|
||||||
type TimelineTimeMode = 'clock' | 'month_day_clock' | 'full_date_clock'
|
|
||||||
type PrivateDotVariant = 'both' | 'inbound_only' | 'outbound_only'
|
|
||||||
type ExportModalStatus = 'idle' | 'progress' | 'success' | 'error'
|
|
||||||
type FootprintAiStatus = 'idle' | 'loading' | 'success' | 'error'
|
|
||||||
|
|
||||||
interface MyFootprintSummary {
|
|
||||||
private_inbound_people: number
|
|
||||||
private_replied_people: number
|
|
||||||
private_outbound_people: number
|
|
||||||
private_reply_rate: number
|
|
||||||
mention_count: number
|
|
||||||
mention_group_count: number
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MyFootprintPrivateSession {
|
|
||||||
session_id: string
|
|
||||||
incoming_count: number
|
|
||||||
outgoing_count: number
|
|
||||||
replied: boolean
|
|
||||||
first_incoming_ts: number
|
|
||||||
first_reply_ts: number
|
|
||||||
latest_ts: number
|
|
||||||
anchor_local_id: number
|
|
||||||
anchor_create_time: number
|
|
||||||
displayName?: string
|
|
||||||
avatarUrl?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MyFootprintPrivateSegment {
|
|
||||||
session_id: string
|
|
||||||
segment_index: number
|
|
||||||
start_ts: number
|
|
||||||
end_ts: number
|
|
||||||
duration_sec: number
|
|
||||||
incoming_count: number
|
|
||||||
outgoing_count: number
|
|
||||||
message_count: number
|
|
||||||
replied: boolean
|
|
||||||
first_incoming_ts: number
|
|
||||||
first_reply_ts: number
|
|
||||||
latest_ts: number
|
|
||||||
anchor_local_id: number
|
|
||||||
anchor_create_time: number
|
|
||||||
displayName?: string
|
|
||||||
avatarUrl?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MyFootprintMention {
|
|
||||||
session_id: string
|
|
||||||
local_id: number
|
|
||||||
create_time: number
|
|
||||||
sender_username: string
|
|
||||||
message_content: string
|
|
||||||
source: string
|
|
||||||
sessionDisplayName?: string
|
|
||||||
senderDisplayName?: string
|
|
||||||
senderAvatarUrl?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MyFootprintMentionGroup {
|
|
||||||
session_id: string
|
|
||||||
count: number
|
|
||||||
latest_ts: number
|
|
||||||
displayName?: string
|
|
||||||
avatarUrl?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MyFootprintDiagnostics {
|
|
||||||
truncated: boolean
|
|
||||||
scanned_dbs: number
|
|
||||||
elapsed_ms: number
|
|
||||||
mention_truncated?: boolean
|
|
||||||
private_truncated?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MyFootprintData {
|
|
||||||
summary: MyFootprintSummary
|
|
||||||
private_sessions: MyFootprintPrivateSession[]
|
|
||||||
private_segments: MyFootprintPrivateSegment[]
|
|
||||||
mentions: MyFootprintMention[]
|
|
||||||
mention_groups: MyFootprintMentionGroup[]
|
|
||||||
diagnostics: MyFootprintDiagnostics
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TimelineBoundaryItem {
|
|
||||||
kind: 'boundary'
|
|
||||||
edge: 'start' | 'end'
|
|
||||||
key: string
|
|
||||||
time: number
|
|
||||||
label: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TimelineMentionItem {
|
|
||||||
kind: 'mention'
|
|
||||||
key: string
|
|
||||||
time: number
|
|
||||||
sessionId: string
|
|
||||||
localId: number
|
|
||||||
createTime: number
|
|
||||||
groupName: string
|
|
||||||
groupAvatarUrl?: string
|
|
||||||
senderName: string
|
|
||||||
messageContent: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TimelinePrivateItem {
|
|
||||||
kind: 'private'
|
|
||||||
key: string
|
|
||||||
time: number
|
|
||||||
endTime: number
|
|
||||||
sessionId: string
|
|
||||||
anchorLocalId: number
|
|
||||||
anchorCreateTime: number
|
|
||||||
displayName: string
|
|
||||||
avatarUrl?: string
|
|
||||||
subtitle: string
|
|
||||||
totalInteractions: number
|
|
||||||
summaryText: string
|
|
||||||
dotVariant: PrivateDotVariant
|
|
||||||
isRange: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
type TimelineItem = TimelineBoundaryItem | TimelineMentionItem | TimelinePrivateItem
|
|
||||||
|
|
||||||
const EMPTY_DATA: MyFootprintData = {
|
|
||||||
summary: {
|
|
||||||
private_inbound_people: 0,
|
|
||||||
private_replied_people: 0,
|
|
||||||
private_outbound_people: 0,
|
|
||||||
private_reply_rate: 0,
|
|
||||||
mention_count: 0,
|
|
||||||
mention_group_count: 0
|
|
||||||
},
|
|
||||||
private_sessions: [],
|
|
||||||
private_segments: [],
|
|
||||||
mentions: [],
|
|
||||||
mention_groups: [],
|
|
||||||
diagnostics: {
|
|
||||||
truncated: false,
|
|
||||||
scanned_dbs: 0,
|
|
||||||
elapsed_ms: 0,
|
|
||||||
mention_truncated: false,
|
|
||||||
private_truncated: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toDayStart(date: Date): Date {
|
|
||||||
const next = new Date(date)
|
|
||||||
next.setHours(0, 0, 0, 0)
|
|
||||||
return next
|
|
||||||
}
|
|
||||||
|
|
||||||
function toDayEnd(date: Date): Date {
|
|
||||||
const next = new Date(date)
|
|
||||||
next.setHours(23, 59, 59, 999)
|
|
||||||
return next
|
|
||||||
}
|
|
||||||
|
|
||||||
function toSeconds(date: Date): number {
|
|
||||||
return Math.floor(date.getTime() / 1000)
|
|
||||||
}
|
|
||||||
|
|
||||||
function toDateInputValue(date: Date): string {
|
|
||||||
const y = date.getFullYear()
|
|
||||||
const m = `${date.getMonth() + 1}`.padStart(2, '0')
|
|
||||||
const d = `${date.getDate()}`.padStart(2, '0')
|
|
||||||
return `${y}-${m}-${d}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function getWeekStart(date: Date): Date {
|
|
||||||
const base = toDayStart(date)
|
|
||||||
const day = base.getDay()
|
|
||||||
const diff = day === 0 ? -6 : 1 - day
|
|
||||||
base.setDate(base.getDate() + diff)
|
|
||||||
return base
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatTimelineMoment(seconds: number, mode: TimelineTimeMode): string {
|
|
||||||
if (!seconds || !Number.isFinite(seconds)) return '--'
|
|
||||||
const date = new Date(seconds * 1000)
|
|
||||||
const yyyy = `${date.getFullYear()}`
|
|
||||||
const mm = `${date.getMonth() + 1}`.padStart(2, '0')
|
|
||||||
const dd = `${date.getDate()}`.padStart(2, '0')
|
|
||||||
const hh = `${date.getHours()}`.padStart(2, '0')
|
|
||||||
const min = `${date.getMinutes()}`.padStart(2, '0')
|
|
||||||
if (mode === 'full_date_clock') {
|
|
||||||
return `${yyyy}-${mm}-${dd} ${hh}:${min}`
|
|
||||||
}
|
|
||||||
if (mode === 'month_day_clock') {
|
|
||||||
return `${mm}-${dd} ${hh}:${min}`
|
|
||||||
}
|
|
||||||
return `${hh}:${min}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatPercent(value: number): string {
|
|
||||||
const safe = Number.isFinite(value) ? value : 0
|
|
||||||
return `${(safe * 100).toFixed(1)}%`
|
|
||||||
}
|
|
||||||
|
|
||||||
function decodeHtmlEntities(content: string): string {
|
|
||||||
return String(content || '')
|
|
||||||
.replace(/&/g, '&')
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
.replace(/"/g, '"')
|
|
||||||
.replace(/'/g, "'")
|
|
||||||
}
|
|
||||||
|
|
||||||
function stripGroupSenderPrefix(content: string): string {
|
|
||||||
return String(content || '')
|
|
||||||
.replace(/^[\s]*([a-zA-Z0-9_@-]+):(?!\/\/)(?:\s*(?:\r?\n|<br\s*\/?>)\s*|\s*)/i, '')
|
|
||||||
.replace(/^[a-zA-Z0-9]+@openim:\n?/i, '')
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeFootprintMessageContent(content: string): string {
|
|
||||||
const decoded = decodeHtmlEntities(content || '')
|
|
||||||
const stripped = stripGroupSenderPrefix(decoded)
|
|
||||||
return stripped.trim()
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderMentionContent(content: string): ReactNode {
|
|
||||||
const normalized = String(content || '').trim() || '[空消息]'
|
|
||||||
const parts = normalized.split(/(@我|@我)/g)
|
|
||||||
if (parts.length <= 1) return normalized
|
|
||||||
return parts.map((part, index) => {
|
|
||||||
if (part === '@我' || part === '@我') {
|
|
||||||
return (
|
|
||||||
<span key={index} className="mention-token">
|
|
||||||
{part}
|
|
||||||
</span>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return <span key={index}>{part}</span>
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDurationLabel(beginTimestamp: number, endTimestamp: number): string {
|
|
||||||
if (!beginTimestamp || !endTimestamp || endTimestamp <= beginTimestamp) {
|
|
||||||
return '持续不足 1 分钟'
|
|
||||||
}
|
|
||||||
const minutes = Math.max(1, Math.round((endTimestamp - beginTimestamp) / 60))
|
|
||||||
return `持续 ${minutes} 分钟`
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveRangePresetLabel(preset: RangePreset): string {
|
|
||||||
switch (preset) {
|
|
||||||
case 'today':
|
|
||||||
return '今天'
|
|
||||||
case 'yesterday':
|
|
||||||
return '昨天'
|
|
||||||
case 'this_week':
|
|
||||||
return '本周'
|
|
||||||
case 'last_week':
|
|
||||||
return '上周'
|
|
||||||
default:
|
|
||||||
return '自定义'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildRange(preset: RangePreset, customStart: string, customEnd: string): { begin: number; end: number; label: string } {
|
|
||||||
const now = new Date()
|
|
||||||
|
|
||||||
if (preset === 'today') {
|
|
||||||
return {
|
|
||||||
begin: toSeconds(toDayStart(now)),
|
|
||||||
end: toSeconds(now),
|
|
||||||
label: '今天'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preset === 'yesterday') {
|
|
||||||
const yesterday = new Date(now)
|
|
||||||
yesterday.setDate(yesterday.getDate() - 1)
|
|
||||||
return {
|
|
||||||
begin: toSeconds(toDayStart(yesterday)),
|
|
||||||
end: toSeconds(toDayEnd(yesterday)),
|
|
||||||
label: '昨天'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preset === 'this_week') {
|
|
||||||
const weekStart = getWeekStart(now)
|
|
||||||
const weekEnd = new Date(weekStart)
|
|
||||||
weekEnd.setDate(weekStart.getDate() + 6)
|
|
||||||
return {
|
|
||||||
begin: toSeconds(toDayStart(weekStart)),
|
|
||||||
end: toSeconds(toDayEnd(weekEnd)),
|
|
||||||
label: '本周'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preset === 'last_week') {
|
|
||||||
const thisWeekStart = getWeekStart(now)
|
|
||||||
const lastWeekStart = new Date(thisWeekStart)
|
|
||||||
lastWeekStart.setDate(lastWeekStart.getDate() - 7)
|
|
||||||
const lastWeekEnd = new Date(thisWeekStart)
|
|
||||||
lastWeekEnd.setDate(lastWeekEnd.getDate() - 1)
|
|
||||||
return {
|
|
||||||
begin: toSeconds(toDayStart(lastWeekStart)),
|
|
||||||
end: toSeconds(toDayEnd(lastWeekEnd)),
|
|
||||||
label: '上周'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const customStartDate = customStart ? new Date(`${customStart}T00:00:00`) : toDayStart(now)
|
|
||||||
const customEndDate = customEnd ? new Date(`${customEnd}T23:59:59`) : toDayEnd(now)
|
|
||||||
const begin = toSeconds(customStartDate)
|
|
||||||
const end = Math.max(begin, toSeconds(customEndDate))
|
|
||||||
|
|
||||||
return {
|
|
||||||
begin,
|
|
||||||
end,
|
|
||||||
label: `${toDateInputValue(customStartDate)} 至 ${toDateInputValue(customEndDate)}`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function MyFootprintPage() {
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const [preset, setPreset] = useState<RangePreset>('today')
|
|
||||||
const [customStartDate, setCustomStartDate] = useState(() => toDateInputValue(toDayStart(new Date())))
|
|
||||||
const [customEndDate, setCustomEndDate] = useState(() => toDateInputValue(toDayStart(new Date())))
|
|
||||||
const [searchKeyword, setSearchKeyword] = useState('')
|
|
||||||
const [timelineMode, setTimelineMode] = useState<TimelineMode>('all')
|
|
||||||
const [data, setData] = useState<MyFootprintData>(EMPTY_DATA)
|
|
||||||
const [loading, setLoading] = useState(false)
|
|
||||||
const [exporting, setExporting] = useState(false)
|
|
||||||
const [exportModalStatus, setExportModalStatus] = useState<ExportModalStatus>('idle')
|
|
||||||
const [exportModalTitle, setExportModalTitle] = useState('')
|
|
||||||
const [exportModalDescription, setExportModalDescription] = useState('')
|
|
||||||
const [exportModalPath, setExportModalPath] = useState('')
|
|
||||||
const [error, setError] = useState<string | null>(null)
|
|
||||||
const [footprintAiStatus, setFootprintAiStatus] = useState<FootprintAiStatus>('idle')
|
|
||||||
const [footprintAiText, setFootprintAiText] = useState('')
|
|
||||||
const inflightRangeKeyRef = useRef<string | null>(null)
|
|
||||||
|
|
||||||
const currentRange = useMemo(() => buildRange(preset, customStartDate, customEndDate), [preset, customStartDate, customEndDate])
|
|
||||||
const timelineTimeMode = useMemo<TimelineTimeMode>(() => {
|
|
||||||
const span = Math.max(0, currentRange.end - currentRange.begin)
|
|
||||||
if (span > 365 * 24 * 60 * 60) return 'full_date_clock'
|
|
||||||
if (span > 24 * 60 * 60) return 'month_day_clock'
|
|
||||||
return 'clock'
|
|
||||||
}, [currentRange.begin, currentRange.end])
|
|
||||||
|
|
||||||
const handleJump = useCallback((sessionId: string, localId: number, createTime: number) => {
|
|
||||||
if (!sessionId || !localId || !createTime) return
|
|
||||||
const query = new URLSearchParams({
|
|
||||||
sessionId,
|
|
||||||
jumpLocalId: String(localId),
|
|
||||||
jumpCreateTime: String(createTime),
|
|
||||||
jumpSource: 'footprint'
|
|
||||||
})
|
|
||||||
navigate(`/chat?${query.toString()}`)
|
|
||||||
}, [navigate])
|
|
||||||
|
|
||||||
const loadData = useCallback(async () => {
|
|
||||||
const rangeKey = `${currentRange.begin}-${currentRange.end}`
|
|
||||||
if (inflightRangeKeyRef.current === rangeKey) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
inflightRangeKeyRef.current = rangeKey
|
|
||||||
setLoading(true)
|
|
||||||
setError(null)
|
|
||||||
try {
|
|
||||||
const result = await window.electronAPI.chat.getMyFootprintStats(currentRange.begin, currentRange.end)
|
|
||||||
if (!result.success || !result.data) {
|
|
||||||
setError(result.error || '读取统计失败')
|
|
||||||
setData(EMPTY_DATA)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setData({
|
|
||||||
...result.data,
|
|
||||||
private_segments: Array.isArray(result.data.private_segments) ? result.data.private_segments : []
|
|
||||||
})
|
|
||||||
} catch (loadError) {
|
|
||||||
setError(String(loadError))
|
|
||||||
setData(EMPTY_DATA)
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
if (inflightRangeKeyRef.current === rangeKey) {
|
|
||||||
inflightRangeKeyRef.current = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [currentRange.begin, currentRange.end])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
void loadData()
|
|
||||||
}, [loadData])
|
|
||||||
|
|
||||||
const keyword = searchKeyword.trim().toLowerCase()
|
|
||||||
|
|
||||||
const privateSessionMetaMap = useMemo(() => {
|
|
||||||
const map = new Map<string, { displayName?: string; avatarUrl?: string }>()
|
|
||||||
for (const item of data.private_sessions) {
|
|
||||||
map.set(item.session_id, {
|
|
||||||
displayName: item.displayName,
|
|
||||||
avatarUrl: item.avatarUrl
|
|
||||||
})
|
|
||||||
}
|
|
||||||
for (const item of data.private_segments) {
|
|
||||||
if (!map.has(item.session_id)) {
|
|
||||||
map.set(item.session_id, {
|
|
||||||
displayName: item.displayName,
|
|
||||||
avatarUrl: item.avatarUrl
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return map
|
|
||||||
}, [data.private_sessions, data.private_segments])
|
|
||||||
|
|
||||||
const filteredMentions = useMemo(() => {
|
|
||||||
if (!keyword) return data.mentions
|
|
||||||
return data.mentions.filter((item) => {
|
|
||||||
const sessionName = (item.sessionDisplayName || '').toLowerCase()
|
|
||||||
const senderName = (item.senderDisplayName || '').toLowerCase()
|
|
||||||
const sender = item.sender_username.toLowerCase()
|
|
||||||
const content = normalizeFootprintMessageContent(item.message_content).toLowerCase()
|
|
||||||
return sessionName.includes(keyword) || senderName.includes(keyword) || sender.includes(keyword) || content.includes(keyword)
|
|
||||||
})
|
|
||||||
}, [data.mentions, keyword])
|
|
||||||
|
|
||||||
const filteredPrivateSegments = useMemo(() => {
|
|
||||||
const rawSegments = data.private_segments.length > 0
|
|
||||||
? data.private_segments
|
|
||||||
: data.private_sessions.map((item, index) => ({
|
|
||||||
session_id: item.session_id,
|
|
||||||
segment_index: index + 1,
|
|
||||||
start_ts: item.first_incoming_ts > 0
|
|
||||||
? item.first_incoming_ts
|
|
||||||
: item.first_reply_ts > 0
|
|
||||||
? item.first_reply_ts
|
|
||||||
: item.latest_ts,
|
|
||||||
end_ts: item.latest_ts,
|
|
||||||
duration_sec: Math.max(0, item.latest_ts - (item.first_incoming_ts || item.first_reply_ts || item.latest_ts)),
|
|
||||||
incoming_count: item.incoming_count,
|
|
||||||
outgoing_count: item.outgoing_count,
|
|
||||||
message_count: Math.max(0, item.incoming_count + item.outgoing_count),
|
|
||||||
replied: item.replied,
|
|
||||||
first_incoming_ts: item.first_incoming_ts,
|
|
||||||
first_reply_ts: item.first_reply_ts,
|
|
||||||
latest_ts: item.latest_ts,
|
|
||||||
anchor_local_id: item.anchor_local_id,
|
|
||||||
anchor_create_time: item.anchor_create_time,
|
|
||||||
displayName: item.displayName,
|
|
||||||
avatarUrl: item.avatarUrl
|
|
||||||
}))
|
|
||||||
|
|
||||||
if (!keyword) return rawSegments
|
|
||||||
return rawSegments.filter((item) => {
|
|
||||||
const meta = privateSessionMetaMap.get(item.session_id)
|
|
||||||
const name = String(item.displayName || meta?.displayName || '').toLowerCase()
|
|
||||||
const id = item.session_id.toLowerCase()
|
|
||||||
return name.includes(keyword) || id.includes(keyword)
|
|
||||||
})
|
|
||||||
}, [data.private_segments, data.private_sessions, keyword, privateSessionMetaMap])
|
|
||||||
|
|
||||||
const mentionGroupMetaMap = useMemo(() => {
|
|
||||||
const map = new Map<string, { displayName?: string; avatarUrl?: string }>()
|
|
||||||
for (const item of data.mention_groups) {
|
|
||||||
map.set(item.session_id, { displayName: item.displayName, avatarUrl: item.avatarUrl })
|
|
||||||
}
|
|
||||||
for (const item of data.private_sessions) {
|
|
||||||
if (!map.has(item.session_id)) {
|
|
||||||
map.set(item.session_id, { displayName: item.displayName, avatarUrl: item.avatarUrl })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return map
|
|
||||||
}, [data.mention_groups, data.private_sessions])
|
|
||||||
|
|
||||||
const mentionTimelineItems = useMemo<TimelineMentionItem[]>(() => {
|
|
||||||
return filteredMentions
|
|
||||||
.filter((item) => item.create_time > 0)
|
|
||||||
.map((item) => {
|
|
||||||
const groupMeta = mentionGroupMetaMap.get(item.session_id)
|
|
||||||
return {
|
|
||||||
kind: 'mention' as const,
|
|
||||||
key: `mention:${item.session_id}:${item.local_id}`,
|
|
||||||
time: item.create_time,
|
|
||||||
sessionId: item.session_id,
|
|
||||||
localId: item.local_id,
|
|
||||||
createTime: item.create_time,
|
|
||||||
groupName: item.sessionDisplayName || groupMeta?.displayName || item.session_id,
|
|
||||||
groupAvatarUrl: groupMeta?.avatarUrl,
|
|
||||||
senderName: item.senderDisplayName || item.sender_username || '未知',
|
|
||||||
messageContent: normalizeFootprintMessageContent(item.message_content)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}, [filteredMentions, mentionGroupMetaMap])
|
|
||||||
|
|
||||||
const privateTimelineItems = useMemo<TimelinePrivateItem[]>(() => {
|
|
||||||
return filteredPrivateSegments
|
|
||||||
.map((item) => {
|
|
||||||
const startTime = item.start_ts > 0
|
|
||||||
? item.start_ts
|
|
||||||
: item.first_incoming_ts > 0
|
|
||||||
? item.first_incoming_ts
|
|
||||||
: item.first_reply_ts > 0
|
|
||||||
? item.first_reply_ts
|
|
||||||
: item.latest_ts
|
|
||||||
|
|
||||||
const endTime = item.end_ts > 0 ? item.end_ts : item.latest_ts
|
|
||||||
const isRange = endTime > startTime + 60
|
|
||||||
const totalInteractions = Math.max(0, item.message_count || (item.incoming_count + item.outgoing_count))
|
|
||||||
const durationLabel = item.duration_sec > 0
|
|
||||||
? `持续 ${Math.max(1, Math.round(item.duration_sec / 60))} 分钟`
|
|
||||||
: formatDurationLabel(startTime, endTime)
|
|
||||||
const subtitle = isRange
|
|
||||||
? `${formatTimelineMoment(startTime, timelineTimeMode)} 至 ${formatTimelineMoment(endTime || startTime, timelineTimeMode)} · ${durationLabel}`
|
|
||||||
: ''
|
|
||||||
const summaryText = `收到 ${item.incoming_count} 条 / 发送 ${item.outgoing_count} 条${item.replied ? ' · 已回复' : ''}`
|
|
||||||
const sessionMeta = privateSessionMetaMap.get(item.session_id)
|
|
||||||
let dotVariant: PrivateDotVariant = 'both'
|
|
||||||
if (item.incoming_count > 0 && item.outgoing_count === 0) {
|
|
||||||
dotVariant = 'inbound_only'
|
|
||||||
} else if (item.incoming_count === 0 && item.outgoing_count > 0) {
|
|
||||||
dotVariant = 'outbound_only'
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
kind: 'private' as const,
|
|
||||||
key: `private:${item.session_id}:${item.segment_index}:${item.start_ts}`,
|
|
||||||
time: startTime,
|
|
||||||
endTime,
|
|
||||||
sessionId: item.session_id,
|
|
||||||
anchorLocalId: item.anchor_local_id,
|
|
||||||
anchorCreateTime: item.anchor_create_time,
|
|
||||||
displayName: item.displayName || sessionMeta?.displayName || item.session_id,
|
|
||||||
avatarUrl: item.avatarUrl || sessionMeta?.avatarUrl,
|
|
||||||
subtitle,
|
|
||||||
totalInteractions,
|
|
||||||
summaryText,
|
|
||||||
dotVariant,
|
|
||||||
isRange
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.filter((item) => item.time > 0)
|
|
||||||
}, [filteredPrivateSegments, privateSessionMetaMap, timelineTimeMode])
|
|
||||||
|
|
||||||
const timelineItems = useMemo<TimelineItem[]>(() => {
|
|
||||||
const events: TimelineItem[] = []
|
|
||||||
if (timelineMode !== 'private') {
|
|
||||||
events.push(...mentionTimelineItems)
|
|
||||||
}
|
|
||||||
if (timelineMode !== 'mention') {
|
|
||||||
events.push(...privateTimelineItems)
|
|
||||||
}
|
|
||||||
|
|
||||||
events.sort((a, b) => {
|
|
||||||
if (a.time !== b.time) return a.time - b.time
|
|
||||||
const rankA = a.kind === 'mention' ? 0 : a.kind === 'private' ? 1 : 2
|
|
||||||
const rankB = b.kind === 'mention' ? 0 : b.kind === 'private' ? 1 : 2
|
|
||||||
return rankA - rankB
|
|
||||||
})
|
|
||||||
|
|
||||||
const presetLabel = resolveRangePresetLabel(preset)
|
|
||||||
const startNode: TimelineBoundaryItem = {
|
|
||||||
kind: 'boundary',
|
|
||||||
edge: 'start',
|
|
||||||
key: 'boundary:start',
|
|
||||||
time: currentRange.begin,
|
|
||||||
label: `区域时间开始(${presetLabel})`
|
|
||||||
}
|
|
||||||
|
|
||||||
const endNode: TimelineBoundaryItem = {
|
|
||||||
kind: 'boundary',
|
|
||||||
edge: 'end',
|
|
||||||
key: 'boundary:end',
|
|
||||||
time: currentRange.end,
|
|
||||||
label: `区域时间结束(${preset === 'today' ? '现在' : presetLabel})`
|
|
||||||
}
|
|
||||||
|
|
||||||
return [startNode, ...events, endNode]
|
|
||||||
}, [timelineMode, mentionTimelineItems, privateTimelineItems, currentRange.begin, currentRange.end, preset])
|
|
||||||
|
|
||||||
const timelineEventCount = useMemo(
|
|
||||||
() => timelineItems.filter((item) => item.kind !== 'boundary').length,
|
|
||||||
[timelineItems]
|
|
||||||
)
|
|
||||||
|
|
||||||
const handleExport = useCallback(async (format: 'csv' | 'json') => {
|
|
||||||
try {
|
|
||||||
setExporting(true)
|
|
||||||
setExportModalStatus('progress')
|
|
||||||
setExportModalTitle(`正在准备导出 ${format.toUpperCase()}`)
|
|
||||||
setExportModalDescription('正在准备文件保存信息...')
|
|
||||||
setExportModalPath('')
|
|
||||||
const downloadsPath = await window.electronAPI.app.getDownloadsPath()
|
|
||||||
const separator = downloadsPath && downloadsPath.includes('\\') ? '\\' : '/'
|
|
||||||
const rangeName = currentRange.label.replace(/[\\/:*?"<>|\s]+/g, '_')
|
|
||||||
const suggestedName = `my_footprint_${rangeName}_${Date.now()}.${format}`
|
|
||||||
const defaultPath = downloadsPath ? `${downloadsPath}${separator}${suggestedName}` : suggestedName
|
|
||||||
|
|
||||||
setExportModalDescription('请在弹窗中选择导出路径...')
|
|
||||||
const saveResult = await window.electronAPI.dialog.saveFile({
|
|
||||||
title: format === 'csv' ? '导出我的足迹 CSV' : '导出我的足迹 JSON',
|
|
||||||
defaultPath,
|
|
||||||
filters: format === 'csv'
|
|
||||||
? [{ name: 'CSV', extensions: ['csv'] }]
|
|
||||||
: [{ name: 'JSON', extensions: ['json'] }]
|
|
||||||
})
|
|
||||||
if (saveResult.canceled || !saveResult.filePath) {
|
|
||||||
setExportModalStatus('idle')
|
|
||||||
setExportModalTitle('')
|
|
||||||
setExportModalDescription('')
|
|
||||||
setExportModalPath('')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setExportModalDescription('正在导出数据,请稍候...')
|
|
||||||
setExportModalPath(saveResult.filePath)
|
|
||||||
const exportResult = await window.electronAPI.chat.exportMyFootprint(
|
|
||||||
currentRange.begin,
|
|
||||||
currentRange.end,
|
|
||||||
format,
|
|
||||||
saveResult.filePath
|
|
||||||
)
|
|
||||||
if (!exportResult.success) {
|
|
||||||
setExportModalStatus('error')
|
|
||||||
setExportModalTitle('导出失败')
|
|
||||||
setExportModalDescription(exportResult.error || '未知错误')
|
|
||||||
setExportModalPath(saveResult.filePath)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setExportModalStatus('success')
|
|
||||||
setExportModalTitle('导出完成')
|
|
||||||
setExportModalDescription(`文件已成功导出为 ${format.toUpperCase()}。`)
|
|
||||||
setExportModalPath(exportResult.filePath || saveResult.filePath)
|
|
||||||
} catch (exportError) {
|
|
||||||
setExportModalStatus('error')
|
|
||||||
setExportModalTitle('导出失败')
|
|
||||||
setExportModalDescription(String(exportError))
|
|
||||||
} finally {
|
|
||||||
setExporting(false)
|
|
||||||
}
|
|
||||||
}, [currentRange.begin, currentRange.end, currentRange.label])
|
|
||||||
|
|
||||||
const handleGenerateAiSummary = useCallback(async () => {
|
|
||||||
setFootprintAiStatus('loading')
|
|
||||||
setFootprintAiText('')
|
|
||||||
try {
|
|
||||||
const privateSegments = (data.private_segments.length > 0 ? data.private_segments : data.private_sessions).slice(0, 12)
|
|
||||||
const result = await window.electronAPI.insight.generateFootprintInsight({
|
|
||||||
rangeLabel: currentRange.label,
|
|
||||||
summary: data.summary,
|
|
||||||
privateSegments: privateSegments.map((item: MyFootprintPrivateSegment | MyFootprintPrivateSession) => ({
|
|
||||||
session_id: item.session_id,
|
|
||||||
displayName: item.displayName,
|
|
||||||
incoming_count: item.incoming_count,
|
|
||||||
outgoing_count: item.outgoing_count,
|
|
||||||
message_count: 'message_count' in item ? item.message_count : item.incoming_count + item.outgoing_count,
|
|
||||||
replied: item.replied
|
|
||||||
})),
|
|
||||||
mentionGroups: data.mention_groups.slice(0, 12).map((item) => ({
|
|
||||||
session_id: item.session_id,
|
|
||||||
displayName: item.displayName,
|
|
||||||
count: item.count
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
if (!result.success || !result.insight) {
|
|
||||||
setFootprintAiStatus('error')
|
|
||||||
setFootprintAiText(result.message || '生成失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setFootprintAiStatus('success')
|
|
||||||
setFootprintAiText(result.insight)
|
|
||||||
} catch (generateError) {
|
|
||||||
setFootprintAiStatus('error')
|
|
||||||
setFootprintAiText(String(generateError))
|
|
||||||
}
|
|
||||||
}, [currentRange.label, data])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="my-footprint-page">
|
|
||||||
<section className="footprint-header">
|
|
||||||
<div className="footprint-title-wrap">
|
|
||||||
<h1>我的微信足迹</h1>
|
|
||||||
<p>范围:{currentRange.label}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="footprint-toolbar">
|
|
||||||
<div className="range-preset-group">
|
|
||||||
{[
|
|
||||||
{ value: 'today', label: '今天' },
|
|
||||||
{ value: 'yesterday', label: '昨天' },
|
|
||||||
{ value: 'this_week', label: '本周' },
|
|
||||||
{ value: 'last_week', label: '上周' },
|
|
||||||
{ value: 'custom', label: '自定义' }
|
|
||||||
].map((item) => (
|
|
||||||
<button
|
|
||||||
key={item.value}
|
|
||||||
type="button"
|
|
||||||
className={`preset-chip ${preset === item.value ? 'active' : ''}`}
|
|
||||||
onClick={() => setPreset(item.value as RangePreset)}
|
|
||||||
>
|
|
||||||
{item.label}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{preset === 'custom' && (
|
|
||||||
<div className="custom-range-row">
|
|
||||||
<DateRangePicker
|
|
||||||
startDate={customStartDate}
|
|
||||||
endDate={customEndDate}
|
|
||||||
onStartDateChange={setCustomStartDate}
|
|
||||||
onEndDateChange={setCustomEndDate}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="toolbar-actions">
|
|
||||||
<div className="search-input">
|
|
||||||
<Search size={15} />
|
|
||||||
<input
|
|
||||||
value={searchKeyword}
|
|
||||||
onChange={(event) => setSearchKeyword(event.target.value)}
|
|
||||||
placeholder="搜索联系人/群聊/内容"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<button type="button" className="action-btn" onClick={() => void loadData()} disabled={loading}>
|
|
||||||
<RefreshCw size={15} className={loading ? 'spin' : ''} />
|
|
||||||
<span>刷新</span>
|
|
||||||
</button>
|
|
||||||
<button type="button" className="action-btn" onClick={() => void handleGenerateAiSummary()} disabled={loading || footprintAiStatus === 'loading'}>
|
|
||||||
{footprintAiStatus === 'loading' ? <Loader2 size={15} className="spin" /> : <Sparkles size={15} />}
|
|
||||||
<span>{footprintAiStatus === 'loading' ? '生成中...' : 'AI 总结'}</span>
|
|
||||||
</button>
|
|
||||||
<button type="button" className="action-btn" onClick={() => void handleExport('csv')} disabled={exporting || loading}>
|
|
||||||
<Download size={15} />
|
|
||||||
<span>导出 CSV</span>
|
|
||||||
</button>
|
|
||||||
<button type="button" className="action-btn" onClick={() => void handleExport('json')} disabled={exporting || loading}>
|
|
||||||
<Download size={15} />
|
|
||||||
<span>导出 JSON</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{loading ? (
|
|
||||||
<section className="footprint-loading" aria-live="polite">
|
|
||||||
<div className="kpi-skeleton-grid">
|
|
||||||
{Array.from({ length: 4 }).map((_, index) => (
|
|
||||||
<div key={index} className="kpi-skeleton-card skeleton-shimmer" />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="timeline-skeleton-list">
|
|
||||||
{Array.from({ length: 7 }).map((_, index) => (
|
|
||||||
<div key={index} className="timeline-skeleton-item skeleton-shimmer" />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
) : error ? (
|
|
||||||
<section className="footprint-error" role="alert">
|
|
||||||
<h3>读取我的足迹失败</h3>
|
|
||||||
<p>{error}</p>
|
|
||||||
<button type="button" className="action-btn" onClick={() => void loadData()}>
|
|
||||||
<RefreshCw size={15} />
|
|
||||||
<span>重试</span>
|
|
||||||
</button>
|
|
||||||
</section>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<section className="kpi-grid">
|
|
||||||
<button type="button" className="kpi-card" onClick={() => setTimelineMode('private')}>
|
|
||||||
<span className="kpi-label">有聊天的人数</span>
|
|
||||||
<strong>{data.summary.private_inbound_people}</strong>
|
|
||||||
<small>回复了其中 {data.summary.private_replied_people} 人</small>
|
|
||||||
</button>
|
|
||||||
<button type="button" className="kpi-card" onClick={() => setTimelineMode('private')}>
|
|
||||||
<span className="kpi-label">我有回复的人数</span>
|
|
||||||
<strong>{data.summary.private_outbound_people}</strong>
|
|
||||||
<small>回复率 {formatPercent(data.summary.private_reply_rate)}</small>
|
|
||||||
</button>
|
|
||||||
<button type="button" className="kpi-card" onClick={() => setTimelineMode('mention')}>
|
|
||||||
<span className="kpi-label">@我次数</span>
|
|
||||||
<strong>{data.summary.mention_count}</strong>
|
|
||||||
<small>可点击查看原消息</small>
|
|
||||||
</button>
|
|
||||||
<button type="button" className="kpi-card" onClick={() => setTimelineMode('mention')}>
|
|
||||||
<span className="kpi-label">涉及群聊</span>
|
|
||||||
<strong>{data.summary.mention_group_count}</strong>
|
|
||||||
<small>按群聚合 @我消息</small>
|
|
||||||
</button>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{footprintAiStatus !== 'idle' && (
|
|
||||||
<section className={`footprint-ai-result footprint-ai-result-${footprintAiStatus}`}>
|
|
||||||
<div className="footprint-ai-head">
|
|
||||||
<strong>AI 足迹总结</strong>
|
|
||||||
<span>{currentRange.label}</span>
|
|
||||||
</div>
|
|
||||||
<p>{footprintAiText}</p>
|
|
||||||
</section>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<section
|
|
||||||
className={`footprint-timeline timeline-time-${timelineTimeMode}`}
|
|
||||||
key={`${timelineMode}:${currentRange.begin}:${currentRange.end}`}
|
|
||||||
>
|
|
||||||
<div className="timeline-head">
|
|
||||||
<div className="timeline-head-left">
|
|
||||||
<h2>联络时间线</h2>
|
|
||||||
<p>最上方是时间区间开始,最下方是时间区间终点,中间按时间展示群聊 @我 与私聊分段会话节点。</p>
|
|
||||||
</div>
|
|
||||||
<div className="timeline-mode-row">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`timeline-mode-chip ${timelineMode === 'all' ? 'active' : ''}`}
|
|
||||||
onClick={() => setTimelineMode('all')}
|
|
||||||
>
|
|
||||||
全部 {timelineEventCount}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`timeline-mode-chip ${timelineMode === 'mention' ? 'active' : ''}`}
|
|
||||||
onClick={() => setTimelineMode('mention')}
|
|
||||||
>
|
|
||||||
@我群聊 {mentionTimelineItems.length}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`timeline-mode-chip ${timelineMode === 'private' ? 'active' : ''}`}
|
|
||||||
onClick={() => setTimelineMode('private')}
|
|
||||||
>
|
|
||||||
私聊 {privateTimelineItems.length}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{timelineEventCount === 0 ? (
|
|
||||||
<div className="panel-empty-state">当前区间暂无联络事件,试试切换日期范围或清空关键词筛选。</div>
|
|
||||||
) : (
|
|
||||||
<div className="timeline-stream">
|
|
||||||
{timelineItems.map((item, index) => (
|
|
||||||
<div
|
|
||||||
key={item.key}
|
|
||||||
className={`timeline-item timeline-item-${item.kind}`}
|
|
||||||
style={{ animationDelay: `${Math.min(index, 12) * 0.04}s` }}
|
|
||||||
>
|
|
||||||
<div className={`timeline-time timeline-time-${item.kind}`}>
|
|
||||||
{item.kind === 'private' ? (
|
|
||||||
<div className="timeline-time-range">
|
|
||||||
<span className="timeline-time-main">{formatTimelineMoment(item.time, timelineTimeMode)}</span>
|
|
||||||
{item.isRange && (
|
|
||||||
<span className="timeline-time-end-wrap">
|
|
||||||
<span className="timeline-time-end">{formatTimelineMoment(item.endTime, timelineTimeMode)}</span>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
formatTimelineMoment(item.time, timelineTimeMode)
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className={`timeline-dot-col timeline-dot-col-${item.kind}`}>
|
|
||||||
{item.kind === 'private' ? (
|
|
||||||
<div className="timeline-dot-range">
|
|
||||||
<div className={`timeline-dot timeline-dot-private timeline-dot-private-start timeline-dot-private-${item.dotVariant}`} />
|
|
||||||
{item.isRange && (
|
|
||||||
<>
|
|
||||||
<div className={`timeline-dot-range-line timeline-dot-range-line-${item.dotVariant}`} />
|
|
||||||
<div className={`timeline-dot timeline-dot-private timeline-dot-private-end timeline-dot-private-${item.dotVariant}`} />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className={`timeline-dot timeline-dot-${item.kind}${item.kind === 'boundary' ? ` timeline-dot-${item.edge}` : ''}`} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="timeline-content-wrap">
|
|
||||||
{item.kind === 'boundary' && (
|
|
||||||
<div className={`timeline-boundary timeline-boundary-${item.edge}`}>{item.label}</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{item.kind === 'mention' && (
|
|
||||||
<div className="timeline-card timeline-card-mention">
|
|
||||||
<div className="timeline-card-head">
|
|
||||||
<div className="timeline-identity">
|
|
||||||
<div className="timeline-avatar">
|
|
||||||
{item.groupAvatarUrl ? (
|
|
||||||
<img src={item.groupAvatarUrl} alt={item.groupName} />
|
|
||||||
) : (
|
|
||||||
<Users size={16} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="timeline-title-group">
|
|
||||||
<div className="timeline-title">{item.groupName}</div>
|
|
||||||
<div className="timeline-subtitle">发送人:{item.senderName}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="jump-btn timeline-jump-btn"
|
|
||||||
onClick={() => handleJump(item.sessionId, item.localId, item.createTime)}
|
|
||||||
>
|
|
||||||
跳转
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="timeline-message mention-message">{renderMentionContent(item.messageContent)}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{item.kind === 'private' && (
|
|
||||||
<div className="timeline-card timeline-card-private">
|
|
||||||
<div className="timeline-card-head">
|
|
||||||
<div className="timeline-identity">
|
|
||||||
<div className="timeline-avatar timeline-avatar-private">
|
|
||||||
{item.avatarUrl ? (
|
|
||||||
<img src={item.avatarUrl} alt={item.displayName} />
|
|
||||||
) : (
|
|
||||||
<MessageCircle size={16} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="timeline-title-group">
|
|
||||||
<div className="timeline-title">{item.displayName}</div>
|
|
||||||
<div className="timeline-subtitle">{item.subtitle}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="timeline-right-tools">
|
|
||||||
<span className="timeline-count-badge">共 {item.totalInteractions} 条</span>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="jump-btn timeline-jump-btn"
|
|
||||||
disabled={!item.anchorLocalId || !item.anchorCreateTime}
|
|
||||||
onClick={() => handleJump(item.sessionId, item.anchorLocalId, item.anchorCreateTime)}
|
|
||||||
>
|
|
||||||
跳转
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="timeline-message private-message">{item.summaryText}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{exportModalStatus !== 'idle' && (
|
|
||||||
<div className="footprint-export-modal-mask" role="presentation">
|
|
||||||
<div className="footprint-export-modal" role="dialog" aria-modal="true" aria-live="polite">
|
|
||||||
<div className={`export-modal-icon export-modal-icon-${exportModalStatus}`}>
|
|
||||||
{exportModalStatus === 'progress' && <RefreshCw size={20} className="spin" />}
|
|
||||||
{exportModalStatus === 'success' && <CheckCircle2 size={20} />}
|
|
||||||
{exportModalStatus === 'error' && <AlertCircle size={20} />}
|
|
||||||
</div>
|
|
||||||
<h3>{exportModalTitle}</h3>
|
|
||||||
<p>{exportModalDescription}</p>
|
|
||||||
{exportModalPath && <code className="export-modal-path">{exportModalPath}</code>}
|
|
||||||
{exportModalStatus !== 'progress' && (
|
|
||||||
<div className="export-modal-actions">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="action-btn"
|
|
||||||
onClick={() => {
|
|
||||||
setExportModalStatus('idle')
|
|
||||||
setExportModalTitle('')
|
|
||||||
setExportModalDescription('')
|
|
||||||
setExportModalPath('')
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
知道了
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default MyFootprintPage
|
|
||||||
@@ -177,66 +177,6 @@
|
|||||||
box-shadow: var(--shadow-sm);
|
box-shadow: var(--shadow-sm);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.tab-group {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-group-trigger {
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-group-arrow {
|
|
||||||
margin-left: auto;
|
|
||||||
color: var(--text-tertiary);
|
|
||||||
transition: transform 0.2s ease;
|
|
||||||
|
|
||||||
&.expanded {
|
|
||||||
transform: rotate(180deg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-sublist {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 4px;
|
|
||||||
padding-left: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-sublist-wrap {
|
|
||||||
display: grid;
|
|
||||||
grid-template-rows: 0fr;
|
|
||||||
opacity: 0;
|
|
||||||
transition: grid-template-rows 0.22s ease, opacity 0.18s ease;
|
|
||||||
|
|
||||||
&.expanded {
|
|
||||||
grid-template-rows: 1fr;
|
|
||||||
opacity: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
&.collapsed {
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-sublist {
|
|
||||||
min-height: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-sub-btn {
|
|
||||||
padding-left: 24px;
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-sub-dot {
|
|
||||||
width: 5px;
|
|
||||||
height: 5px;
|
|
||||||
border-radius: 999px;
|
|
||||||
background: color-mix(in srgb, var(--text-tertiary) 70%, transparent);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.settings-body {
|
.settings-body {
|
||||||
@@ -259,12 +199,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.ai-prompt-textarea {
|
|
||||||
font-family: inherit !important;
|
|
||||||
font-size: 14px !important;
|
|
||||||
line-height: 1.6;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-content {
|
.tab-content {
|
||||||
background: var(--bg-secondary);
|
background: var(--bg-secondary);
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
|
|||||||
@@ -16,23 +16,9 @@ import {
|
|||||||
import { Avatar } from '../components/Avatar'
|
import { Avatar } from '../components/Avatar'
|
||||||
import './SettingsPage.scss'
|
import './SettingsPage.scss'
|
||||||
|
|
||||||
type SettingsTab =
|
type SettingsTab = 'appearance' | 'notification' | 'antiRevoke' | 'database' | 'models' | 'cache' | 'api' | 'updates' | 'security' | 'about' | 'analytics' | 'insight'
|
||||||
| 'appearance'
|
|
||||||
| 'notification'
|
|
||||||
| 'antiRevoke'
|
|
||||||
| 'database'
|
|
||||||
| 'models'
|
|
||||||
| 'cache'
|
|
||||||
| 'api'
|
|
||||||
| 'updates'
|
|
||||||
| 'security'
|
|
||||||
| 'about'
|
|
||||||
| 'analytics'
|
|
||||||
| 'aiCommon'
|
|
||||||
| 'insight'
|
|
||||||
| 'aiFootprint'
|
|
||||||
|
|
||||||
const tabs: { id: Exclude<SettingsTab, 'insight' | 'aiFootprint'>; label: string; icon: React.ElementType }[] = [
|
const tabs: { id: SettingsTab; label: string; icon: React.ElementType }[] = [
|
||||||
{ id: 'appearance', label: '外观', icon: Palette },
|
{ id: 'appearance', label: '外观', icon: Palette },
|
||||||
{ id: 'notification', label: '通知', icon: Bell },
|
{ id: 'notification', label: '通知', icon: Bell },
|
||||||
{ id: 'antiRevoke', label: '防撤回', icon: RotateCcw },
|
{ id: 'antiRevoke', label: '防撤回', icon: RotateCcw },
|
||||||
@@ -41,17 +27,12 @@ const tabs: { id: Exclude<SettingsTab, 'insight' | 'aiFootprint'>; label: string
|
|||||||
{ id: 'cache', label: '缓存', icon: HardDrive },
|
{ id: 'cache', label: '缓存', icon: HardDrive },
|
||||||
{ id: 'api', label: 'API 服务', icon: Globe },
|
{ id: 'api', label: 'API 服务', icon: Globe },
|
||||||
{ id: 'analytics', label: '分析', icon: BarChart2 },
|
{ id: 'analytics', label: '分析', icon: BarChart2 },
|
||||||
|
{ id: 'insight', label: 'AI 见解', icon: Sparkles },
|
||||||
{ id: 'security', label: '安全', icon: ShieldCheck },
|
{ id: 'security', label: '安全', icon: ShieldCheck },
|
||||||
{ id: 'updates', label: '版本更新', icon: RefreshCw },
|
{ id: 'updates', label: '版本更新', icon: RefreshCw },
|
||||||
{ id: 'about', label: '关于', icon: Info }
|
{ id: 'about', label: '关于', icon: Info }
|
||||||
]
|
]
|
||||||
|
|
||||||
const aiTabs: Array<{ id: Extract<SettingsTab, 'aiCommon' | 'insight' | 'aiFootprint'>; label: string }> = [
|
|
||||||
{ id: 'aiCommon', label: 'AI 通用' },
|
|
||||||
{ id: 'insight', label: 'AI 见解' },
|
|
||||||
{ id: 'aiFootprint', label: 'AI 足迹' }
|
|
||||||
]
|
|
||||||
|
|
||||||
const isMac = navigator.userAgent.toLowerCase().includes('mac')
|
const isMac = navigator.userAgent.toLowerCase().includes('mac')
|
||||||
const isLinux = navigator.userAgent.toLowerCase().includes('linux')
|
const isLinux = navigator.userAgent.toLowerCase().includes('linux')
|
||||||
const isWindows = !isMac && !isLinux
|
const isWindows = !isMac && !isLinux
|
||||||
@@ -107,7 +88,6 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
const clearAnalyticsStoreCache = useAnalyticsStore((state) => state.clearCache)
|
const clearAnalyticsStoreCache = useAnalyticsStore((state) => state.clearCache)
|
||||||
|
|
||||||
const [activeTab, setActiveTab] = useState<SettingsTab>('appearance')
|
const [activeTab, setActiveTab] = useState<SettingsTab>('appearance')
|
||||||
const [aiGroupExpanded, setAiGroupExpanded] = useState(false)
|
|
||||||
const [decryptKey, setDecryptKey] = useState('')
|
const [decryptKey, setDecryptKey] = useState('')
|
||||||
const [imageXorKey, setImageXorKey] = useState('')
|
const [imageXorKey, setImageXorKey] = useState('')
|
||||||
const [imageAesKey, setImageAesKey] = useState('')
|
const [imageAesKey, setImageAesKey] = useState('')
|
||||||
@@ -145,7 +125,7 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
|
|
||||||
setHttpApiToken(token)
|
setHttpApiToken(token)
|
||||||
await configService.setHttpApiToken(token)
|
await configService.setHttpApiToken(token)
|
||||||
showMessage('已生成并保存新的 Access Token', true)
|
showMessage('已生成<EFBFBD><EFBFBD>保存新的 Access Token', true)
|
||||||
}
|
}
|
||||||
|
|
||||||
const clearApiToken = async () => {
|
const clearApiToken = async () => {
|
||||||
@@ -237,19 +217,9 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
|
|
||||||
// AI 见解 state
|
// AI 见解 state
|
||||||
const [aiInsightEnabled, setAiInsightEnabled] = useState(false)
|
const [aiInsightEnabled, setAiInsightEnabled] = useState(false)
|
||||||
const [aiModelApiBaseUrl, setAiModelApiBaseUrl] = useState('')
|
const [aiInsightApiBaseUrl, setAiInsightApiBaseUrl] = useState('')
|
||||||
const [aiModelApiKey, setAiModelApiKey] = useState('')
|
const [aiInsightApiKey, setAiInsightApiKey] = useState('')
|
||||||
const [aiModelApiModel, setAiModelApiModel] = useState('gpt-4o-mini')
|
const [aiInsightApiModel, setAiInsightApiModel] = useState('gpt-4o-mini')
|
||||||
const [aiAgentMaxMessagesPerRequest, setAiAgentMaxMessagesPerRequest] = useState(120)
|
|
||||||
const [aiAgentMaxHistoryRounds, setAiAgentMaxHistoryRounds] = useState(12)
|
|
||||||
const [aiAgentEnableAutoSkill, setAiAgentEnableAutoSkill] = useState(true)
|
|
||||||
const [aiAgentSearchContextBefore, setAiAgentSearchContextBefore] = useState(3)
|
|
||||||
const [aiAgentSearchContextAfter, setAiAgentSearchContextAfter] = useState(3)
|
|
||||||
const [aiAgentPreprocessClean, setAiAgentPreprocessClean] = useState(true)
|
|
||||||
const [aiAgentPreprocessMerge, setAiAgentPreprocessMerge] = useState(true)
|
|
||||||
const [aiAgentPreprocessDenoise, setAiAgentPreprocessDenoise] = useState(true)
|
|
||||||
const [aiAgentPreprocessDesensitize, setAiAgentPreprocessDesensitize] = useState(false)
|
|
||||||
const [aiAgentPreprocessAnonymize, setAiAgentPreprocessAnonymize] = useState(false)
|
|
||||||
const [aiInsightSilenceDays, setAiInsightSilenceDays] = useState(3)
|
const [aiInsightSilenceDays, setAiInsightSilenceDays] = useState(3)
|
||||||
const [aiInsightAllowContext, setAiInsightAllowContext] = useState(false)
|
const [aiInsightAllowContext, setAiInsightAllowContext] = useState(false)
|
||||||
const [isTestingInsight, setIsTestingInsight] = useState(false)
|
const [isTestingInsight, setIsTestingInsight] = useState(false)
|
||||||
@@ -267,8 +237,6 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
const [aiInsightTelegramEnabled, setAiInsightTelegramEnabled] = useState(false)
|
const [aiInsightTelegramEnabled, setAiInsightTelegramEnabled] = useState(false)
|
||||||
const [aiInsightTelegramToken, setAiInsightTelegramToken] = useState('')
|
const [aiInsightTelegramToken, setAiInsightTelegramToken] = useState('')
|
||||||
const [aiInsightTelegramChatIds, setAiInsightTelegramChatIds] = useState('')
|
const [aiInsightTelegramChatIds, setAiInsightTelegramChatIds] = useState('')
|
||||||
const [aiFootprintEnabled, setAiFootprintEnabled] = useState(false)
|
|
||||||
const [aiFootprintSystemPrompt, setAiFootprintSystemPrompt] = useState('')
|
|
||||||
|
|
||||||
// 检查 Hello 可用性
|
// 检查 Hello 可用性
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -308,12 +276,6 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
setActiveTab(initialTab)
|
setActiveTab(initialTab)
|
||||||
}, [location.state])
|
}, [location.state])
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (activeTab === 'aiCommon' || activeTab === 'insight' || activeTab === 'aiFootprint') {
|
|
||||||
setAiGroupExpanded(true)
|
|
||||||
}
|
|
||||||
}, [activeTab])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!onClose) return
|
if (!onClose) return
|
||||||
const handleKeyDown = (event: KeyboardEvent) => {
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
@@ -486,19 +448,9 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
|
|
||||||
// 加载 AI 见解配置
|
// 加载 AI 见解配置
|
||||||
const savedAiInsightEnabled = await configService.getAiInsightEnabled()
|
const savedAiInsightEnabled = await configService.getAiInsightEnabled()
|
||||||
const savedAiModelApiBaseUrl = await configService.getAiModelApiBaseUrl()
|
const savedAiInsightApiBaseUrl = await configService.getAiInsightApiBaseUrl()
|
||||||
const savedAiModelApiKey = await configService.getAiModelApiKey()
|
const savedAiInsightApiKey = await configService.getAiInsightApiKey()
|
||||||
const savedAiModelApiModel = await configService.getAiModelApiModel()
|
const savedAiInsightApiModel = await configService.getAiInsightApiModel()
|
||||||
const savedAiAgentMaxMessagesPerRequest = await configService.getAiAgentMaxMessagesPerRequest()
|
|
||||||
const savedAiAgentMaxHistoryRounds = await configService.getAiAgentMaxHistoryRounds()
|
|
||||||
const savedAiAgentEnableAutoSkill = await configService.getAiAgentEnableAutoSkill()
|
|
||||||
const savedAiAgentSearchContextBefore = await configService.getAiAgentSearchContextBefore()
|
|
||||||
const savedAiAgentSearchContextAfter = await configService.getAiAgentSearchContextAfter()
|
|
||||||
const savedAiAgentPreprocessClean = await configService.getAiAgentPreprocessClean()
|
|
||||||
const savedAiAgentPreprocessMerge = await configService.getAiAgentPreprocessMerge()
|
|
||||||
const savedAiAgentPreprocessDenoise = await configService.getAiAgentPreprocessDenoise()
|
|
||||||
const savedAiAgentPreprocessDesensitize = await configService.getAiAgentPreprocessDesensitize()
|
|
||||||
const savedAiAgentPreprocessAnonymize = await configService.getAiAgentPreprocessAnonymize()
|
|
||||||
const savedAiInsightSilenceDays = await configService.getAiInsightSilenceDays()
|
const savedAiInsightSilenceDays = await configService.getAiInsightSilenceDays()
|
||||||
const savedAiInsightAllowContext = await configService.getAiInsightAllowContext()
|
const savedAiInsightAllowContext = await configService.getAiInsightAllowContext()
|
||||||
const savedAiInsightWhitelistEnabled = await configService.getAiInsightWhitelistEnabled()
|
const savedAiInsightWhitelistEnabled = await configService.getAiInsightWhitelistEnabled()
|
||||||
@@ -510,22 +462,10 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
const savedAiInsightTelegramEnabled = await configService.getAiInsightTelegramEnabled()
|
const savedAiInsightTelegramEnabled = await configService.getAiInsightTelegramEnabled()
|
||||||
const savedAiInsightTelegramToken = await configService.getAiInsightTelegramToken()
|
const savedAiInsightTelegramToken = await configService.getAiInsightTelegramToken()
|
||||||
const savedAiInsightTelegramChatIds = await configService.getAiInsightTelegramChatIds()
|
const savedAiInsightTelegramChatIds = await configService.getAiInsightTelegramChatIds()
|
||||||
const savedAiFootprintEnabled = await configService.getAiFootprintEnabled()
|
|
||||||
const savedAiFootprintSystemPrompt = await configService.getAiFootprintSystemPrompt()
|
|
||||||
setAiInsightEnabled(savedAiInsightEnabled)
|
setAiInsightEnabled(savedAiInsightEnabled)
|
||||||
setAiModelApiBaseUrl(savedAiModelApiBaseUrl)
|
setAiInsightApiBaseUrl(savedAiInsightApiBaseUrl)
|
||||||
setAiModelApiKey(savedAiModelApiKey)
|
setAiInsightApiKey(savedAiInsightApiKey)
|
||||||
setAiModelApiModel(savedAiModelApiModel)
|
setAiInsightApiModel(savedAiInsightApiModel)
|
||||||
setAiAgentMaxMessagesPerRequest(savedAiAgentMaxMessagesPerRequest)
|
|
||||||
setAiAgentMaxHistoryRounds(savedAiAgentMaxHistoryRounds)
|
|
||||||
setAiAgentEnableAutoSkill(savedAiAgentEnableAutoSkill)
|
|
||||||
setAiAgentSearchContextBefore(savedAiAgentSearchContextBefore)
|
|
||||||
setAiAgentSearchContextAfter(savedAiAgentSearchContextAfter)
|
|
||||||
setAiAgentPreprocessClean(savedAiAgentPreprocessClean)
|
|
||||||
setAiAgentPreprocessMerge(savedAiAgentPreprocessMerge)
|
|
||||||
setAiAgentPreprocessDenoise(savedAiAgentPreprocessDenoise)
|
|
||||||
setAiAgentPreprocessDesensitize(savedAiAgentPreprocessDesensitize)
|
|
||||||
setAiAgentPreprocessAnonymize(savedAiAgentPreprocessAnonymize)
|
|
||||||
setAiInsightSilenceDays(savedAiInsightSilenceDays)
|
setAiInsightSilenceDays(savedAiInsightSilenceDays)
|
||||||
setAiInsightAllowContext(savedAiInsightAllowContext)
|
setAiInsightAllowContext(savedAiInsightAllowContext)
|
||||||
setAiInsightWhitelistEnabled(savedAiInsightWhitelistEnabled)
|
setAiInsightWhitelistEnabled(savedAiInsightWhitelistEnabled)
|
||||||
@@ -537,8 +477,6 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
setAiInsightTelegramEnabled(savedAiInsightTelegramEnabled)
|
setAiInsightTelegramEnabled(savedAiInsightTelegramEnabled)
|
||||||
setAiInsightTelegramToken(savedAiInsightTelegramToken)
|
setAiInsightTelegramToken(savedAiInsightTelegramToken)
|
||||||
setAiInsightTelegramChatIds(savedAiInsightTelegramChatIds)
|
setAiInsightTelegramChatIds(savedAiInsightTelegramChatIds)
|
||||||
setAiFootprintEnabled(savedAiFootprintEnabled)
|
|
||||||
setAiFootprintSystemPrompt(savedAiFootprintSystemPrompt)
|
|
||||||
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error('加载配置失败:', e)
|
console.error('加载配置失败:', e)
|
||||||
@@ -680,7 +618,7 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
showMessage(`已切换到${channelLabel}更新渠道,正在检查更新`, true)
|
showMessage(`已切换到${channelLabel}更新渠道,正在检查更新`, true)
|
||||||
await handleCheckUpdate()
|
await handleCheckUpdate()
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
showMessage(`切换更新渠道失败: ${e}`, false)
|
showMessage(`切换更新渠道<EFBFBD><EFBFBD>败: ${e}`, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1275,7 +1213,7 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
if (result.success && result.aesKey) {
|
if (result.success && result.aesKey) {
|
||||||
if (typeof result.xorKey === 'number') setImageXorKey(`0x${result.xorKey.toString(16).toUpperCase().padStart(2, '0')}`)
|
if (typeof result.xorKey === 'number') setImageXorKey(`0x${result.xorKey.toString(16).toUpperCase().padStart(2, '0')}`)
|
||||||
setImageAesKey(result.aesKey)
|
setImageAesKey(result.aesKey)
|
||||||
setImageKeyStatus('已获取图片密钥')
|
setImageKeyStatus('已获取图片<EFBFBD><EFBFBD>钥')
|
||||||
showMessage('已自动获取图片密钥', true)
|
showMessage('已自动获取图片密钥', true)
|
||||||
const newXorKey = typeof result.xorKey === 'number' ? result.xorKey : 0
|
const newXorKey = typeof result.xorKey === 'number' ? result.xorKey : 0
|
||||||
const newAesKey = result.aesKey
|
const newAesKey = result.aesKey
|
||||||
@@ -2560,225 +2498,6 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const renderAiCommonTab = () => (
|
|
||||||
<div className="tab-content">
|
|
||||||
<div className="form-group">
|
|
||||||
<label>通用 API 地址</label>
|
|
||||||
<span className="form-hint">
|
|
||||||
这是「AI 见解」与「AI 足迹总结」共享的模型接入配置。填写 OpenAI 兼容接口的 <strong>Base URL</strong>,末尾<strong>不要加斜杠</strong>。
|
|
||||||
程序会自动拼接 <code>/chat/completions</code>。
|
|
||||||
<br />
|
|
||||||
示例:<code>https://api.ohmygpt.com/v1</code> 或 <code>https://api.openai.com/v1</code>
|
|
||||||
</span>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
className="field-input"
|
|
||||||
value={aiModelApiBaseUrl}
|
|
||||||
placeholder="https://api.ohmygpt.com/v1"
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = e.target.value
|
|
||||||
setAiModelApiBaseUrl(val)
|
|
||||||
scheduleConfigSave('aiModelApiBaseUrl', () => configService.setAiModelApiBaseUrl(val))
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="form-group">
|
|
||||||
<label>通用 API Key</label>
|
|
||||||
<span className="form-hint">
|
|
||||||
你的 API Key,保存后经过系统加密存储,不会明文写入磁盘。
|
|
||||||
</span>
|
|
||||||
<div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
|
|
||||||
<input
|
|
||||||
type={showInsightApiKey ? 'text' : 'password'}
|
|
||||||
className="field-input"
|
|
||||||
value={aiModelApiKey}
|
|
||||||
placeholder="sk-..."
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = e.target.value
|
|
||||||
setAiModelApiKey(val)
|
|
||||||
scheduleConfigSave('aiModelApiKey', () => configService.setAiModelApiKey(val))
|
|
||||||
}}
|
|
||||||
style={{ flex: 1 }}
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
className="btn btn-secondary"
|
|
||||||
onClick={() => setShowInsightApiKey(!showInsightApiKey)}
|
|
||||||
title={showInsightApiKey ? '隐藏' : '显示'}
|
|
||||||
>
|
|
||||||
{showInsightApiKey ? <EyeOff size={14} /> : <Eye size={14} />}
|
|
||||||
</button>
|
|
||||||
{aiModelApiKey && (
|
|
||||||
<button
|
|
||||||
className="btn btn-danger"
|
|
||||||
onClick={async () => {
|
|
||||||
setAiModelApiKey('')
|
|
||||||
await configService.setAiModelApiKey('')
|
|
||||||
}}
|
|
||||||
title="清除 Key"
|
|
||||||
>
|
|
||||||
<Trash2 size={14} />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="form-group">
|
|
||||||
<label>通用模型名称</label>
|
|
||||||
<span className="form-hint">
|
|
||||||
填写你的 API 提供商支持的模型名,将同时用于见解和足迹模块。
|
|
||||||
<br />
|
|
||||||
常用示例:<code>gpt-4o-mini</code>、<code>gpt-4o</code>、<code>deepseek-chat</code>、<code>claude-3-5-haiku-20241022</code>
|
|
||||||
</span>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
className="field-input"
|
|
||||||
value={aiModelApiModel}
|
|
||||||
placeholder="gpt-4o-mini"
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = e.target.value.trim() || 'gpt-4o-mini'
|
|
||||||
setAiModelApiModel(val)
|
|
||||||
scheduleConfigSave('aiModelApiModel', () => configService.setAiModelApiModel(val))
|
|
||||||
}}
|
|
||||||
style={{ width: 260 }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="divider" />
|
|
||||||
|
|
||||||
<div className="form-group">
|
|
||||||
<label>Agent 运行参数</label>
|
|
||||||
<span className="form-hint">
|
|
||||||
控制 AI 分析时的上下文与工具读取规模。
|
|
||||||
</span>
|
|
||||||
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 8 }}>
|
|
||||||
<div>
|
|
||||||
<span style={{ fontSize: 12, opacity: 0.8 }}>单次最大消息数</span>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
className="field-input"
|
|
||||||
value={aiAgentMaxMessagesPerRequest}
|
|
||||||
min={20}
|
|
||||||
max={500}
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = Math.max(20, Math.min(500, parseInt(e.target.value, 10) || 120))
|
|
||||||
setAiAgentMaxMessagesPerRequest(val)
|
|
||||||
scheduleConfigSave('aiAgentMaxMessagesPerRequest', () => configService.setAiAgentMaxMessagesPerRequest(val))
|
|
||||||
}}
|
|
||||||
style={{ width: 130, marginTop: 6 }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<span style={{ fontSize: 12, opacity: 0.8 }}>历史轮数上限</span>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
className="field-input"
|
|
||||||
value={aiAgentMaxHistoryRounds}
|
|
||||||
min={4}
|
|
||||||
max={60}
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = Math.max(4, Math.min(60, parseInt(e.target.value, 10) || 12))
|
|
||||||
setAiAgentMaxHistoryRounds(val)
|
|
||||||
scheduleConfigSave('aiAgentMaxHistoryRounds', () => configService.setAiAgentMaxHistoryRounds(val))
|
|
||||||
}}
|
|
||||||
style={{ width: 130, marginTop: 6 }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<span style={{ fontSize: 12, opacity: 0.8 }}>搜索上下文前后条数</span>
|
|
||||||
<div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
className="field-input"
|
|
||||||
value={aiAgentSearchContextBefore}
|
|
||||||
min={0}
|
|
||||||
max={20}
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = Math.max(0, Math.min(20, parseInt(e.target.value, 10) || 3))
|
|
||||||
setAiAgentSearchContextBefore(val)
|
|
||||||
scheduleConfigSave('aiAgentSearchContextBefore', () => configService.setAiAgentSearchContextBefore(val))
|
|
||||||
}}
|
|
||||||
style={{ width: 90 }}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
className="field-input"
|
|
||||||
value={aiAgentSearchContextAfter}
|
|
||||||
min={0}
|
|
||||||
max={20}
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = Math.max(0, Math.min(20, parseInt(e.target.value, 10) || 3))
|
|
||||||
setAiAgentSearchContextAfter(val)
|
|
||||||
scheduleConfigSave('aiAgentSearchContextAfter', () => configService.setAiAgentSearchContextAfter(val))
|
|
||||||
}}
|
|
||||||
style={{ width: 90 }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="form-group">
|
|
||||||
<label>技能与预处理</label>
|
|
||||||
<span className="form-hint">
|
|
||||||
自动技能会让 Agent 根据问题动态调用 <code>activate_skill</code>;预处理用于清洗/合并/去噪/脱敏/匿名。
|
|
||||||
</span>
|
|
||||||
<div style={{ display: 'grid', gap: 8, marginTop: 8 }}>
|
|
||||||
{[
|
|
||||||
['自动技能 Auto Skill', aiAgentEnableAutoSkill, setAiAgentEnableAutoSkill, () => configService.setAiAgentEnableAutoSkill(!aiAgentEnableAutoSkill), 'aiAgentEnableAutoSkill'],
|
|
||||||
['清洗', aiAgentPreprocessClean, setAiAgentPreprocessClean, () => configService.setAiAgentPreprocessClean(!aiAgentPreprocessClean), 'aiAgentPreprocessClean'],
|
|
||||||
['合并', aiAgentPreprocessMerge, setAiAgentPreprocessMerge, () => configService.setAiAgentPreprocessMerge(!aiAgentPreprocessMerge), 'aiAgentPreprocessMerge'],
|
|
||||||
['去噪', aiAgentPreprocessDenoise, setAiAgentPreprocessDenoise, () => configService.setAiAgentPreprocessDenoise(!aiAgentPreprocessDenoise), 'aiAgentPreprocessDenoise'],
|
|
||||||
['脱敏', aiAgentPreprocessDesensitize, setAiAgentPreprocessDesensitize, () => configService.setAiAgentPreprocessDesensitize(!aiAgentPreprocessDesensitize), 'aiAgentPreprocessDesensitize'],
|
|
||||||
['匿名', aiAgentPreprocessAnonymize, setAiAgentPreprocessAnonymize, () => configService.setAiAgentPreprocessAnonymize(!aiAgentPreprocessAnonymize), 'aiAgentPreprocessAnonymize']
|
|
||||||
].map(([label, value, setter, saveFn, key]) => (
|
|
||||||
<div key={key as string} className="log-toggle-line">
|
|
||||||
<span className="log-status">{label as string}</span>
|
|
||||||
<label className="switch">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={value as boolean}
|
|
||||||
onChange={() => {
|
|
||||||
const next = !(value as boolean)
|
|
||||||
;(setter as (value: boolean) => void)(next)
|
|
||||||
scheduleConfigSave(key as string, saveFn as () => Promise<void>)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<span className="switch-slider" />
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="form-group">
|
|
||||||
<label>连接测试</label>
|
|
||||||
<span className="form-hint">
|
|
||||||
测试通用模型连接,见解与足迹都会使用这套配置。
|
|
||||||
</span>
|
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap', marginTop: '10px' }}>
|
|
||||||
<button
|
|
||||||
className="btn btn-secondary"
|
|
||||||
onClick={handleTestInsightConnection}
|
|
||||||
disabled={isTestingInsight || !aiModelApiBaseUrl || !aiModelApiKey}
|
|
||||||
>
|
|
||||||
{isTestingInsight ? (
|
|
||||||
<><Loader2 size={14} style={{ marginRight: 4, animation: 'spin 1s linear infinite' }} />测试中...</>
|
|
||||||
) : (
|
|
||||||
<>测试 API 连接</>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
{insightTestResult && (
|
|
||||||
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: insightTestResult.success ? 'var(--color-success, #22c55e)' : 'var(--color-danger, #ef4444)' }}>
|
|
||||||
{insightTestResult.success ? <CheckCircle2 size={14} /> : <XCircle size={14} />}
|
|
||||||
{insightTestResult.message}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
|
|
||||||
const renderInsightTab = () => (
|
const renderInsightTab = () => (
|
||||||
<div className="tab-content">
|
<div className="tab-content">
|
||||||
{/* 总开关 */}
|
{/* 总开关 */}
|
||||||
@@ -2807,41 +2526,149 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
|
|
||||||
<div className="divider" />
|
<div className="divider" />
|
||||||
|
|
||||||
|
{/* API 配置 */}
|
||||||
|
<div className="form-group">
|
||||||
|
<label>API 地址</label>
|
||||||
|
<span className="form-hint">
|
||||||
|
填写 OpenAI 兼容接口的 <strong>Base URL</strong>,末尾<strong>不要加斜杠</strong>。
|
||||||
|
程序会自动拼接 <code>/chat/completions</code>。
|
||||||
|
<br />
|
||||||
|
示例:<code>https://api.ohmygpt.com/v1</code> 或 <code>https://api.openai.com/v1</code>
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="field-input"
|
||||||
|
value={aiInsightApiBaseUrl}
|
||||||
|
placeholder="https://api.ohmygpt.com/v1"
|
||||||
|
onChange={(e) => {
|
||||||
|
const val = e.target.value
|
||||||
|
setAiInsightApiBaseUrl(val)
|
||||||
|
scheduleConfigSave('aiInsightApiBaseUrl', () => configService.setAiInsightApiBaseUrl(val))
|
||||||
|
}}
|
||||||
|
style={{ fontFamily: 'monospace' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label>API Key</label>
|
||||||
|
<span className="form-hint">
|
||||||
|
你的 API Key,保存后经过系统加密存储,不会明文写入磁盘。
|
||||||
|
</span>
|
||||||
|
<div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
|
||||||
|
<input
|
||||||
|
type={showInsightApiKey ? 'text' : 'password'}
|
||||||
|
className="field-input"
|
||||||
|
value={aiInsightApiKey}
|
||||||
|
placeholder="sk-..."
|
||||||
|
onChange={(e) => {
|
||||||
|
const val = e.target.value
|
||||||
|
setAiInsightApiKey(val)
|
||||||
|
scheduleConfigSave('aiInsightApiKey', () => configService.setAiInsightApiKey(val))
|
||||||
|
}}
|
||||||
|
style={{ flex: 1, fontFamily: 'monospace' }}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setShowInsightApiKey(!showInsightApiKey)}
|
||||||
|
title={showInsightApiKey ? '隐藏' : '显示'}
|
||||||
|
>
|
||||||
|
{showInsightApiKey ? <EyeOff size={14} /> : <Eye size={14} />}
|
||||||
|
</button>
|
||||||
|
{aiInsightApiKey && (
|
||||||
|
<button
|
||||||
|
className="btn btn-danger"
|
||||||
|
onClick={async () => {
|
||||||
|
setAiInsightApiKey('')
|
||||||
|
await configService.setAiInsightApiKey('')
|
||||||
|
}}
|
||||||
|
title="清除 Key"
|
||||||
|
>
|
||||||
|
<Trash2 size={14} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label>模型名称</label>
|
||||||
|
<span className="form-hint">
|
||||||
|
填写你的 API 提供商支持的模型名,建议使用综合能力较强的模型以获得有洞察力的见解。
|
||||||
|
<br />
|
||||||
|
常用示例:<code>gpt-4o-mini</code>、<code>gpt-4o</code>、<code>deepseek-chat</code>、<code>claude-3-5-haiku-20241022</code>
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="field-input"
|
||||||
|
value={aiInsightApiModel}
|
||||||
|
placeholder="gpt-4o-mini"
|
||||||
|
onChange={(e) => {
|
||||||
|
const val = e.target.value.trim() || 'gpt-4o-mini'
|
||||||
|
setAiInsightApiModel(val)
|
||||||
|
scheduleConfigSave('aiInsightApiModel', () => configService.setAiInsightApiModel(val))
|
||||||
|
}}
|
||||||
|
style={{ width: 260, fontFamily: 'monospace' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 测试连接 + 触发测试 */}
|
||||||
<div className="form-group">
|
<div className="form-group">
|
||||||
<label>调试工具</label>
|
<label>调试工具</label>
|
||||||
<span className="form-hint">
|
<span className="form-hint">
|
||||||
该功能依赖「AI 通用」里的模型配置。用于验证完整链路(数据库→API→弹窗)。
|
先用"测试 API 连接"确认 Key 和 URL 填写正确,再用"立即触发测试见解"验证完整链路(数据库→API→弹窗)。触发后请留意右下角通知弹窗。
|
||||||
</span>
|
</span>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap', marginTop: '10px' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginTop: '10px' }}>
|
||||||
<button
|
{/* 测试 API 连接 */}
|
||||||
className="btn btn-secondary"
|
<div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
|
||||||
onClick={async () => {
|
<button
|
||||||
setIsTriggeringInsightTest(true)
|
className="btn btn-secondary"
|
||||||
setInsightTriggerResult(null)
|
onClick={handleTestInsightConnection}
|
||||||
try {
|
disabled={isTestingInsight || !aiInsightApiBaseUrl || !aiInsightApiKey}
|
||||||
const result = await (window.electronAPI as any).insight.triggerTest()
|
>
|
||||||
setInsightTriggerResult(result)
|
{isTestingInsight ? (
|
||||||
} catch (e: any) {
|
<><Loader2 size={14} style={{ marginRight: 4, animation: 'spin 1s linear infinite' }} />测试中...</>
|
||||||
setInsightTriggerResult({ success: false, message: `调用失败:${e?.message || String(e)}` })
|
) : (
|
||||||
} finally {
|
<>测试 API 连接</>
|
||||||
setIsTriggeringInsightTest(false)
|
)}
|
||||||
}
|
</button>
|
||||||
}}
|
{insightTestResult && (
|
||||||
disabled={isTriggeringInsightTest || !aiInsightEnabled || !aiModelApiBaseUrl || !aiModelApiKey}
|
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: insightTestResult.success ? 'var(--color-success, #22c55e)' : 'var(--color-danger, #ef4444)' }}>
|
||||||
title={!aiInsightEnabled ? '请先开启 AI 见解总开关' : ''}
|
{insightTestResult.success ? <CheckCircle2 size={14} /> : <XCircle size={14} />}
|
||||||
>
|
{insightTestResult.message}
|
||||||
{isTriggeringInsightTest ? (
|
</span>
|
||||||
<><Loader2 size={14} style={{ marginRight: 4, animation: 'spin 1s linear infinite' }} />触发中...</>
|
|
||||||
) : (
|
|
||||||
<>立即触发测试见解</>
|
|
||||||
)}
|
)}
|
||||||
</button>
|
</div>
|
||||||
{insightTriggerResult && (
|
{/* 触发测试见解 */}
|
||||||
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: insightTriggerResult.success ? 'var(--color-success, #22c55e)' : 'var(--color-danger, #ef4444)' }}>
|
<div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
|
||||||
{insightTriggerResult.success ? <CheckCircle2 size={14} /> : <XCircle size={14} />}
|
<button
|
||||||
{insightTriggerResult.message}
|
className="btn btn-secondary"
|
||||||
</span>
|
onClick={async () => {
|
||||||
)}
|
setIsTriggeringInsightTest(true)
|
||||||
|
setInsightTriggerResult(null)
|
||||||
|
try {
|
||||||
|
const result = await (window.electronAPI as any).insight.triggerTest()
|
||||||
|
setInsightTriggerResult(result)
|
||||||
|
} catch (e: any) {
|
||||||
|
setInsightTriggerResult({ success: false, message: `调用失败:${e?.message || String(e)}` })
|
||||||
|
} finally {
|
||||||
|
setIsTriggeringInsightTest(false)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={isTriggeringInsightTest || !aiInsightEnabled || !aiInsightApiBaseUrl || !aiInsightApiKey}
|
||||||
|
title={!aiInsightEnabled ? '请先开启 AI 见解总开关' : ''}
|
||||||
|
>
|
||||||
|
{isTriggeringInsightTest ? (
|
||||||
|
<><Loader2 size={14} style={{ marginRight: 4, animation: 'spin 1s linear infinite' }} />触发中...</>
|
||||||
|
) : (
|
||||||
|
<>立即触发测试见解</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
{insightTriggerResult && (
|
||||||
|
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: insightTriggerResult.success ? 'var(--color-success, #22c55e)' : 'var(--color-danger, #ef4444)' }}>
|
||||||
|
{insightTriggerResult.success ? <CheckCircle2 size={14} /> : <XCircle size={14} />}
|
||||||
|
{insightTriggerResult.message}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -2997,9 +2824,9 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
当前显示内置默认提示词,可直接编辑修改。修改后立即生效,无需重启。可变的统计信息(触发次数、对话内容)会自动附加在用户消息里,无需在此填写。
|
当前显示内置默认提示词,可直接编辑修改。修改后立即生效,无需重启。可变的统计信息(触发次数、对话内容)会自动附加在用户消息里,无需在此填写。
|
||||||
</span>
|
</span>
|
||||||
<textarea
|
<textarea
|
||||||
className="field-input ai-prompt-textarea"
|
className="field-input"
|
||||||
rows={8}
|
rows={8}
|
||||||
style={{ width: '100%', resize: 'vertical' }}
|
style={{ width: '100%', resize: 'vertical', fontFamily: 'monospace', fontSize: 12 }}
|
||||||
value={displayValue}
|
value={displayValue}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const val = e.target.value
|
const val = e.target.value
|
||||||
@@ -3045,7 +2872,7 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
type="password"
|
type="password"
|
||||||
className="field-input"
|
className="field-input"
|
||||||
style={{ width: '100%' }}
|
style={{ width: '100%' }}
|
||||||
placeholder="在此处填入你的 Telegram Bot Token"
|
placeholder="110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw"
|
||||||
value={aiInsightTelegramToken}
|
value={aiInsightTelegramToken}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const val = e.target.value
|
const val = e.target.value
|
||||||
@@ -3279,74 +3106,6 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|
||||||
const renderAiFootprintTab = () => (
|
|
||||||
<div className="tab-content">
|
|
||||||
{(() => {
|
|
||||||
const DEFAULT_FOOTPRINT_PROMPT = `你是用户的聊天足迹教练,负责基于统计数据给出一段简明复盘。
|
|
||||||
要求:
|
|
||||||
1. 输出 2-3 句,总长度不超过 180 字。
|
|
||||||
2. 必须包含:总体观察 + 一个可执行建议。
|
|
||||||
3. 语气务实,不夸张,不使用 Markdown。`
|
|
||||||
const displayValue = aiFootprintSystemPrompt || DEFAULT_FOOTPRINT_PROMPT
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<div className="form-group">
|
|
||||||
<label>AI 足迹总结</label>
|
|
||||||
<span className="form-hint">
|
|
||||||
开启后,可在「我的微信足迹」页面一键生成当前范围的 AI 复盘总结。
|
|
||||||
</span>
|
|
||||||
<div className="log-toggle-line">
|
|
||||||
<span className="log-status">{aiFootprintEnabled ? '已开启' : '已关闭'}</span>
|
|
||||||
<label className="switch">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={aiFootprintEnabled}
|
|
||||||
onChange={async (e) => {
|
|
||||||
const val = e.target.checked
|
|
||||||
setAiFootprintEnabled(val)
|
|
||||||
await configService.setAiFootprintEnabled(val)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<span className="switch-slider" />
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="form-group">
|
|
||||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
|
|
||||||
<label style={{ marginBottom: 0 }}>足迹总结提示词</label>
|
|
||||||
<button
|
|
||||||
className="button-secondary"
|
|
||||||
style={{ fontSize: 12, padding: '3px 10px' }}
|
|
||||||
onClick={async () => {
|
|
||||||
setAiFootprintSystemPrompt('')
|
|
||||||
await configService.setAiFootprintSystemPrompt('')
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
恢复默认
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<span className="form-hint">
|
|
||||||
足迹模块专用的小配置。留空时使用内置默认提示词。
|
|
||||||
</span>
|
|
||||||
<textarea
|
|
||||||
className="field-input ai-prompt-textarea"
|
|
||||||
rows={6}
|
|
||||||
style={{ width: '100%', resize: 'vertical' }}
|
|
||||||
value={displayValue}
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = e.target.value
|
|
||||||
setAiFootprintSystemPrompt(val)
|
|
||||||
scheduleConfigSave('aiFootprintSystemPrompt', () => configService.setAiFootprintSystemPrompt(val))
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
})()}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
|
|
||||||
const renderApiTab = () => (
|
const renderApiTab = () => (
|
||||||
<div className="tab-content">
|
<div className="tab-content">
|
||||||
<div className="form-group">
|
<div className="form-group">
|
||||||
@@ -3448,7 +3207,7 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
value={`http://${httpApiHost}:${httpApiPort}`}
|
value={`http://${httpApiHost}:${httpApiPort}`}
|
||||||
readOnly
|
readOnly
|
||||||
/>
|
/>
|
||||||
<button className="btn btn-secondary" onClick={handleCopyApiUrl} title="复制">
|
<button className="btn btn-secondary" onClick={handleCopyApiUrl} title="复<EFBFBD><EFBFBD><EFBFBD>">
|
||||||
<Copy size={16} />
|
<Copy size={16} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -3582,7 +3341,7 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
try {
|
try {
|
||||||
const verifyResult = await window.electronAPI.auth.hello('请验证您的身份以开启 Windows Hello')
|
const verifyResult = await window.electronAPI.auth.hello('请验证您的身份以开启 Windows Hello')
|
||||||
if (!verifyResult.success) {
|
if (!verifyResult.success) {
|
||||||
showMessage(verifyResult.error || 'Windows Hello 验证失败', false)
|
showMessage(verifyResult.error || 'Windows Hello <EFBFBD><EFBFBD>证失败', false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3814,7 +3573,7 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
onClick={handleSetupHello}
|
onClick={handleSetupHello}
|
||||||
disabled={!helloAvailable || isSettingHello || !authEnabled || !helloPassword}
|
disabled={!helloAvailable || isSettingHello || !authEnabled || !helloPassword}
|
||||||
>
|
>
|
||||||
{isSettingHello ? '配置中...' : '开启与设置'}
|
{isSettingHello ? '<EFBFBD><EFBFBD><EFBFBD>置中...' : '开启与设置'}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -4021,33 +3780,6 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
<span>{tab.label}</span>
|
<span>{tab.label}</span>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
<div className={`tab-group ${aiGroupExpanded ? 'expanded' : ''}`}>
|
|
||||||
<button
|
|
||||||
className={`tab-btn tab-group-trigger ${(activeTab === 'aiCommon' || activeTab === 'insight' || activeTab === 'aiFootprint') ? 'active' : ''}`}
|
|
||||||
onClick={() => setAiGroupExpanded((prev) => !prev)}
|
|
||||||
aria-expanded={aiGroupExpanded}
|
|
||||||
>
|
|
||||||
<Sparkles size={16} />
|
|
||||||
<span>AI 相关</span>
|
|
||||||
<ChevronDown size={14} className={`tab-group-arrow ${aiGroupExpanded ? 'expanded' : ''}`} />
|
|
||||||
</button>
|
|
||||||
<div className={`tab-sublist-wrap ${aiGroupExpanded ? 'expanded' : 'collapsed'}`}>
|
|
||||||
<div className="tab-sublist">
|
|
||||||
{aiTabs.map((tab) => (
|
|
||||||
<button
|
|
||||||
key={tab.id}
|
|
||||||
className={`tab-btn tab-sub-btn ${activeTab === tab.id ? 'active' : ''}`}
|
|
||||||
onClick={() => setActiveTab(tab.id)}
|
|
||||||
tabIndex={aiGroupExpanded ? 0 : -1}
|
|
||||||
>
|
|
||||||
<span className="tab-sub-dot" />
|
|
||||||
<span>{tab.label}</span>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="settings-body">
|
<div className="settings-body">
|
||||||
@@ -4058,9 +3790,7 @@ function SettingsPage({ onClose }: SettingsPageProps = {}) {
|
|||||||
{activeTab === 'models' && renderModelsTab()}
|
{activeTab === 'models' && renderModelsTab()}
|
||||||
{activeTab === 'cache' && renderCacheTab()}
|
{activeTab === 'cache' && renderCacheTab()}
|
||||||
{activeTab === 'api' && renderApiTab()}
|
{activeTab === 'api' && renderApiTab()}
|
||||||
{activeTab === 'aiCommon' && renderAiCommonTab()}
|
|
||||||
{activeTab === 'insight' && renderInsightTab()}
|
{activeTab === 'insight' && renderInsightTab()}
|
||||||
{activeTab === 'aiFootprint' && renderAiFootprintTab()}
|
|
||||||
{activeTab === 'updates' && renderUpdatesTab()}
|
{activeTab === 'updates' && renderUpdatesTab()}
|
||||||
{activeTab === 'analytics' && renderAnalyticsTab()}
|
{activeTab === 'analytics' && renderAnalyticsTab()}
|
||||||
{activeTab === 'security' && renderSecurityTab()}
|
{activeTab === 'security' && renderSecurityTab()}
|
||||||
|
|||||||
@@ -1127,7 +1127,7 @@ export default function SnsPage() {
|
|||||||
activeContactsCountTaskIdRef.current = null
|
activeContactsCountTaskIdRef.current = null
|
||||||
}
|
}
|
||||||
finishBackgroundTask(taskId, 'completed', {
|
finishBackgroundTask(taskId, 'completed', {
|
||||||
detail: '联系人朋友圈条数补算完成',
|
detail: '鑱旂郴浜烘湅鍙嬪湀鏉℃暟琛ョ畻瀹屾垚',
|
||||||
progressText: `${totalTargets}/${totalTargets}`
|
progressText: `${totalTargets}/${totalTargets}`
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ const isMac = navigator.userAgent.toLowerCase().includes('mac')
|
|||||||
const isLinux = navigator.userAgent.toLowerCase().includes('linux')
|
const isLinux = navigator.userAgent.toLowerCase().includes('linux')
|
||||||
const isWindows = !isMac && !isLinux
|
const isWindows = !isMac && !isLinux
|
||||||
|
|
||||||
|
const dbDirName = isMac ? '2.0b4.0.9 目录' : 'xwechat_files 目录'
|
||||||
const DB_PATH_CHINESE_ERROR = '路径包含中文字符,迁移至全英文目录后再试'
|
const DB_PATH_CHINESE_ERROR = '路径包含中文字符,迁移至全英文目录后再试'
|
||||||
const dbPathPlaceholder = isMac
|
const dbPathPlaceholder = isMac
|
||||||
? '例如: ~/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/2.0b4.0.9'
|
? '例如: ~/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/2.0b4.0.9'
|
||||||
@@ -24,7 +25,7 @@ const dbPathPlaceholder = isMac
|
|||||||
|
|
||||||
const steps = [
|
const steps = [
|
||||||
{ id: 'intro', title: '欢迎', desc: '准备开始你的本地数据探索' },
|
{ id: 'intro', title: '欢迎', desc: '准备开始你的本地数据探索' },
|
||||||
{ id: 'db', title: '数据库目录', desc: `定位 xwechat_files 目录` },
|
{ id: 'db', title: '数据库目录', desc: `定位 ${dbDirName}` },
|
||||||
{ id: 'cache', title: '缓存目录', desc: '设置本地缓存存储位置(可选)' },
|
{ id: 'cache', title: '缓存目录', desc: '设置本地缓存存储位置(可选)' },
|
||||||
{ id: 'key', title: '解密密钥', desc: '获取密钥与自动识别账号' },
|
{ id: 'key', title: '解密密钥', desc: '获取密钥与自动识别账号' },
|
||||||
{ id: 'image', title: '图片密钥', desc: '获取 XOR 与 AES 密钥' },
|
{ id: 'image', title: '图片密钥', desc: '获取 XOR 与 AES 密钥' },
|
||||||
|
|||||||
@@ -83,19 +83,6 @@ export const CONFIG_KEYS = {
|
|||||||
ANALYTICS_DENY_COUNT: 'analyticsDenyCount',
|
ANALYTICS_DENY_COUNT: 'analyticsDenyCount',
|
||||||
|
|
||||||
// AI 见解
|
// AI 见解
|
||||||
AI_MODEL_API_BASE_URL: 'aiModelApiBaseUrl',
|
|
||||||
AI_MODEL_API_KEY: 'aiModelApiKey',
|
|
||||||
AI_MODEL_API_MODEL: 'aiModelApiModel',
|
|
||||||
AI_AGENT_MAX_MESSAGES_PER_REQUEST: 'aiAgentMaxMessagesPerRequest',
|
|
||||||
AI_AGENT_MAX_HISTORY_ROUNDS: 'aiAgentMaxHistoryRounds',
|
|
||||||
AI_AGENT_ENABLE_AUTO_SKILL: 'aiAgentEnableAutoSkill',
|
|
||||||
AI_AGENT_SEARCH_CONTEXT_BEFORE: 'aiAgentSearchContextBefore',
|
|
||||||
AI_AGENT_SEARCH_CONTEXT_AFTER: 'aiAgentSearchContextAfter',
|
|
||||||
AI_AGENT_PREPROCESS_CLEAN: 'aiAgentPreprocessClean',
|
|
||||||
AI_AGENT_PREPROCESS_MERGE: 'aiAgentPreprocessMerge',
|
|
||||||
AI_AGENT_PREPROCESS_DENOISE: 'aiAgentPreprocessDenoise',
|
|
||||||
AI_AGENT_PREPROCESS_DESENSITIZE: 'aiAgentPreprocessDesensitize',
|
|
||||||
AI_AGENT_PREPROCESS_ANONYMIZE: 'aiAgentPreprocessAnonymize',
|
|
||||||
AI_INSIGHT_ENABLED: 'aiInsightEnabled',
|
AI_INSIGHT_ENABLED: 'aiInsightEnabled',
|
||||||
AI_INSIGHT_API_BASE_URL: 'aiInsightApiBaseUrl',
|
AI_INSIGHT_API_BASE_URL: 'aiInsightApiBaseUrl',
|
||||||
AI_INSIGHT_API_KEY: 'aiInsightApiKey',
|
AI_INSIGHT_API_KEY: 'aiInsightApiKey',
|
||||||
@@ -110,11 +97,7 @@ export const CONFIG_KEYS = {
|
|||||||
AI_INSIGHT_SYSTEM_PROMPT: 'aiInsightSystemPrompt',
|
AI_INSIGHT_SYSTEM_PROMPT: 'aiInsightSystemPrompt',
|
||||||
AI_INSIGHT_TELEGRAM_ENABLED: 'aiInsightTelegramEnabled',
|
AI_INSIGHT_TELEGRAM_ENABLED: 'aiInsightTelegramEnabled',
|
||||||
AI_INSIGHT_TELEGRAM_TOKEN: 'aiInsightTelegramToken',
|
AI_INSIGHT_TELEGRAM_TOKEN: 'aiInsightTelegramToken',
|
||||||
AI_INSIGHT_TELEGRAM_CHAT_IDS: 'aiInsightTelegramChatIds',
|
AI_INSIGHT_TELEGRAM_CHAT_IDS: 'aiInsightTelegramChatIds'
|
||||||
|
|
||||||
// AI 足迹
|
|
||||||
AI_FOOTPRINT_ENABLED: 'aiFootprintEnabled',
|
|
||||||
AI_FOOTPRINT_SYSTEM_PROMPT: 'aiFootprintSystemPrompt'
|
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
export interface WxidConfig {
|
export interface WxidConfig {
|
||||||
@@ -537,7 +520,7 @@ export async function setExportDefaultTxtColumns(columns: string[]): Promise<voi
|
|||||||
await config.set(CONFIG_KEYS.EXPORT_DEFAULT_TXT_COLUMNS, columns)
|
await config.set(CONFIG_KEYS.EXPORT_DEFAULT_TXT_COLUMNS, columns)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取导出默认并发数
|
// 获取导出默认并发<EFBFBD><EFBFBD>
|
||||||
export async function getExportDefaultConcurrency(): Promise<number | null> {
|
export async function getExportDefaultConcurrency(): Promise<number | null> {
|
||||||
const value = await config.get(CONFIG_KEYS.EXPORT_DEFAULT_CONCURRENCY)
|
const value = await config.get(CONFIG_KEYS.EXPORT_DEFAULT_CONCURRENCY)
|
||||||
if (typeof value === 'number' && Number.isFinite(value)) return value
|
if (typeof value === 'number' && Number.isFinite(value)) return value
|
||||||
@@ -1603,133 +1586,6 @@ export async function setHttpApiHost(host: string): Promise<void> {
|
|||||||
|
|
||||||
// ─── AI 见解 ──────────────────────────────────────────────────────────────────
|
// ─── AI 见解 ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export async function getAiModelApiBaseUrl(): Promise<string> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_MODEL_API_BASE_URL)
|
|
||||||
if (typeof value === 'string' && value.trim()) return value
|
|
||||||
const legacy = await config.get(CONFIG_KEYS.AI_INSIGHT_API_BASE_URL)
|
|
||||||
return typeof legacy === 'string' ? legacy : ''
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiModelApiBaseUrl(url: string): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_MODEL_API_BASE_URL, url)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiModelApiKey(): Promise<string> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_MODEL_API_KEY)
|
|
||||||
if (typeof value === 'string' && value.trim()) return value
|
|
||||||
const legacy = await config.get(CONFIG_KEYS.AI_INSIGHT_API_KEY)
|
|
||||||
return typeof legacy === 'string' ? legacy : ''
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiModelApiKey(key: string): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_MODEL_API_KEY, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiModelApiModel(): Promise<string> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_MODEL_API_MODEL)
|
|
||||||
if (typeof value === 'string' && value.trim()) return value.trim()
|
|
||||||
const legacy = await config.get(CONFIG_KEYS.AI_INSIGHT_API_MODEL)
|
|
||||||
return typeof legacy === 'string' && legacy.trim() ? legacy.trim() : 'gpt-4o-mini'
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiModelApiModel(model: string): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_MODEL_API_MODEL, model)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentMaxMessagesPerRequest(): Promise<number> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_MAX_MESSAGES_PER_REQUEST)
|
|
||||||
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 120
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentMaxMessagesPerRequest(value: number): Promise<void> {
|
|
||||||
const normalized = Number.isFinite(value) ? Math.max(20, Math.min(500, Math.floor(value))) : 120
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_MAX_MESSAGES_PER_REQUEST, normalized)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentMaxHistoryRounds(): Promise<number> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_MAX_HISTORY_ROUNDS)
|
|
||||||
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 12
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentMaxHistoryRounds(value: number): Promise<void> {
|
|
||||||
const normalized = Number.isFinite(value) ? Math.max(4, Math.min(60, Math.floor(value))) : 12
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_MAX_HISTORY_ROUNDS, normalized)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentEnableAutoSkill(): Promise<boolean> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_ENABLE_AUTO_SKILL)
|
|
||||||
return value !== false
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentEnableAutoSkill(enabled: boolean): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_ENABLE_AUTO_SKILL, enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentSearchContextBefore(): Promise<number> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_SEARCH_CONTEXT_BEFORE)
|
|
||||||
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 3
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentSearchContextBefore(value: number): Promise<void> {
|
|
||||||
const normalized = Number.isFinite(value) ? Math.max(0, Math.min(20, Math.floor(value))) : 3
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_SEARCH_CONTEXT_BEFORE, normalized)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentSearchContextAfter(): Promise<number> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_SEARCH_CONTEXT_AFTER)
|
|
||||||
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 3
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentSearchContextAfter(value: number): Promise<void> {
|
|
||||||
const normalized = Number.isFinite(value) ? Math.max(0, Math.min(20, Math.floor(value))) : 3
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_SEARCH_CONTEXT_AFTER, normalized)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentPreprocessClean(): Promise<boolean> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_PREPROCESS_CLEAN)
|
|
||||||
return value !== false
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentPreprocessClean(enabled: boolean): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_PREPROCESS_CLEAN, enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentPreprocessMerge(): Promise<boolean> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_PREPROCESS_MERGE)
|
|
||||||
return value !== false
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentPreprocessMerge(enabled: boolean): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_PREPROCESS_MERGE, enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentPreprocessDenoise(): Promise<boolean> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_PREPROCESS_DENOISE)
|
|
||||||
return value !== false
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentPreprocessDenoise(enabled: boolean): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_PREPROCESS_DENOISE, enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentPreprocessDesensitize(): Promise<boolean> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_PREPROCESS_DESENSITIZE)
|
|
||||||
return value === true
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentPreprocessDesensitize(enabled: boolean): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_PREPROCESS_DESENSITIZE, enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiAgentPreprocessAnonymize(): Promise<boolean> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_AGENT_PREPROCESS_ANONYMIZE)
|
|
||||||
return value === true
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiAgentPreprocessAnonymize(enabled: boolean): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_AGENT_PREPROCESS_ANONYMIZE, enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiInsightEnabled(): Promise<boolean> {
|
export async function getAiInsightEnabled(): Promise<boolean> {
|
||||||
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_ENABLED)
|
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_ENABLED)
|
||||||
return value === true
|
return value === true
|
||||||
@@ -1740,30 +1596,30 @@ export async function setAiInsightEnabled(enabled: boolean): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getAiInsightApiBaseUrl(): Promise<string> {
|
export async function getAiInsightApiBaseUrl(): Promise<string> {
|
||||||
return getAiModelApiBaseUrl()
|
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_API_BASE_URL)
|
||||||
|
return typeof value === 'string' ? value : ''
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setAiInsightApiBaseUrl(url: string): Promise<void> {
|
export async function setAiInsightApiBaseUrl(url: string): Promise<void> {
|
||||||
await config.set(CONFIG_KEYS.AI_INSIGHT_API_BASE_URL, url)
|
await config.set(CONFIG_KEYS.AI_INSIGHT_API_BASE_URL, url)
|
||||||
await setAiModelApiBaseUrl(url)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAiInsightApiKey(): Promise<string> {
|
export async function getAiInsightApiKey(): Promise<string> {
|
||||||
return getAiModelApiKey()
|
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_API_KEY)
|
||||||
|
return typeof value === 'string' ? value : ''
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setAiInsightApiKey(key: string): Promise<void> {
|
export async function setAiInsightApiKey(key: string): Promise<void> {
|
||||||
await config.set(CONFIG_KEYS.AI_INSIGHT_API_KEY, key)
|
await config.set(CONFIG_KEYS.AI_INSIGHT_API_KEY, key)
|
||||||
await setAiModelApiKey(key)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAiInsightApiModel(): Promise<string> {
|
export async function getAiInsightApiModel(): Promise<string> {
|
||||||
return getAiModelApiModel()
|
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_API_MODEL)
|
||||||
|
return typeof value === 'string' && value.trim() ? value.trim() : 'gpt-4o-mini'
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setAiInsightApiModel(model: string): Promise<void> {
|
export async function setAiInsightApiModel(model: string): Promise<void> {
|
||||||
await config.set(CONFIG_KEYS.AI_INSIGHT_API_MODEL, model)
|
await config.set(CONFIG_KEYS.AI_INSIGHT_API_MODEL, model)
|
||||||
await setAiModelApiModel(model)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAiInsightSilenceDays(): Promise<number> {
|
export async function getAiInsightSilenceDays(): Promise<number> {
|
||||||
@@ -1864,21 +1720,3 @@ export async function getAiInsightTelegramChatIds(): Promise<string> {
|
|||||||
export async function setAiInsightTelegramChatIds(chatIds: string): Promise<void> {
|
export async function setAiInsightTelegramChatIds(chatIds: string): Promise<void> {
|
||||||
await config.set(CONFIG_KEYS.AI_INSIGHT_TELEGRAM_CHAT_IDS, chatIds)
|
await config.set(CONFIG_KEYS.AI_INSIGHT_TELEGRAM_CHAT_IDS, chatIds)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAiFootprintEnabled(): Promise<boolean> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_FOOTPRINT_ENABLED)
|
|
||||||
return value === true
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiFootprintEnabled(enabled: boolean): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_FOOTPRINT_ENABLED, enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAiFootprintSystemPrompt(): Promise<string> {
|
|
||||||
const value = await config.get(CONFIG_KEYS.AI_FOOTPRINT_SYSTEM_PROMPT)
|
|
||||||
return typeof value === 'string' ? value : ''
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setAiFootprintSystemPrompt(prompt: string): Promise<void> {
|
|
||||||
await config.set(CONFIG_KEYS.AI_FOOTPRINT_SYSTEM_PROMPT, prompt)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
import { create } from 'zustand'
|
|
||||||
import type { AgentStreamChunk } from '../types/electron'
|
|
||||||
|
|
||||||
interface ConversationRuntimeState {
|
|
||||||
draft: string
|
|
||||||
chunks: AgentStreamChunk[]
|
|
||||||
running: boolean
|
|
||||||
updatedAt: number
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AiRuntimeStoreState {
|
|
||||||
activeRunId: string
|
|
||||||
states: Record<string, ConversationRuntimeState>
|
|
||||||
startRun: (conversationId: string, runId: string) => void
|
|
||||||
appendChunk: (conversationId: string, chunk: AgentStreamChunk) => void
|
|
||||||
finishRun: (conversationId: string) => void
|
|
||||||
clearConversation: (conversationId: string) => void
|
|
||||||
}
|
|
||||||
|
|
||||||
function nextConversationState(previous?: ConversationRuntimeState): ConversationRuntimeState {
|
|
||||||
return previous || {
|
|
||||||
draft: '',
|
|
||||||
chunks: [],
|
|
||||||
running: false,
|
|
||||||
updatedAt: Date.now()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const useAiRuntimeStore = create<AiRuntimeStoreState>((set) => ({
|
|
||||||
activeRunId: '',
|
|
||||||
states: {},
|
|
||||||
startRun: (conversationId, runId) => set((state) => {
|
|
||||||
const prev = nextConversationState(state.states[conversationId])
|
|
||||||
return {
|
|
||||||
activeRunId: runId,
|
|
||||||
states: {
|
|
||||||
...state.states,
|
|
||||||
[conversationId]: {
|
|
||||||
...prev,
|
|
||||||
draft: '',
|
|
||||||
chunks: [],
|
|
||||||
running: true,
|
|
||||||
updatedAt: Date.now()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
appendChunk: (conversationId, chunk) => set((state) => {
|
|
||||||
const prev = nextConversationState(state.states[conversationId])
|
|
||||||
const nextDraft = chunk.type === 'content'
|
|
||||||
? `${prev.draft}${chunk.content || ''}`
|
|
||||||
: prev.draft
|
|
||||||
return {
|
|
||||||
states: {
|
|
||||||
...state.states,
|
|
||||||
[conversationId]: {
|
|
||||||
...prev,
|
|
||||||
draft: nextDraft,
|
|
||||||
chunks: [...prev.chunks, chunk].slice(-300),
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
running: chunk.type === 'done' || chunk.isFinished ? false : prev.running
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
finishRun: (conversationId) => set((state) => {
|
|
||||||
const prev = state.states[conversationId]
|
|
||||||
if (!prev) return state
|
|
||||||
return {
|
|
||||||
activeRunId: '',
|
|
||||||
states: {
|
|
||||||
...state.states,
|
|
||||||
[conversationId]: {
|
|
||||||
...prev,
|
|
||||||
draft: '',
|
|
||||||
running: false,
|
|
||||||
updatedAt: Date.now()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
clearConversation: (conversationId) => set((state) => {
|
|
||||||
const next = { ...state.states }
|
|
||||||
delete next[conversationId]
|
|
||||||
return { states: next }
|
|
||||||
})
|
|
||||||
}))
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
import type { AgentStreamChunk } from './electron'
|
|
||||||
|
|
||||||
export type AiToolCategory = 'core' | 'analysis'
|
|
||||||
|
|
||||||
export interface AiConversation {
|
|
||||||
conversationId: string
|
|
||||||
title: string
|
|
||||||
createdAt: number
|
|
||||||
updatedAt: number
|
|
||||||
lastMessageAt: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AiMessageRecord {
|
|
||||||
messageId: string
|
|
||||||
conversationId: string
|
|
||||||
role: 'user' | 'assistant' | 'system' | 'tool' | string
|
|
||||||
content: string
|
|
||||||
intentType: string
|
|
||||||
components: any[]
|
|
||||||
toolTrace: any[]
|
|
||||||
usage?: {
|
|
||||||
promptTokens?: number
|
|
||||||
completionTokens?: number
|
|
||||||
totalTokens?: number
|
|
||||||
}
|
|
||||||
error?: string
|
|
||||||
parentMessageId?: string
|
|
||||||
createdAt: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ToolCatalogEntry {
|
|
||||||
name: string
|
|
||||||
category: AiToolCategory
|
|
||||||
description: string
|
|
||||||
parameters: Record<string, unknown>
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AssistantSummary {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
systemPrompt: string
|
|
||||||
presetQuestions: string[]
|
|
||||||
allowedBuiltinTools?: string[]
|
|
||||||
builtinId?: string
|
|
||||||
applicableChatTypes?: Array<'group' | 'private'>
|
|
||||||
supportedLocales?: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SkillSummary {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
description: string
|
|
||||||
tags: string[]
|
|
||||||
chatScope: 'all' | 'group' | 'private'
|
|
||||||
tools: string[]
|
|
||||||
builtinId?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SqlSchemaTable {
|
|
||||||
name: string
|
|
||||||
columns: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SqlSchemaSource {
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path: string | null
|
|
||||||
label: string
|
|
||||||
tables: SqlSchemaTable[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SqlSchemaPayload {
|
|
||||||
generatedAt: number
|
|
||||||
sources: SqlSchemaSource[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SqlResultPayload {
|
|
||||||
rows: Record<string, unknown>[]
|
|
||||||
columns: string[]
|
|
||||||
total: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ConversationRuntimeView {
|
|
||||||
draft: string
|
|
||||||
chunks: AgentStreamChunk[]
|
|
||||||
running: boolean
|
|
||||||
updatedAt: number
|
|
||||||
}
|
|
||||||
|
|
||||||
408
src/types/electron.d.ts
vendored
408
src/types/electron.d.ts
vendored
@@ -7,37 +7,6 @@ export interface SessionChatWindowOpenOptions {
|
|||||||
initialContactType?: ContactInfo['type']
|
initialContactType?: ContactInfo['type']
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TokenUsage {
|
|
||||||
promptTokens?: number
|
|
||||||
completionTokens?: number
|
|
||||||
totalTokens?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AgentRuntimeStatus {
|
|
||||||
phase: 'idle' | 'thinking' | 'tool_running' | 'responding' | 'completed' | 'error' | 'aborted'
|
|
||||||
round?: number
|
|
||||||
currentTool?: string
|
|
||||||
toolsUsed?: number
|
|
||||||
updatedAt: number
|
|
||||||
totalUsage?: TokenUsage
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AgentStreamChunk {
|
|
||||||
runId: string
|
|
||||||
conversationId?: string
|
|
||||||
type: 'content' | 'think' | 'tool_start' | 'tool_result' | 'status' | 'done' | 'error'
|
|
||||||
content?: string
|
|
||||||
thinkTag?: string
|
|
||||||
thinkDurationMs?: number
|
|
||||||
toolName?: string
|
|
||||||
toolParams?: Record<string, unknown>
|
|
||||||
toolResult?: unknown
|
|
||||||
error?: string
|
|
||||||
isFinished?: boolean
|
|
||||||
usage?: TokenUsage
|
|
||||||
status?: AgentRuntimeStatus
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ElectronAPI {
|
export interface ElectronAPI {
|
||||||
window: {
|
window: {
|
||||||
minimize: () => void
|
minimize: () => void
|
||||||
@@ -424,121 +393,6 @@ export interface ElectronAPI {
|
|||||||
getVoiceTranscript: (sessionId: string, msgId: string, createTime?: number) => Promise<{ success: boolean; transcript?: string; error?: string }>
|
getVoiceTranscript: (sessionId: string, msgId: string, createTime?: number) => Promise<{ success: boolean; transcript?: string; error?: string }>
|
||||||
onVoiceTranscriptPartial: (callback: (payload: { sessionId?: string; msgId: string; createTime?: number; text: string }) => void) => () => void
|
onVoiceTranscriptPartial: (callback: (payload: { sessionId?: string; msgId: string; createTime?: number; text: string }) => void) => () => void
|
||||||
getMessage: (sessionId: string, localId: number) => Promise<{ success: boolean; message?: Message; error?: string }>
|
getMessage: (sessionId: string, localId: number) => Promise<{ success: boolean; message?: Message; error?: string }>
|
||||||
getMyFootprintStats: (
|
|
||||||
beginTimestamp: number,
|
|
||||||
endTimestamp: number,
|
|
||||||
options?: {
|
|
||||||
myWxid?: string
|
|
||||||
privateSessionIds?: string[]
|
|
||||||
groupSessionIds?: string[]
|
|
||||||
mentionLimit?: number
|
|
||||||
privateLimit?: number
|
|
||||||
mentionMode?: 'text_at_me' | string
|
|
||||||
}
|
|
||||||
) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
data?: {
|
|
||||||
summary: {
|
|
||||||
private_inbound_people: number
|
|
||||||
private_replied_people: number
|
|
||||||
private_outbound_people: number
|
|
||||||
private_reply_rate: number
|
|
||||||
mention_count: number
|
|
||||||
mention_group_count: number
|
|
||||||
}
|
|
||||||
private_sessions: Array<{
|
|
||||||
session_id: string
|
|
||||||
incoming_count: number
|
|
||||||
outgoing_count: number
|
|
||||||
replied: boolean
|
|
||||||
first_incoming_ts: number
|
|
||||||
first_reply_ts: number
|
|
||||||
latest_ts: number
|
|
||||||
anchor_local_id: number
|
|
||||||
anchor_create_time: number
|
|
||||||
displayName?: string
|
|
||||||
avatarUrl?: string
|
|
||||||
}>
|
|
||||||
private_segments: Array<{
|
|
||||||
session_id: string
|
|
||||||
segment_index: number
|
|
||||||
start_ts: number
|
|
||||||
end_ts: number
|
|
||||||
duration_sec: number
|
|
||||||
incoming_count: number
|
|
||||||
outgoing_count: number
|
|
||||||
message_count: number
|
|
||||||
replied: boolean
|
|
||||||
first_incoming_ts: number
|
|
||||||
first_reply_ts: number
|
|
||||||
latest_ts: number
|
|
||||||
anchor_local_id: number
|
|
||||||
anchor_create_time: number
|
|
||||||
displayName?: string
|
|
||||||
avatarUrl?: string
|
|
||||||
}>
|
|
||||||
mentions: Array<{
|
|
||||||
session_id: string
|
|
||||||
local_id: number
|
|
||||||
create_time: number
|
|
||||||
sender_username: string
|
|
||||||
message_content: string
|
|
||||||
source: string
|
|
||||||
sessionDisplayName?: string
|
|
||||||
senderDisplayName?: string
|
|
||||||
senderAvatarUrl?: string
|
|
||||||
}>
|
|
||||||
mention_groups: Array<{
|
|
||||||
session_id: string
|
|
||||||
count: number
|
|
||||||
latest_ts: number
|
|
||||||
displayName?: string
|
|
||||||
avatarUrl?: string
|
|
||||||
}>
|
|
||||||
diagnostics: {
|
|
||||||
truncated: boolean
|
|
||||||
scanned_dbs: number
|
|
||||||
elapsed_ms: number
|
|
||||||
}
|
|
||||||
}
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
exportMyFootprint: (
|
|
||||||
beginTimestamp: number,
|
|
||||||
endTimestamp: number,
|
|
||||||
format: 'csv' | 'json',
|
|
||||||
filePath: string
|
|
||||||
) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
filePath?: string
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
getSchema: (payload?: { sessionId?: string }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
schema?: {
|
|
||||||
generatedAt: number
|
|
||||||
sources: Array<{
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path: string | null
|
|
||||||
label: string
|
|
||||||
tables: Array<{ name: string; columns: string[] }>
|
|
||||||
}>
|
|
||||||
}
|
|
||||||
schemaText?: string
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
executeSQL: (payload: {
|
|
||||||
kind: 'message' | 'contact' | 'biz'
|
|
||||||
path?: string | null
|
|
||||||
sql: string
|
|
||||||
limit?: number
|
|
||||||
}) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
rows?: Record<string, unknown>[]
|
|
||||||
columns?: string[]
|
|
||||||
total?: number
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
onWcdbChange: (callback: (event: any, data: { type: string; json: string }) => void) => () => void
|
onWcdbChange: (callback: (event: any, data: { type: string; json: string }) => void) => () => void
|
||||||
}
|
}
|
||||||
biz: {
|
biz: {
|
||||||
@@ -1132,263 +986,6 @@ export interface ElectronAPI {
|
|||||||
stop: () => Promise<{ success: boolean }>
|
stop: () => Promise<{ success: boolean }>
|
||||||
status: () => Promise<{ running: boolean; port: number; mediaExportPath: string }>
|
status: () => Promise<{ running: boolean; port: number; mediaExportPath: string }>
|
||||||
}
|
}
|
||||||
insight: {
|
|
||||||
testConnection: () => Promise<{ success: boolean; message: string }>
|
|
||||||
getTodayStats: () => Promise<Array<{ sessionId: string; count: number; times: string[] }>>
|
|
||||||
triggerTest: () => Promise<{ success: boolean; message: string }>
|
|
||||||
generateFootprintInsight: (payload: {
|
|
||||||
rangeLabel: string
|
|
||||||
summary: {
|
|
||||||
private_inbound_people?: number
|
|
||||||
private_replied_people?: number
|
|
||||||
private_outbound_people?: number
|
|
||||||
private_reply_rate?: number
|
|
||||||
mention_count?: number
|
|
||||||
mention_group_count?: number
|
|
||||||
}
|
|
||||||
privateSegments?: Array<{ displayName?: string; session_id?: string; incoming_count?: number; outgoing_count?: number; message_count?: number; replied?: boolean }>
|
|
||||||
mentionGroups?: Array<{ displayName?: string; session_id?: string; count?: number }>
|
|
||||||
}) => Promise<{ success: boolean; message: string; insight?: string }>
|
|
||||||
}
|
|
||||||
aiApi: {
|
|
||||||
listConversations: (payload?: { page?: number; pageSize?: number }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
conversations?: Array<{
|
|
||||||
conversationId: string
|
|
||||||
title: string
|
|
||||||
createdAt: number
|
|
||||||
updatedAt: number
|
|
||||||
lastMessageAt: number
|
|
||||||
}>
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
createConversation: (payload?: { title?: string }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
conversationId?: string
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
renameConversation: (payload: { conversationId: string; title: string }) => Promise<{ success: boolean; error?: string }>
|
|
||||||
deleteConversation: (conversationId: string) => Promise<{ success: boolean; error?: string }>
|
|
||||||
listMessages: (payload: { conversationId: string; limit?: number }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
messages?: Array<{
|
|
||||||
messageId: string
|
|
||||||
conversationId: string
|
|
||||||
role: 'user' | 'assistant' | 'system' | 'tool' | string
|
|
||||||
content: string
|
|
||||||
intentType: string
|
|
||||||
components: any[]
|
|
||||||
toolTrace: any[]
|
|
||||||
usage: Record<string, unknown>
|
|
||||||
error: string
|
|
||||||
parentMessageId: string
|
|
||||||
createdAt: number
|
|
||||||
}>
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
exportConversation: (payload: { conversationId: string }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
conversation?: { conversationId: string; title: string; updatedAt: number }
|
|
||||||
markdown?: string
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
getToolCatalog: () => Promise<Array<{
|
|
||||||
name: string
|
|
||||||
category: 'core' | 'analysis'
|
|
||||||
description: string
|
|
||||||
parameters: Record<string, unknown>
|
|
||||||
}>>
|
|
||||||
executeTool: (payload: { name: string; args?: Record<string, any> }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
result?: unknown
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
cancelToolTest: (payload?: { taskId?: string }) => Promise<{ success: boolean }>
|
|
||||||
}
|
|
||||||
agentApi: {
|
|
||||||
runStream: (payload: {
|
|
||||||
mode?: 'chat' | 'sql'
|
|
||||||
conversationId?: string
|
|
||||||
userInput: string
|
|
||||||
assistantId?: string
|
|
||||||
activeSkillId?: string
|
|
||||||
chatScope?: 'group' | 'private'
|
|
||||||
sqlContext?: { schemaText?: string; targetHint?: string }
|
|
||||||
}) => Promise<{ success: boolean; runId: string }>
|
|
||||||
abort: (payload: { runId?: string; conversationId?: string }) => Promise<{ success: boolean }>
|
|
||||||
onStream: (callback: (payload: AgentStreamChunk) => void) => () => void
|
|
||||||
}
|
|
||||||
assistantApi: {
|
|
||||||
getAll: () => Promise<Array<{
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
systemPrompt: string
|
|
||||||
presetQuestions: string[]
|
|
||||||
allowedBuiltinTools?: string[]
|
|
||||||
builtinId?: string
|
|
||||||
applicableChatTypes?: Array<'group' | 'private'>
|
|
||||||
supportedLocales?: string[]
|
|
||||||
}>>
|
|
||||||
getConfig: (id: string) => Promise<{
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
systemPrompt: string
|
|
||||||
presetQuestions: string[]
|
|
||||||
allowedBuiltinTools?: string[]
|
|
||||||
builtinId?: string
|
|
||||||
applicableChatTypes?: Array<'group' | 'private'>
|
|
||||||
supportedLocales?: string[]
|
|
||||||
} | null>
|
|
||||||
create: (payload: any) => Promise<{ success: boolean; id?: string; error?: string }>
|
|
||||||
update: (payload: { id: string; updates: any }) => Promise<{ success: boolean; error?: string }>
|
|
||||||
delete: (id: string) => Promise<{ success: boolean; error?: string }>
|
|
||||||
reset: (id: string) => Promise<{ success: boolean; error?: string }>
|
|
||||||
getBuiltinCatalog: () => Promise<Array<{
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
systemPrompt: string
|
|
||||||
applicableChatTypes?: Array<'group' | 'private'>
|
|
||||||
supportedLocales?: string[]
|
|
||||||
imported: boolean
|
|
||||||
}>>
|
|
||||||
getBuiltinToolCatalog: () => Promise<Array<{ name: string; category: 'core' | 'analysis' }>>
|
|
||||||
importFromMd: (rawMd: string) => Promise<{ success: boolean; id?: string; error?: string }>
|
|
||||||
}
|
|
||||||
skillApi: {
|
|
||||||
getAll: () => Promise<Array<{
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
description: string
|
|
||||||
tags: string[]
|
|
||||||
chatScope: 'all' | 'group' | 'private'
|
|
||||||
tools: string[]
|
|
||||||
builtinId?: string
|
|
||||||
}>>
|
|
||||||
getConfig: (id: string) => Promise<{
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
description: string
|
|
||||||
tags: string[]
|
|
||||||
chatScope: 'all' | 'group' | 'private'
|
|
||||||
tools: string[]
|
|
||||||
prompt: string
|
|
||||||
builtinId?: string
|
|
||||||
} | null>
|
|
||||||
create: (rawMd: string) => Promise<{ success: boolean; id?: string; error?: string }>
|
|
||||||
update: (payload: { id: string; rawMd: string }) => Promise<{ success: boolean; error?: string }>
|
|
||||||
delete: (id: string) => Promise<{ success: boolean; error?: string }>
|
|
||||||
getBuiltinCatalog: () => Promise<Array<{
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
description: string
|
|
||||||
tags: string[]
|
|
||||||
chatScope: 'all' | 'group' | 'private'
|
|
||||||
tools: string[]
|
|
||||||
imported: boolean
|
|
||||||
}>>
|
|
||||||
importFromMd: (rawMd: string) => Promise<{ success: boolean; id?: string; error?: string }>
|
|
||||||
}
|
|
||||||
llmApi: {
|
|
||||||
getConfig: () => Promise<{ success: boolean; config: { apiBaseUrl: string; apiKey: string; model: string } }>
|
|
||||||
setConfig: (payload: { apiBaseUrl?: string; apiKey?: string; model?: string }) => Promise<{ success: boolean }>
|
|
||||||
listModels: () => Promise<{ success: boolean; models: Array<{ id: string; label: string }> }>
|
|
||||||
}
|
|
||||||
aiAnalysis: {
|
|
||||||
listConversations: (payload?: { page?: number; pageSize?: number }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
conversations?: Array<{
|
|
||||||
conversationId: string
|
|
||||||
title: string
|
|
||||||
createdAt: number
|
|
||||||
updatedAt: number
|
|
||||||
lastMessageAt: number
|
|
||||||
}>
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
createConversation: (payload?: { title?: string }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
conversationId?: string
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
deleteConversation: (conversationId: string) => Promise<{ success: boolean; error?: string }>
|
|
||||||
listMessages: (payload: { conversationId: string; limit?: number }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
messages?: Array<{
|
|
||||||
messageId: string
|
|
||||||
conversationId: string
|
|
||||||
role: 'user' | 'assistant' | 'system' | 'tool' | string
|
|
||||||
content: string
|
|
||||||
intentType: string
|
|
||||||
components: any[]
|
|
||||||
toolTrace: any[]
|
|
||||||
usage: Record<string, unknown>
|
|
||||||
error: string
|
|
||||||
parentMessageId: string
|
|
||||||
createdAt: number
|
|
||||||
}>
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
sendMessage: (payload: {
|
|
||||||
conversationId: string
|
|
||||||
userInput: string
|
|
||||||
options?: {
|
|
||||||
parentMessageId?: string
|
|
||||||
persistUserMessage?: boolean
|
|
||||||
assistantId?: string
|
|
||||||
activeSkillId?: string
|
|
||||||
chatScope?: 'group' | 'private'
|
|
||||||
}
|
|
||||||
}) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
result?: {
|
|
||||||
conversationId: string
|
|
||||||
messageId: string
|
|
||||||
assistantText: string
|
|
||||||
components: any[]
|
|
||||||
toolTrace: any[]
|
|
||||||
usage?: {
|
|
||||||
promptTokens?: number
|
|
||||||
completionTokens?: number
|
|
||||||
totalTokens?: number
|
|
||||||
}
|
|
||||||
error?: string
|
|
||||||
createdAt: number
|
|
||||||
}
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
retryMessage: (payload: { conversationId: string; userMessageId?: string }) => Promise<{
|
|
||||||
success: boolean
|
|
||||||
result?: {
|
|
||||||
conversationId: string
|
|
||||||
messageId: string
|
|
||||||
assistantText: string
|
|
||||||
components: any[]
|
|
||||||
toolTrace: any[]
|
|
||||||
usage?: {
|
|
||||||
promptTokens?: number
|
|
||||||
completionTokens?: number
|
|
||||||
totalTokens?: number
|
|
||||||
}
|
|
||||||
error?: string
|
|
||||||
createdAt: number
|
|
||||||
}
|
|
||||||
error?: string
|
|
||||||
}>
|
|
||||||
abortRun: (payload: { runId?: string; conversationId?: string }) => Promise<{ success: boolean }>
|
|
||||||
onRunEvent: (callback: (payload: {
|
|
||||||
runId: string
|
|
||||||
conversationId: string
|
|
||||||
stage: string
|
|
||||||
ts: number
|
|
||||||
message: string
|
|
||||||
intent?: string
|
|
||||||
round?: number
|
|
||||||
toolName?: string
|
|
||||||
status?: string
|
|
||||||
durationMs?: number
|
|
||||||
data?: Record<string, unknown>
|
|
||||||
}) => void) => () => void
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExportOptions {
|
export interface ExportOptions {
|
||||||
@@ -1445,11 +1042,6 @@ export interface WxidInfo {
|
|||||||
declare global {
|
declare global {
|
||||||
interface Window {
|
interface Window {
|
||||||
electronAPI: ElectronAPI
|
electronAPI: ElectronAPI
|
||||||
aiApi: ElectronAPI['aiApi']
|
|
||||||
agentApi: ElectronAPI['agentApi']
|
|
||||||
assistantApi: ElectronAPI['assistantApi']
|
|
||||||
skillApi: ElectronAPI['skillApi']
|
|
||||||
llmApi: ElectronAPI['llmApi']
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Electron 类型声明
|
// Electron 类型声明
|
||||||
|
|||||||
Reference in New Issue
Block a user