Skip to content

Commit 424f56d

Browse files
authored
Merge pull request #25 from beersoccer/feature/session-memory
refactor: update branch naming in plugin publish workflow
2 parents b3d0e70 + 40d89c6 commit 424f56d

21 files changed

Lines changed: 239 additions & 89 deletions

.github/workflows/plugin-publish.yml

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -26,74 +26,75 @@ jobs:
2626
wget -q https://github.com/langgenius/dify-plugin-daemon/releases/latest/download/dify-plugin-linux-amd64
2727
chmod +x dify-plugin-linux-amd64
2828
29-
- name: Get plugin info from manifest
30-
id: get_info
29+
- name: Get basic info from manifest
30+
id: get_basic_info
3131
run: |
3232
PLUGIN_NAME=$(grep "^name:" manifest.yaml | cut -d' ' -f2)
33-
VERSION=$(grep "^version:" manifest.yaml | cut -d' ' -f2)
34-
AUTHOR=$(grep "^author:" manifest.yaml | cut -d' ' -f2)
35-
33+
echo "Plugin name: $PLUGIN_NAME"
3634
echo "plugin_name=$PLUGIN_NAME" >> $GITHUB_OUTPUT
35+
36+
VERSION=$(grep "^version:" manifest.yaml | cut -d' ' -f2)
37+
echo "Plugin version: $VERSION"
3738
echo "version=$VERSION" >> $GITHUB_OUTPUT
39+
40+
AUTHOR=$(grep "^author:" manifest.yaml | cut -d' ' -f2)
41+
echo "Plugin author: $AUTHOR"
3842
echo "author=$AUTHOR" >> $GITHUB_OUTPUT
39-
40-
echo "Plugin: $PLUGIN_NAME v$VERSION (Author: $AUTHOR)"
4143
42-
- name: Package plugin
44+
- name: Package Plugin
4345
id: package
4446
run: |
45-
PACKAGE_NAME="${{ steps.get_info.outputs.plugin_name }}-${{ steps.get_info.outputs.version }}.difypkg"
47+
cd $GITHUB_WORKSPACE
48+
PACKAGE_NAME="${{ steps.get_basic_info.outputs.plugin_name }}-${{ steps.get_basic_info.outputs.version }}.difypkg"
4649
$RUNNER_TEMP/bin/dify-plugin-linux-amd64 plugin package . -o "$PACKAGE_NAME"
4750
echo "package_name=$PACKAGE_NAME" >> $GITHUB_OUTPUT
48-
echo "Package created: $PACKAGE_NAME"
4951
5052
- name: Checkout target repo
5153
uses: actions/checkout@v4
5254
with:
53-
repository: ${{ steps.get_info.outputs.author }}/dify-plugins
55+
repository: ${{ steps.get_basic_info.outputs.author }}/dify-plugins
5456
path: dify-plugins
5557
token: ${{ secrets.PLUGIN_ACTION }}
5658
fetch-depth: 1
59+
persist-credentials: true
5760

58-
- name: Prepare and push changes
61+
- name: Prepare and create PR
5962
run: |
63+
PACKAGE_NAME="${{ steps.get_basic_info.outputs.plugin_name }}-${{ steps.get_basic_info.outputs.version }}.difypkg"
64+
mkdir -p dify-plugins/${{ steps.get_basic_info.outputs.author }}/${{ steps.get_basic_info.outputs.plugin_name }}
65+
mv "$PACKAGE_NAME" dify-plugins/${{ steps.get_basic_info.outputs.author }}/${{ steps.get_basic_info.outputs.plugin_name }}/
66+
6067
cd dify-plugins
61-
62-
# Configure git
68+
6369
git config user.name "GitHub Actions"
6470
git config user.email "actions@github.com"
65-
66-
# Ensure we are on the latest main branch
71+
6772
git fetch origin main
6873
git checkout main
6974
git pull origin main
70-
71-
# Create branch
72-
BRANCH_NAME="bump-${{ steps.get_info.outputs.plugin_name }}-${{ steps.get_info.outputs.version }}"
75+
76+
BRANCH_NAME="bump-${{ steps.get_basic_info.outputs.plugin_name }}-plugin-${{ steps.get_basic_info.outputs.version }}"
7377
git checkout -b "$BRANCH_NAME"
74-
75-
# Copy package file
76-
mkdir -p ${{ steps.get_info.outputs.author }}/${{ steps.get_info.outputs.plugin_name }}
77-
cp "$GITHUB_WORKSPACE/${{ steps.package.outputs.package_name }}" \
78-
"${{ steps.get_info.outputs.author }}/${{ steps.get_info.outputs.plugin_name }}/"
79-
80-
# Commit and push
78+
8179
git add .
82-
git commit -m "bump ${{ steps.get_info.outputs.plugin_name }} to version ${{ steps.get_info.outputs.version }}"
80+
git commit -m "bump ${{ steps.get_basic_info.outputs.plugin_name }} plugin to version ${{ steps.get_basic_info.outputs.version }}"
81+
8382
git push -u origin "$BRANCH_NAME" --force
8483
85-
- name: Create pull request
84+
echo "Waiting for branch to sync..."
85+
sleep 10
86+
87+
- name: Create PR via GitHub API
8688
env:
8789
GH_TOKEN: ${{ secrets.PLUGIN_ACTION }}
8890
run: |
89-
cd dify-plugins
90-
91-
BRANCH_NAME="bump-${{ steps.get_info.outputs.plugin_name }}-${{ steps.get_info.outputs.version }}"
92-
91+
BRANCH_NAME="bump-${{ steps.get_basic_info.outputs.plugin_name }}-plugin-${{ steps.get_basic_info.outputs.version }}"
9392
gh pr create \
9493
--repo langgenius/dify-plugins \
95-
--head "${{ steps.get_info.outputs.author }}:$BRANCH_NAME" \
94+
--head "${{ steps.get_basic_info.outputs.author }}:$BRANCH_NAME" \
9695
--base main \
97-
--title "bump ${{ steps.get_info.outputs.plugin_name }} to version ${{ steps.get_info.outputs.version }}" \
98-
--body "Automated release: bump ${{ steps.get_info.outputs.plugin_name }} plugin to version ${{ steps.get_info.outputs.version }}" \
99-
|| echo "PR may already exist"
96+
--title "bump ${{ steps.get_basic_info.outputs.plugin_name }} plugin to version ${{ steps.get_basic_info.outputs.version }}" \
97+
--body "bump ${{ steps.get_basic_info.outputs.plugin_name }} plugin package to version ${{ steps.get_basic_info.outputs.version }}
98+
99+
Changes:
100+
- Updated plugin package file" || echo "PR already exists or creation skipped."

main.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
os.environ.setdefault("DIFY_PLUGIN_RUNTIME", "1")
1717

1818
from dify_plugin import DifyPluginEnv, Plugin
19+
1920
from utils.background_loop import BackgroundEventLoop
2021
from utils.constants import MAX_REQUEST_TIMEOUT
2122
from utils.logger import get_logger

tests/e2e/cleanup_test_memories.py

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
"""清理测试记忆数据
2+
3+
运行此脚本以清理之前测试创建的记忆,避免重复内容导致 Mem0 返回 NONE。
4+
5+
使用方法:
6+
cd tests/e2e
7+
python cleanup_test_memories.py
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import sys
13+
from pathlib import Path
14+
15+
# Add project root to path
16+
project_root = Path(__file__).parent.parent.parent
17+
sys.path.insert(0, str(project_root))
18+
19+
from utils.mem0_client import get_sync_client
20+
21+
22+
def load_env_config() -> dict[str, str]:
23+
"""从.env文件加载配置"""
24+
# .env 文件应该在 tests/.env,而不是 tests/e2e/.env
25+
env_file = Path(__file__).parent.parent / ".env"
26+
27+
if not env_file.exists():
28+
print(f"❌ 未找到 .env 文件: {env_file}")
29+
print("请创建 tests/.env 文件并配置以下变量:")
30+
print("MEM0_LLM_CONFIG, MEM0_EMBEDDER_CONFIG, MEM0_VECTOR_DB_CONFIG")
31+
sys.exit(1)
32+
33+
env_vars: dict[str, str] = {}
34+
with env_file.open() as f:
35+
for line in f:
36+
line = line.strip()
37+
if not line or line.startswith("#"):
38+
continue
39+
if "=" not in line:
40+
continue
41+
key, _, value = line.partition("=")
42+
# 去除单引号和双引号包裹
43+
value = value.strip().strip('"').strip("'")
44+
env_vars[key.strip()] = value
45+
46+
print(f"✓ 已加载环境变量: {env_file}")
47+
return env_vars
48+
49+
50+
def cleanup_test_memories():
51+
"""删除测试用户的所有记忆"""
52+
print("\n" + "="*80)
53+
print("清理测试记忆数据")
54+
print("="*80)
55+
56+
# Load environment config
57+
env_config = load_env_config()
58+
59+
# Build credentials from environment
60+
credentials = {
61+
"local_llm_json_secret": env_config.get("MEM0_LLM_CONFIG", ""),
62+
"local_embedder_json_secret": env_config.get("MEM0_EMBEDDER_CONFIG", ""),
63+
"local_vector_db_json_secret": env_config.get("MEM0_VECTOR_DB_CONFIG", ""),
64+
"local_graph_db_json_secret": env_config.get("MEM0_GRAPH_DB_CONFIG", ""),
65+
"local_reranker_json_secret": env_config.get("MEM0_RERANKER_CONFIG", ""),
66+
}
67+
68+
# Validate required configs
69+
required_keys = ["MEM0_LLM_CONFIG", "MEM0_EMBEDDER_CONFIG", "MEM0_VECTOR_DB_CONFIG"]
70+
missing = [key for key in required_keys if not env_config.get(key)]
71+
if missing:
72+
print(f"❌ 缺少必需的配置: {missing}")
73+
sys.exit(1)
74+
75+
# Build mem0 client
76+
try:
77+
client = get_sync_client(credentials)
78+
print("✓ Mem0 客户端已初始化")
79+
except Exception as e:
80+
print(f"❌ 无法初始化 Mem0 客户端: {e}")
81+
sys.exit(1)
82+
83+
# Test user IDs
84+
test_users = ["real_user", "test_user"]
85+
86+
total_deleted = 0
87+
for user_id in test_users:
88+
print(f"\n清理用户: {user_id}")
89+
try:
90+
# Use delete_all to delete all memories for this user
91+
result = client.delete_all({"user_id": user_id})
92+
93+
# Extract deleted count from result if available
94+
deleted_count = 0
95+
if isinstance(result, dict):
96+
deleted_count = result.get("deleted_count", result.get("count", 0))
97+
if deleted_count == 0 and "message" in result:
98+
# If no explicit count, check if operation succeeded
99+
print(f" ✓ {result.get('message', '删除操作已完成')}")
100+
else:
101+
print(f" ✓ 成功删除 {deleted_count} 条记忆")
102+
else:
103+
print(f" ✓ 删除操作已完成")
104+
105+
total_deleted += deleted_count
106+
107+
except Exception as e:
108+
print(f" ❌ 清理失败: {e}")
109+
import traceback
110+
traceback.print_exc()
111+
112+
print(f"\n{'='*80}")
113+
if total_deleted > 0:
114+
print(f"清理完成! 总共删除 {total_deleted} 条记忆")
115+
else:
116+
print("清理完成! (未统计删除数量)")
117+
print(f"{'='*80}\n")
118+
119+
120+
if __name__ == "__main__":
121+
cleanup_test_memories()
122+

tests/unit/tools/test_extract_long_term_memory.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
from __future__ import annotations
22

3-
import pytest
4-
53

64
def test_parse_user_ids_variants() -> None:
75
from utils.helpers import _parse_user_ids

tests/unit/tools/test_extraction_async.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,9 @@ def test_successful_processing(
9393
with (
9494
patch("tools.extract_long_term_memory.load_checkpoint") as mock_load,
9595
patch("tools.extract_long_term_memory.save_checkpoint_atomic") as mock_save,
96-
patch("tools.extract_long_term_memory.scan_user_conversations_incremental") as mock_scan,
96+
patch(
97+
"tools.extract_long_term_memory.scan_user_conversations_incremental"
98+
) as mock_scan,
9799
):
98100
# Setup mocks
99101
mock_load.return_value = (None, None)
@@ -202,7 +204,9 @@ def test_dify_api_error(
202204
"""Test error handling when Dify API fails."""
203205
with (
204206
patch("tools.extract_long_term_memory.load_checkpoint") as mock_load,
205-
patch("tools.extract_long_term_memory.scan_user_conversations_incremental") as mock_scan,
207+
patch(
208+
"tools.extract_long_term_memory.scan_user_conversations_incremental"
209+
) as mock_scan,
206210
):
207211
mock_load.return_value = (None, None)
208212
mock_scan.side_effect = Exception("Dify API error")
@@ -426,7 +430,7 @@ def test_invoke_returns_immediately(self):
426430
patch("tools.extract_long_term_memory.build_subtype_memories") as mock_subtypes,
427431
patch("tools.extract_long_term_memory.save_task_status"), # noqa: F401
428432
patch("tools.extract_long_term_memory.BackgroundEventLoop") as mock_loop_cls,
429-
patch("tools.extract_long_term_memory.TaskTracker") as mock_tracker,
433+
patch("tools.extract_long_term_memory.TaskTracker"),
430434
):
431435
mock_config.return_value = {}
432436
mock_memory = MagicMock()
@@ -457,9 +461,6 @@ def test_invoke_returns_immediately(self):
457461
json_msg = messages[0]
458462
assert hasattr(json_msg, "message")
459463

460-
# Verify task was tracked
461-
assert mock_tracker.track_bg_task.called
462-
463464
def test_invoke_validation_errors(self):
464465
"""Test parameter validation errors."""
465466
mock_runtime = MagicMock()
@@ -499,7 +500,7 @@ def test_invoke_with_custom_limits(self):
499500
patch("tools.extract_long_term_memory.build_subtype_memories") as mock_subtypes,
500501
patch("tools.extract_long_term_memory.save_task_status"), # noqa: F401
501502
patch("tools.extract_long_term_memory.BackgroundEventLoop") as mock_loop_cls,
502-
patch("tools.extract_long_term_memory.TaskTracker") as mock_tracker,
503+
patch("tools.extract_long_term_memory.TaskTracker"),
503504
):
504505
mock_config.return_value = {}
505506
mock_memory = MagicMock()

tests/unit/tools/test_time_range_expansion.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,8 @@
55
from datetime import UTC, datetime, timedelta
66
from typing import TYPE_CHECKING, Any
77

8-
import pytest
9-
108
from utils.extraction import (
119
ConversationCheckpoint,
12-
UserCheckpoint,
1310
scan_new_messages_for_conversation,
1411
)
1512

0 commit comments

Comments
 (0)