mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 11:48:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0d29b34ed | ||
|
|
219961755c | ||
|
|
bca2d26e1d | ||
|
|
4bd166d7b9 | ||
|
|
51208d3ff0 | ||
|
|
ae5c58d48c | ||
|
|
eb73ba7d6a | ||
|
|
3727879c19 | ||
|
|
f46fa31262 | ||
|
|
08552c229d | ||
|
|
9dfda1d446 | ||
|
|
e214036308 | ||
|
|
9da6818adc | ||
|
|
ff113906d7 | ||
|
|
56421cd562 | ||
|
|
4e2694e2d9 | ||
|
|
b876af464e | ||
|
|
216538fcfa | ||
|
|
bb71e6bb2a | ||
|
|
9bfa174348 | ||
|
|
cd3c7f3641 | ||
|
|
b8345f7c46 | ||
|
|
d364e13eb7 | ||
|
|
f429873362 | ||
|
|
d81fc09b35 | ||
|
|
6dec8e9786 | ||
|
|
e1ec56147e | ||
|
|
972b1c7458 | ||
|
|
07396725aa | ||
|
|
869bb873cf | ||
|
|
fd7b4ca331 | ||
|
|
c4bba31f20 | ||
|
|
72654e84b2 | ||
|
|
cec3821d00 | ||
|
|
dc3dbcb73e | ||
|
|
6226090fd1 | ||
|
|
d052c56d39 | ||
|
|
bd13fa7774 | ||
|
|
5e462cc7b1 | ||
|
|
73c11af9a3 | ||
|
|
adb73b56a2 | ||
|
|
e5dcf02b26 | ||
|
|
684f88a406 | ||
|
|
8ec970e2bf | ||
|
|
3eb7894df9 | ||
|
|
464167ec83 |
@@ -161,3 +161,44 @@ jobs:
|
|||||||
|
|
||||||
- name: Run Workflow E2E Tests
|
- name: Run Workflow E2E Tests
|
||||||
run: bun run test:e2e:workflow
|
run: bun run test:e2e:workflow
|
||||||
|
|
||||||
|
docker_compose_deploy:
|
||||||
|
name: Docker Compose Deployment
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Build Docker Image
|
||||||
|
run: |
|
||||||
|
docker build -t shumaione/shumai:latest .
|
||||||
|
|
||||||
|
- name: Start Docker Compose
|
||||||
|
run: |
|
||||||
|
docker compose -f docker-compose/local/docker-compose.yaml up -d
|
||||||
|
|
||||||
|
- name: Verify Home Page HTTP 200
|
||||||
|
run: |
|
||||||
|
echo "Waiting for shumai_app container to start..."
|
||||||
|
for i in {1..30}; do
|
||||||
|
STATUS_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000 || true)
|
||||||
|
echo "Attempt $i: HTTP status code $STATUS_CODE"
|
||||||
|
if [ "$STATUS_CODE" -eq 200 ]; then
|
||||||
|
echo "✅ Docker compose app is running cleanly (HTTP 200 OK)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "❌ Container failed to respond with HTTP 200 OK within 60s"
|
||||||
|
echo "--- Container Logs ---"
|
||||||
|
docker compose -f docker-compose/local/docker-compose.yaml logs
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Cleanup Docker Compose
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
docker compose -f docker-compose/local/docker-compose.yaml down -v
|
||||||
|
|||||||
@@ -16,20 +16,31 @@
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **S3-Compatible & Local Storage**: Securely store and serve your creative assets using a local filesystem or any S3-compatible cloud storage (AWS S3, Cloudflare R2, MinIO, etc.).
|
Shumai is an open-source Frame.io alternative built for creative teams to collaborate and share media with ease:
|
||||||
- **Frame-by-Frame Annotations & Comments**: Give precise feedback using frame-specific drawing tools and timestamped comments directly on video and image assets.
|
|
||||||
- **Secure Sharing & Collections**: Create secure public share links and curated media collections to collaborate with clients and stakeholders.
|
* **S3-Compatible & Local Storage**: Store and serve creative assets securely using the local filesystem or any S3-compatible storage service, including AWS S3, Cloudflare R2, and MinIO.
|
||||||
- **Granular Access Control**: Manage workspace permissions using team-level and project-level role-based access controls.
|
* **Frame-by-Frame Annotations & Comments**: Leave precise feedback with frame-specific drawing tools and timestamped comments on both video and image assets.
|
||||||
- **Distributed Transcoding via Temporal**: Offload resource-heavy video transcoding to a background worker pool orchestrated by Temporal.
|
* **Secure Sharing & Collections**: Create private share links and curated media collections for clients, stakeholders, and collaborators.
|
||||||
- **Custom Asset Metadata**: Define and customize dynamic metadata fields tailored to your production pipeline.
|
* **Granular Access Control**: Manage workspace permissions with team-level and project-level role-based access control.
|
||||||
|
* **Distributed Transcoding via Temporal**: Offload resource-intensive video transcoding to a background worker pool orchestrated by Temporal.
|
||||||
|
* **Custom Asset Metadata**: Define dynamic metadata fields tailored to your production pipeline.
|
||||||
|
|
||||||
|
But Shumai goes beyond being a Frame.io alternative. With modern models like GPT-Image-2 and Seedance 2.5, AI can already handle a surprising amount of creative work. That means you can create or update videos and images from a simple prompt without having to jump back into Photoshop, Premiere or Houdini. That is why Shumai includes a powerful agent system:
|
||||||
|
|
||||||
|
* **Agent as a Team Member**: Mention a context-aware AI agent with `@mentions` directly in asset comments, just like a real teammate.
|
||||||
|
* **Agent as a One-to-One Assistant**: Chat privately with the agent and ask it to help with tasks.
|
||||||
|
* **Custom Skills & Tools**: Extend the agent by registering custom scripts, tools, and automation skills.
|
||||||
|
* **Isolated Sandbox Execution**: Run agent-submitted scripts safely in a sandboxed environment.
|
||||||
|
* **AI Metadata Autofill**: Automatically fill in custom metadata for new assets.
|
||||||
|
* **Semantic Search**: Find assets by visual or conceptual meaning using vector embeddings (Gemini Embedding 2).
|
||||||
|
|
||||||
|
Here is a short demo video showing what the Shumai agent can do:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
https://github.com/user-attachments/assets/2ebe5456-342e-47f7-9a93-a963fcf12097
|
||||||
|
|
||||||
#### Shumai Agent
|
|
||||||
|
|
||||||
- **Collaborative AI Chat**: Converse with a context-aware AI agent by using `@mentions` directly within the file's comments area.
|
|
||||||
- **Custom Skills & Tools**: Extend the agent's capabilities by registering custom scripts, tools, and automation skills.
|
|
||||||
- **Isolated Sandbox Execution**: Run agent-submitted scripts securely within a sandboxed environment.
|
|
||||||
- **AI Metadata Autofill**: Automatically autofill custom metadata for new assets.
|
|
||||||
- **Semantic Search**: Find assets based on visual or conceptual search queries using vector embeddings(Gemini Embedding 2).
|
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> **Media Processing & Storage:** When uploading media, Shumai always preserves and stores your original raw file. Note that the file size shown in the system represents the original file size and does not include the size of any transcoded files. For all media types (both images and videos), Shumai creates a 480p WebP poster image to serve as the preview in the file list view. Additionally:
|
> **Media Processing & Storage:** When uploading media, Shumai always preserves and stores your original raw file. Note that the file size shown in the system represents the original file size and does not include the size of any transcoded files. For all media types (both images and videos), Shumai creates a 480p WebP poster image to serve as the preview in the file list view. Additionally:
|
||||||
|
|||||||
+20
-13
@@ -15,22 +15,29 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
## 功能特性
|
## 功能
|
||||||
|
|
||||||
- **兼容 S3 与本地存储**:支持使用本地文件系统或任意兼容 S3 协议的对象存储(AWS S3、Cloudflare R2、MinIO 等)安全存储和访问你的创意资产。
|
Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让大家能更轻松地协作、审片和分享素材:
|
||||||
- **逐帧标注与评论**:可直接在图片和视频上进行逐帧绘制标注,并结合时间戳评论,实现精准反馈与协作。
|
|
||||||
- **安全分享与媒体合集**:支持创建安全的公开分享链接和精心组织的媒体合集,方便与客户及团队成员协同沟通。
|
|
||||||
- **细粒度权限控制**:基于团队和项目两级角色权限(RBAC),灵活管理工作区访问权限。
|
|
||||||
- **基于 Temporal 的分布式转码**:将高负载的视频转码任务交由 Temporal 调度的后台 Worker 集群处理,提升系统扩展性与处理效率。
|
|
||||||
- **自定义资产元数据**:支持定义和扩展动态元数据字段,灵活适配你的制作流程。
|
|
||||||
|
|
||||||
#### Shumai Agent
|
* **支持 S3 和本地存储**:你可以把创意素材安全地存到本地文件系统,或者任意兼容 S3 的存储服务里,比如 AWS S3、Cloudflare R2、MinIO 等。
|
||||||
|
* **逐帧标注和评论**:支持按帧进行精确反馈,可以直接在视频和图片素材上画重点、写评论,还能留下时间戳。
|
||||||
|
* **安全分享和合集管理**:可以生成私密分享链接,也能整理成精选合集,方便给客户、同事和合作方查看。
|
||||||
|
* **细粒度权限控制**:支持按团队、项目设置角色权限,方便管理不同成员的访问范围。
|
||||||
|
* **基于 Temporal 的分布式转码**:把吃资源的视频转码任务交给后台 worker 池处理,由 Temporal 统一调度。
|
||||||
|
* **自定义素材元数据**:可以按你的制作流程,自由定义动态元数据字段。
|
||||||
|
|
||||||
- **协作式 AI 对话**:在文件评论区通过 `@mention` 即可唤起具备上下文感知能力的 AI Agent,参与讨论与协作。
|
但 Shumai 不仅仅只满足于 Frame.io 的开源替代。随着 GPT-Image-2、Seedance 2.5 这类强大模型的问世,AI已经生成产品级的图片/视频。很多时候,你只要给一句提示词,就能直接生成或修改图片和视频,而不用再打开 Photoshop、Premiere 或者 Houdini。也正因为这样,Shumai 才把 AI Agent 做成了核心能力:
|
||||||
- **自定义技能与工具**:支持为 Agent 注册自定义脚本、工具和自动化技能,扩展其能力边界。
|
|
||||||
- **隔离沙箱执行**:Agent 提交的脚本会在安全隔离的沙箱环境中运行,保障执行安全。
|
* **Agent 就像团队成员**:你可以在素材评论区里直接用 `@` 提到 AI Agent,像拉一个真实同事进来一起看稿一样。
|
||||||
- **AI 自动填充元数据**:为新上传的资产自动生成并填写自定义元数据。
|
* **Agent 也能当你的私聊助手**:你可以单独和它聊天,让它帮你查东西、做任务。
|
||||||
- **语义搜索**:基于向量进行搜索(Gemini Embedding 2),支持按视觉内容或语义概念搜索资产。
|
* **自定义技能和工具**:你可以给 Agent 接上自己的脚本、工具和自动化能力。
|
||||||
|
* **沙箱隔离执行**:Agent 生成的脚本会在隔离环境里运行,更安全。
|
||||||
|
* **AI 自动补全元数据**:新素材上传后,系统可以自动帮你补一些元数据。
|
||||||
|
* **语义搜索**:支持按画面内容或语义找素材,底层用的是向量 embedding(Gemini Embedding 2)。
|
||||||
|
|
||||||
|
下面是一个简短的 demo 视频,展示了 Shumai Agent 能做什么:
|
||||||
|
|
||||||
|
https://github.com/user-attachments/assets/2ebe5456-342e-47f7-9a93-a963fcf12097
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> **媒体处理与存储机制:** 上传媒体文件后,Shumai 始终会保留并存储原始文件。请注意,系统中显示的文件大小为原始文件的大小,不包含转码后生成的代理文件大小。无论图片还是视频,都会额外生成一张 480p 的 WebP 封面图,作为文件列表中的预览图。此外:
|
> **媒体处理与存储机制:** 上传媒体文件后,Shumai 始终会保留并存储原始文件。请注意,系统中显示的文件大小为原始文件的大小,不包含转码后生成的代理文件大小。无论图片还是视频,都会额外生成一张 480p 的 WebP 封面图,作为文件列表中的预览图。此外:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/agent-app",
|
"name": "@shumai/agent-app",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/cli",
|
"name": "@shumai/cli",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/transcode-app",
|
"name": "@shumai/transcode-app",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/web-app",
|
"name": "@shumai/web-app",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -33,7 +33,7 @@
|
|||||||
},
|
},
|
||||||
"apps/agent": {
|
"apps/agent": {
|
||||||
"name": "@shumai/agent-app",
|
"name": "@shumai/agent-app",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"bin": {
|
"bin": {
|
||||||
"shumai-agent": "./src/index.ts",
|
"shumai-agent": "./src/index.ts",
|
||||||
},
|
},
|
||||||
@@ -45,7 +45,7 @@
|
|||||||
},
|
},
|
||||||
"apps/cli": {
|
"apps/cli": {
|
||||||
"name": "@shumai/cli",
|
"name": "@shumai/cli",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"bin": {
|
"bin": {
|
||||||
"shumai-cli": "./src/index.ts",
|
"shumai-cli": "./src/index.ts",
|
||||||
},
|
},
|
||||||
@@ -60,7 +60,7 @@
|
|||||||
},
|
},
|
||||||
"apps/transcode": {
|
"apps/transcode": {
|
||||||
"name": "@shumai/transcode-app",
|
"name": "@shumai/transcode-app",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"bin": {
|
"bin": {
|
||||||
"shumai-transcode": "./src/index.ts",
|
"shumai-transcode": "./src/index.ts",
|
||||||
},
|
},
|
||||||
@@ -72,7 +72,7 @@
|
|||||||
},
|
},
|
||||||
"apps/web": {
|
"apps/web": {
|
||||||
"name": "@shumai/web-app",
|
"name": "@shumai/web-app",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shumai/agent": "workspace:*",
|
"@shumai/agent": "workspace:*",
|
||||||
"@shumai/api": "workspace:*",
|
"@shumai/api": "workspace:*",
|
||||||
@@ -92,9 +92,9 @@
|
|||||||
},
|
},
|
||||||
"packages/agent": {
|
"packages/agent": {
|
||||||
"name": "@shumai/agent",
|
"name": "@shumai/agent",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/sandbox-runtime": "0.0.52",
|
"@anthropic-ai/sandbox-runtime": "0.0.66",
|
||||||
"@earendil-works/pi-agent-core": "0.78.0",
|
"@earendil-works/pi-agent-core": "0.78.0",
|
||||||
"@earendil-works/pi-ai": "0.80.7",
|
"@earendil-works/pi-ai": "0.80.7",
|
||||||
"@google/genai": "1.52.0",
|
"@google/genai": "1.52.0",
|
||||||
@@ -117,7 +117,7 @@
|
|||||||
},
|
},
|
||||||
"packages/api": {
|
"packages/api": {
|
||||||
"name": "@shumai/api",
|
"name": "@shumai/api",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hono/zod-validator": "0.7.6",
|
"@hono/zod-validator": "0.7.6",
|
||||||
"@shumai/core": "workspace:*",
|
"@shumai/core": "workspace:*",
|
||||||
@@ -131,7 +131,7 @@
|
|||||||
},
|
},
|
||||||
"packages/core": {
|
"packages/core": {
|
||||||
"name": "@shumai/core",
|
"name": "@shumai/core",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@earendil-works/pi-agent-core": "0.78.0",
|
"@earendil-works/pi-agent-core": "0.78.0",
|
||||||
"@shumai/db": "workspace:*",
|
"@shumai/db": "workspace:*",
|
||||||
@@ -162,7 +162,7 @@
|
|||||||
},
|
},
|
||||||
"packages/db": {
|
"packages/db": {
|
||||||
"name": "@shumai/db",
|
"name": "@shumai/db",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@earendil-works/pi-agent-core": "0.78.0",
|
"@earendil-works/pi-agent-core": "0.78.0",
|
||||||
"@prisma/adapter-pg": "7.8.0",
|
"@prisma/adapter-pg": "7.8.0",
|
||||||
@@ -178,7 +178,7 @@
|
|||||||
},
|
},
|
||||||
"packages/dtos": {
|
"packages/dtos": {
|
||||||
"name": "@shumai/dtos",
|
"name": "@shumai/dtos",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@earendil-works/pi-agent-core": "0.78.0",
|
"@earendil-works/pi-agent-core": "0.78.0",
|
||||||
"zod": "4.4.3",
|
"zod": "4.4.3",
|
||||||
@@ -186,7 +186,7 @@
|
|||||||
},
|
},
|
||||||
"packages/e2e": {
|
"packages/e2e": {
|
||||||
"name": "@shumai/e2e",
|
"name": "@shumai/e2e",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@earendil-works/pi-agent-core": "0.78.0",
|
"@earendil-works/pi-agent-core": "0.78.0",
|
||||||
"@google/genai": "1.52.0",
|
"@google/genai": "1.52.0",
|
||||||
@@ -196,15 +196,16 @@
|
|||||||
"@shumai/dtos": "workspace:*",
|
"@shumai/dtos": "workspace:*",
|
||||||
"@shumai/transcode": "workspace:*",
|
"@shumai/transcode": "workspace:*",
|
||||||
"@shumai/workflow-core": "workspace:*",
|
"@shumai/workflow-core": "workspace:*",
|
||||||
|
"sharp": "0.34.5",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"packages/tableprinter": {
|
"packages/tableprinter": {
|
||||||
"name": "@shumai/tableprinter",
|
"name": "@shumai/tableprinter",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
},
|
},
|
||||||
"packages/transcode": {
|
"packages/transcode": {
|
||||||
"name": "@shumai/transcode",
|
"name": "@shumai/transcode",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shumai/core": "workspace:*",
|
"@shumai/core": "workspace:*",
|
||||||
"@shumai/db": "workspace:*",
|
"@shumai/db": "workspace:*",
|
||||||
@@ -218,7 +219,7 @@
|
|||||||
},
|
},
|
||||||
"packages/webui": {
|
"packages/webui": {
|
||||||
"name": "@shumai/webui",
|
"name": "@shumai/webui",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "1.5.0",
|
"@base-ui/react": "1.5.0",
|
||||||
"@dnd-kit/abstract": "0.4.0",
|
"@dnd-kit/abstract": "0.4.0",
|
||||||
@@ -316,7 +317,7 @@
|
|||||||
},
|
},
|
||||||
"packages/workflow-core": {
|
"packages/workflow-core": {
|
||||||
"name": "@shumai/workflow-core",
|
"name": "@shumai/workflow-core",
|
||||||
"version": "0.2.0",
|
"version": "0.2.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shumai/core": "workspace:*",
|
"@shumai/core": "workspace:*",
|
||||||
"@shumai/db": "workspace:*",
|
"@shumai/db": "workspace:*",
|
||||||
@@ -331,7 +332,7 @@
|
|||||||
"packages": {
|
"packages": {
|
||||||
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
|
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
|
||||||
|
|
||||||
"@anthropic-ai/sandbox-runtime": ["@anthropic-ai/sandbox-runtime@0.0.52", "", { "dependencies": { "@pondwader/socks5-server": "^1.0.10", "commander": "^12.1.0", "node-forge": "^1.4.0", "shell-quote": "^1.8.3", "zod": "^3.24.1" }, "bin": { "srt": "dist/cli.js" } }, "sha512-vYaM7OslFmOAzNgfy5gxvt3NoWFeCbr7C0AKyuduQq7Gdxbg2NnYmE7deBf8Nxj3ZNECTcC5RhAfz0lZwvbtBA=="],
|
"@anthropic-ai/sandbox-runtime": ["@anthropic-ai/sandbox-runtime@0.0.66", "", { "dependencies": { "@pondwader/socks5-server": "^1.0.10", "commander": "^12.1.0", "node-forge": "^1.4.0", "zod": "^3.24.1" }, "bin": { "srt": "dist/cli.js" } }, "sha512-OE7QiGZJXe7ZshP47U2vk2z9FGSyiSN4ca9krVrE28LS2Qj0AHRWZz+gAce6FzG3gx/4OjNFwIhDuHXnI0WWwA=="],
|
||||||
|
|
||||||
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.91.1", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw=="],
|
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.91.1", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw=="],
|
||||||
|
|
||||||
@@ -473,7 +474,7 @@
|
|||||||
|
|
||||||
"@electric-sql/pglite-tools": ["@electric-sql/pglite-tools@0.3.1", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.1" } }, "sha512-C+T3oivmy9bpQvSxVqXA1UDY8cB9Eb9vZHL9zxWwEUfDixbXv4G3r2LjoTdR33LD8aomR3O9ZXEO3XEwr/cUCA=="],
|
"@electric-sql/pglite-tools": ["@electric-sql/pglite-tools@0.3.1", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.1" } }, "sha512-C+T3oivmy9bpQvSxVqXA1UDY8cB9Eb9vZHL9zxWwEUfDixbXv4G3r2LjoTdR33LD8aomR3O9ZXEO3XEwr/cUCA=="],
|
||||||
|
|
||||||
"@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],
|
"@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="],
|
||||||
|
|
||||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="],
|
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="],
|
||||||
|
|
||||||
@@ -2509,8 +2510,6 @@
|
|||||||
|
|
||||||
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||||
|
|
||||||
"shell-quote": ["shell-quote@1.8.4", "", {}, "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ=="],
|
|
||||||
|
|
||||||
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
|
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
|
||||||
|
|
||||||
"side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
|
"side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
|
||||||
@@ -3225,7 +3224,7 @@
|
|||||||
|
|
||||||
"schema-utils/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
|
"schema-utils/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
|
||||||
|
|
||||||
"sharp/semver": ["semver@7.8.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg=="],
|
"sharp/semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
|
||||||
|
|
||||||
"source-map-loader/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
|
"source-map-loader/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ services:
|
|||||||
|
|
||||||
shumai:
|
shumai:
|
||||||
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
||||||
|
cap_add:
|
||||||
|
- SYS_ADMIN
|
||||||
|
security_opt:
|
||||||
|
- apparmor=unconfined
|
||||||
|
- seccomp=unconfined
|
||||||
container_name: shumai_app
|
container_name: shumai_app
|
||||||
ports:
|
ports:
|
||||||
- '3000:3000'
|
- '3000:3000'
|
||||||
@@ -37,6 +42,9 @@ services:
|
|||||||
# Better Auth
|
# Better Auth
|
||||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||||
|
|
||||||
|
# Sandbox Configuration
|
||||||
|
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||||
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ services:
|
|||||||
|
|
||||||
shumai:
|
shumai:
|
||||||
image: shumaione/shumai:latest
|
image: shumaione/shumai:latest
|
||||||
|
cap_add:
|
||||||
|
- SYS_ADMIN
|
||||||
|
security_opt:
|
||||||
|
- apparmor=unconfined
|
||||||
|
- seccomp=unconfined
|
||||||
container_name: shumai_app
|
container_name: shumai_app
|
||||||
ports:
|
ports:
|
||||||
- '3000:3000'
|
- '3000:3000'
|
||||||
@@ -37,6 +42,9 @@ services:
|
|||||||
# Better Auth
|
# Better Auth
|
||||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||||
|
|
||||||
|
# Sandbox Configuration
|
||||||
|
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||||
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ services:
|
|||||||
WORKFLOW_EXECUTOR: temporal
|
WORKFLOW_EXECUTOR: temporal
|
||||||
TEMPORAL_ADDRESS: temporal:7233
|
TEMPORAL_ADDRESS: temporal:7233
|
||||||
GEMINI_API_KEY: KEY
|
GEMINI_API_KEY: KEY
|
||||||
|
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
@@ -72,6 +72,12 @@ Configures whether background transcoding and AI agents are executed locally or
|
|||||||
| `EMBEDDING_CHUNK_DURATION` | The duration in seconds for each video chunk when generating video embeddings. | `60.0` (default) |
|
| `EMBEDDING_CHUNK_DURATION` | The duration in seconds for each video chunk when generating video embeddings. | `60.0` (default) |
|
||||||
| `EMBEDDING_CHUNK_OVERLAP` | The duration in seconds to overlap video chunks when generating video embeddings. | `5.0` (default) |
|
| `EMBEDDING_CHUNK_OVERLAP` | The duration in seconds to overlap video chunks when generating video embeddings. | `5.0` (default) |
|
||||||
|
|
||||||
|
## Sandbox Config
|
||||||
|
|
||||||
|
| Variable | Description | Example / Default |
|
||||||
|
| :----------------------------- | :----------------------------------------------------------------------------------------------------- | :---------------- |
|
||||||
|
| `ENABLE_WEAKER_NESTED_SANDBOX` | Enables weaker nested sandbox mode for environments without user namespace permissions (e.g., Docker). | `false` (default) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Logging Config
|
## Logging Config
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "shumai",
|
"name": "shumai",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/agent",
|
"name": "@shumai/agent",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
"types": "./src/index.ts",
|
"types": "./src/index.ts",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/sandbox-runtime": "0.0.52",
|
"@anthropic-ai/sandbox-runtime": "0.0.66",
|
||||||
"@earendil-works/pi-agent-core": "0.78.0",
|
"@earendil-works/pi-agent-core": "0.78.0",
|
||||||
"@earendil-works/pi-ai": "0.80.7",
|
"@earendil-works/pi-ai": "0.80.7",
|
||||||
"@google/genai": "1.52.0",
|
"@google/genai": "1.52.0",
|
||||||
|
|||||||
@@ -17,10 +17,11 @@ import {
|
|||||||
executeAgentToolActivity,
|
executeAgentToolActivity,
|
||||||
generateSessionNameActivity,
|
generateSessionNameActivity,
|
||||||
type GenerateSessionNameParams,
|
type GenerateSessionNameParams,
|
||||||
|
getUserTeamInfoActivity,
|
||||||
} from './agent'
|
} from './agent'
|
||||||
import * as piAgent from '../index'
|
import * as piAgent from '../index'
|
||||||
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
|
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
|
||||||
import { type DatabaseSessionMetadata } from '../database-session-storage'
|
import { DatabaseSessionStorage, type DatabaseSessionMetadata } from '../database-session-storage'
|
||||||
import { triggerLocalCancel } from '@shumai/workflow-core'
|
import { triggerLocalCancel } from '@shumai/workflow-core'
|
||||||
import { Context } from '@temporalio/activity'
|
import { Context } from '@temporalio/activity'
|
||||||
|
|
||||||
@@ -545,12 +546,128 @@ describe('Agent Database Activities Integration', () => {
|
|||||||
|
|
||||||
// Verify historical comment is converted and saved to entries (mentions replaced, prefixes added)
|
// Verify historical comment is converted and saved to entries (mentions replaced, prefixes added)
|
||||||
expect(agentSession?.entries.length).toBe(1)
|
expect(agentSession?.entries.length).toBe(1)
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- entry is stored as Json in DB and needs casting to check properties
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- entry data is stored as Json in DB and needs casting to check properties
|
||||||
const parsedEntry = agentSession?.entries[0].entry as any
|
const parsedEntry = agentSession?.entries[0].data as any
|
||||||
expect(parsedEntry.message.content[0].text).toContain(
|
expect(parsedEntry.message.content[0].text).toContain(
|
||||||
`[${user.name}]: Hello <@${user.name}> check this`,
|
`[${user.name} (owner)]: Hello <@${user.name}> check this`,
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('should distinguish Main Session (userCommentId: null) and Thread Session (userCommentId: rootId) during lazy sync', async () => {
|
||||||
|
// 1. Top-level comments
|
||||||
|
const mainComment1 = await prisma.assetComment.create({
|
||||||
|
data: { assetId: asset.id, message: 'Main Comment 1', creatorId: user.id },
|
||||||
|
})
|
||||||
|
const mainComment2 = await prisma.assetComment.create({
|
||||||
|
data: { assetId: asset.id, message: 'Main Comment 2', creatorId: user.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Thread reply under mainComment1
|
||||||
|
const threadReply1 = await prisma.assetComment.create({
|
||||||
|
data: {
|
||||||
|
assetId: asset.id,
|
||||||
|
message: 'Thread Reply 1',
|
||||||
|
creatorId: user.id,
|
||||||
|
replyToId: mainComment1.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 3. Initialize session for mention on mainComment2 (Main Session)
|
||||||
|
const mainSessionId = await initializeAgentSessionActivity({
|
||||||
|
teamId: team.id,
|
||||||
|
agentId: 'test-agent-id',
|
||||||
|
userCommentId: mainComment2.id,
|
||||||
|
userId: user.id,
|
||||||
|
})
|
||||||
|
|
||||||
|
const mainSession = await prisma.agentSession.findUnique({
|
||||||
|
where: { id: mainSessionId },
|
||||||
|
})
|
||||||
|
expect(mainSession?.userCommentId).toBeNull() // Main Session has userCommentId = null
|
||||||
|
|
||||||
|
// Retrieve main session entries
|
||||||
|
const mainEntries = await prisma.agentSessionEntry.findMany({
|
||||||
|
where: { sessionId: mainSessionId },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
// Main session contains mainComment1, but NOT threadReply1
|
||||||
|
expect(mainEntries.length).toBe(1)
|
||||||
|
expect(mainEntries[0].id).toBe(mainComment1.id)
|
||||||
|
|
||||||
|
const mainStorage = new DatabaseSessionStorage(mainSessionId)
|
||||||
|
const mainLeafId = await mainStorage.getLeafId()
|
||||||
|
const mainPath = await mainStorage.getPathToRoot(mainLeafId)
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const mainText = (mainPath[0] as any).message.content[0].text
|
||||||
|
expect(mainText).toContain(`[Thread ID: ${mainComment1.id}]`)
|
||||||
|
|
||||||
|
// 4. Initialize session for mention on threadReply1 (Thread Session)
|
||||||
|
const threadSessionId = await initializeAgentSessionActivity({
|
||||||
|
teamId: team.id,
|
||||||
|
agentId: 'test-agent-id',
|
||||||
|
userCommentId: threadReply1.id,
|
||||||
|
userId: user.id,
|
||||||
|
})
|
||||||
|
|
||||||
|
const threadSession = await prisma.agentSession.findUnique({
|
||||||
|
where: { id: threadSessionId },
|
||||||
|
})
|
||||||
|
expect(threadSession?.userCommentId).toBe(mainComment1.id) // Thread Session has userCommentId = rootComment.id
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should dynamically tag top-level comments with [Thread ID: id] even if thread was created after initial sync', async () => {
|
||||||
|
const msg3 = await prisma.assetComment.create({
|
||||||
|
data: { assetId: asset.id, message: 'Question in msg3', creatorId: user.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const session1Id = await initializeAgentSessionActivity({
|
||||||
|
teamId: team.id,
|
||||||
|
agentId: 'test-agent-id',
|
||||||
|
userCommentId: msg3.id,
|
||||||
|
userId: user.id,
|
||||||
|
})
|
||||||
|
|
||||||
|
await prisma.assetComment.create({
|
||||||
|
data: {
|
||||||
|
assetId: asset.id,
|
||||||
|
message: 'Reply msg4',
|
||||||
|
creatorId: user.id,
|
||||||
|
replyToId: msg3.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const msg6 = await prisma.assetComment.create({
|
||||||
|
data: { assetId: asset.id, message: 'Question in msg6', creatorId: user.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
await initializeAgentSessionActivity({
|
||||||
|
teamId: team.id,
|
||||||
|
agentId: 'test-agent-id',
|
||||||
|
userCommentId: msg6.id,
|
||||||
|
userId: user.id,
|
||||||
|
})
|
||||||
|
|
||||||
|
const storage = new DatabaseSessionStorage(session1Id)
|
||||||
|
const leafId = await storage.getLeafId()
|
||||||
|
const pathEntries = await storage.getPathToRoot(leafId)
|
||||||
|
|
||||||
|
const msg3Entry = pathEntries.find((e) => e.id === msg3.id)
|
||||||
|
expect(msg3Entry).toBeDefined()
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const text = (msg3Entry as any).message.content[0].text
|
||||||
|
expect(text).toContain(`[Thread ID: ${msg3.id}]`)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return user name and role for team member', async () => {
|
||||||
|
const info = await getUserTeamInfoActivity({
|
||||||
|
userId: user.id,
|
||||||
|
teamId: team.id,
|
||||||
|
})
|
||||||
|
expect(info).toBeDefined()
|
||||||
|
expect(info?.name).toBe(user.name)
|
||||||
|
expect(info?.role).toBe('owner')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('Comment Operations', () => {
|
describe('Comment Operations', () => {
|
||||||
|
|||||||
@@ -333,20 +333,62 @@ export interface AgentChatParams {
|
|||||||
sessionId: string
|
sessionId: string
|
||||||
userId?: string
|
userId?: string
|
||||||
userCommentId?: string | null
|
userCommentId?: string | null
|
||||||
explicitMention?: boolean
|
|
||||||
context: AgentExecutionContext
|
context: AgentExecutionContext
|
||||||
attachedAssets?: Array<{ id: string; name: string; type: string }>
|
attachedAssets?: Array<{ id: string; name: string; type: string }>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getUserTeamInfoActivity(params: {
|
||||||
|
userId?: string
|
||||||
|
teamId: string
|
||||||
|
}): Promise<{ name: string; role: string } | null> {
|
||||||
|
if (!params.userId) return null
|
||||||
|
const [user, member] = await Promise.all([
|
||||||
|
prisma.user.findUnique({
|
||||||
|
where: { id: params.userId },
|
||||||
|
select: { name: true },
|
||||||
|
}),
|
||||||
|
prisma.teamMember.findUnique({
|
||||||
|
where: { teamIdUserId: { teamId: params.teamId, userId: params.userId } },
|
||||||
|
select: { role: true },
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
if (!user) return null
|
||||||
|
return {
|
||||||
|
name: user.name || 'Unknown User',
|
||||||
|
role: member?.role || 'user',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function agentChatActivity(params: AgentChatParams) {
|
export async function agentChatActivity(params: AgentChatParams) {
|
||||||
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
|
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
|
||||||
const sessionId = params.sessionId
|
const sessionId = params.sessionId
|
||||||
|
|
||||||
|
let prompt = cleanMessage
|
||||||
|
if (params.userCommentId) {
|
||||||
|
let targetUserId = params.userId
|
||||||
|
if (!targetUserId) {
|
||||||
|
const comment = await prisma.assetComment.findUnique({
|
||||||
|
where: { id: params.userCommentId },
|
||||||
|
select: { creatorId: true },
|
||||||
|
})
|
||||||
|
targetUserId = comment?.creatorId || undefined
|
||||||
|
}
|
||||||
|
if (targetUserId) {
|
||||||
|
const userInfo = await getUserTeamInfoActivity({
|
||||||
|
userId: targetUserId,
|
||||||
|
teamId: params.teamId,
|
||||||
|
})
|
||||||
|
if (userInfo) {
|
||||||
|
prompt = `[${userInfo.name} (${userInfo.role})]: ${cleanMessage}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return executeAgentPrompt({
|
return executeAgentPrompt({
|
||||||
taskId: params.taskId,
|
taskId: params.taskId,
|
||||||
teamId: params.teamId,
|
teamId: params.teamId,
|
||||||
agentId: params.agentId,
|
agentId: params.agentId,
|
||||||
prompt: cleanMessage,
|
prompt,
|
||||||
images: params.imageUrls,
|
images: params.imageUrls,
|
||||||
agentsInstruction: params.agentsInstruction || '',
|
agentsInstruction: params.agentsInstruction || '',
|
||||||
sessionId,
|
sessionId,
|
||||||
@@ -448,19 +490,117 @@ export async function initializeAgentSessionActivity(params: {
|
|||||||
include: { creator: true },
|
include: { creator: true },
|
||||||
})
|
})
|
||||||
|
|
||||||
// Create a new AgentSession
|
if (!userComment) {
|
||||||
const newSession = await prisma.agentSession.create({
|
throw new Error(`User comment ${params.userCommentId} not found`)
|
||||||
data: {
|
}
|
||||||
agentId,
|
|
||||||
userId: params.userId || null,
|
const isThread = !!userComment.replyToId
|
||||||
cwd: process.cwd(),
|
const rootCommentId = userComment.replyToId || userComment.id
|
||||||
assetId: userComment ? userComment.assetId : null,
|
const targetUserCommentId = isThread ? rootCommentId : null
|
||||||
userCommentId: params.userCommentId,
|
|
||||||
|
let session = await prisma.agentSession.findFirst({
|
||||||
|
where: {
|
||||||
|
assetId: userComment.assetId,
|
||||||
|
type: 'comment',
|
||||||
|
userCommentId: targetUserCommentId,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
const sessionId = newSession.id
|
|
||||||
|
|
||||||
// Fetch existing comments as context
|
if (!session) {
|
||||||
|
session = await prisma.agentSession.create({
|
||||||
|
data: {
|
||||||
|
agentId,
|
||||||
|
userId: params.userId || null,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
assetId: userComment.assetId,
|
||||||
|
userCommentId: targetUserCommentId,
|
||||||
|
type: 'comment',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const sessionId = session.id
|
||||||
|
|
||||||
|
// If this is a Thread Session, ensure preceding top-level comments up to rootCommentId are synced in Main Session first
|
||||||
|
if (isThread) {
|
||||||
|
let mainSession = await prisma.agentSession.findFirst({
|
||||||
|
where: {
|
||||||
|
assetId: userComment.assetId,
|
||||||
|
type: 'comment',
|
||||||
|
userCommentId: null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if (!mainSession) {
|
||||||
|
mainSession = await prisma.agentSession.create({
|
||||||
|
data: {
|
||||||
|
agentId,
|
||||||
|
userId: params.userId || null,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
assetId: userComment.assetId,
|
||||||
|
userCommentId: null,
|
||||||
|
type: 'comment',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const topLevelComments = await prisma.assetComment.findMany({
|
||||||
|
where: {
|
||||||
|
assetId: userComment.assetId,
|
||||||
|
replyToId: null,
|
||||||
|
createdAt: { lte: userComment.createdAt },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
include: { creator: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
let mainPrevId: string | null = mainSession.leafId
|
||||||
|
for (const c of topLevelComments) {
|
||||||
|
const existingEntry = await prisma.agentSessionEntry.findUnique({
|
||||||
|
where: { id: c.id },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
if (existingEntry) {
|
||||||
|
mainPrevId = existingEntry.id
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
|
||||||
|
let messageContent = c.message || ''
|
||||||
|
if (isAgent) {
|
||||||
|
const agentName = c.creator?.name || 'Ai Agent'
|
||||||
|
messageContent = `[Agent Message][${agentName}]: ${messageContent}`
|
||||||
|
} else if (c.creator?.name) {
|
||||||
|
messageContent = `[${c.creator.name} (user)]: ${messageContent}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const entryId = c.id
|
||||||
|
const message: AgentMessage = {
|
||||||
|
role: 'user',
|
||||||
|
content: [{ type: 'text', text: messageContent }],
|
||||||
|
timestamp: c.createdAt.getTime(),
|
||||||
|
}
|
||||||
|
await prisma.agentSessionEntry.create({
|
||||||
|
data: {
|
||||||
|
id: entryId,
|
||||||
|
sessionId: mainSession.id,
|
||||||
|
assetId: userComment.assetId,
|
||||||
|
type: 'message',
|
||||||
|
parentId: mainPrevId,
|
||||||
|
createdAt: c.createdAt,
|
||||||
|
data: { message },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
mainPrevId = entryId
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mainPrevId && mainPrevId !== mainSession.leafId) {
|
||||||
|
await prisma.agentSession.update({
|
||||||
|
where: { id: mainSession.id },
|
||||||
|
data: { leafId: mainPrevId },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch existing comments as context for current session
|
||||||
let existingComments: Array<{
|
let existingComments: Array<{
|
||||||
id: string
|
id: string
|
||||||
message: string | null
|
message: string | null
|
||||||
@@ -468,39 +608,40 @@ export async function initializeAgentSessionActivity(params: {
|
|||||||
creatorId: string | null
|
creatorId: string | null
|
||||||
creator: { type: string; name: string } | null
|
creator: { type: string; name: string } | null
|
||||||
sessionId: string | null
|
sessionId: string | null
|
||||||
|
replyToId: string | null
|
||||||
}> = []
|
}> = []
|
||||||
|
|
||||||
if (userComment) {
|
if (!isThread) {
|
||||||
if (!userComment.replyToId) {
|
// Main Session: Only fetch top-level comments (replyToId: null)
|
||||||
// Rule 1: outside of a reply, add all other comments on that asset
|
existingComments = await prisma.assetComment.findMany({
|
||||||
existingComments = await prisma.assetComment.findMany({
|
where: {
|
||||||
|
assetId: userComment.assetId,
|
||||||
|
replyToId: null,
|
||||||
|
id: { not: userComment.id },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
include: { creator: true },
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// Thread Session: Fetch root comment + replies in this specific thread (replyToId: rootCommentId)
|
||||||
|
const rootComment = await prisma.assetComment.findUnique({
|
||||||
|
where: { id: rootCommentId },
|
||||||
|
include: { creator: true },
|
||||||
|
})
|
||||||
|
if (rootComment) {
|
||||||
|
const replies = await prisma.assetComment.findMany({
|
||||||
where: {
|
where: {
|
||||||
assetId: userComment.assetId,
|
replyToId: rootCommentId,
|
||||||
id: { not: userComment.id },
|
id: { not: userComment.id },
|
||||||
},
|
},
|
||||||
orderBy: { id: 'asc' },
|
orderBy: { createdAt: 'asc' },
|
||||||
include: { creator: true },
|
include: { creator: true },
|
||||||
})
|
})
|
||||||
} else {
|
existingComments = [rootComment, ...replies]
|
||||||
// Rule 2: in a reply, add root comment + all other replies to it
|
|
||||||
const rootComment = await prisma.assetComment.findUnique({
|
|
||||||
where: { id: userComment.replyToId },
|
|
||||||
include: { creator: true },
|
|
||||||
})
|
|
||||||
if (rootComment) {
|
|
||||||
const replies = await prisma.assetComment.findMany({
|
|
||||||
where: {
|
|
||||||
replyToId: rootComment.id,
|
|
||||||
id: { not: userComment.id },
|
|
||||||
},
|
|
||||||
orderBy: { id: 'asc' },
|
|
||||||
include: { creator: true },
|
|
||||||
})
|
|
||||||
existingComments = [rootComment, ...replies]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check which top-level comments have reply threads (for prompt tagging)
|
||||||
// Resolve user mentions from IDs to names
|
// Resolve user mentions from IDs to names
|
||||||
const mentionRegex = /<@([^>]+)>/g
|
const mentionRegex = /<@([^>]+)>/g
|
||||||
const mentionedUserIds = new Set<string>()
|
const mentionedUserIds = new Set<string>()
|
||||||
@@ -531,9 +672,40 @@ export async function initializeAgentSessionActivity(params: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save context as AgentSessionEntry records
|
const userRoleMap = new Map<string, string>()
|
||||||
let prevId: string | null = null
|
const humanCreatorIds = Array.from(
|
||||||
|
new Set(
|
||||||
|
existingComments
|
||||||
|
.filter((c) => c.creator?.type !== 'agent' && c.creatorId)
|
||||||
|
.map((c) => c.creatorId!),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if (humanCreatorIds.length > 0) {
|
||||||
|
const members = await prisma.teamMember.findMany({
|
||||||
|
where: {
|
||||||
|
teamId: params.teamId,
|
||||||
|
userId: { in: humanCreatorIds },
|
||||||
|
},
|
||||||
|
select: { userId: true, role: true },
|
||||||
|
})
|
||||||
|
for (const m of members) {
|
||||||
|
userRoleMap.set(m.userId, m.role)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save context as AgentSessionEntry records (with parent pointers)
|
||||||
|
let prevId: string | null = session.leafId
|
||||||
for (const c of existingComments) {
|
for (const c of existingComments) {
|
||||||
|
// Check if entry already exists for this comment
|
||||||
|
const existingEntry = await prisma.agentSessionEntry.findUnique({
|
||||||
|
where: { id: c.id },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
if (existingEntry) {
|
||||||
|
prevId = existingEntry.id
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
|
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
|
||||||
let messageContent = c.message || ''
|
let messageContent = c.message || ''
|
||||||
|
|
||||||
@@ -547,36 +719,33 @@ export async function initializeAgentSessionActivity(params: {
|
|||||||
const agentName = c.creator?.name || 'Ai Agent'
|
const agentName = c.creator?.name || 'Ai Agent'
|
||||||
messageContent = `[Agent Message][${agentName}]: ${messageContent}`
|
messageContent = `[Agent Message][${agentName}]: ${messageContent}`
|
||||||
} else if (c.creator?.name) {
|
} else if (c.creator?.name) {
|
||||||
messageContent = `[${c.creator.name}]: ${messageContent}`
|
const role = (c.creatorId ? userRoleMap.get(c.creatorId) : undefined) || 'user'
|
||||||
|
messageContent = `[${c.creator.name} (${role})]: ${messageContent}`
|
||||||
}
|
}
|
||||||
|
|
||||||
const entryId = ulid()
|
const entryId = c.id
|
||||||
const message: AgentMessage = {
|
const message: AgentMessage = {
|
||||||
role: 'user',
|
role: 'user',
|
||||||
content: [{ type: 'text', text: messageContent }],
|
content: [{ type: 'text', text: messageContent }],
|
||||||
timestamp: c.createdAt.getTime(),
|
timestamp: c.createdAt.getTime(),
|
||||||
}
|
}
|
||||||
|
|
||||||
const entryJson: SessionTreeEntry = {
|
|
||||||
type: 'message',
|
|
||||||
id: entryId,
|
|
||||||
parentId: prevId,
|
|
||||||
timestamp: c.createdAt.toISOString(),
|
|
||||||
message,
|
|
||||||
}
|
|
||||||
|
|
||||||
await prisma.agentSessionEntry.create({
|
await prisma.agentSessionEntry.create({
|
||||||
data: {
|
data: {
|
||||||
id: entryId,
|
id: entryId,
|
||||||
sessionId,
|
sessionId,
|
||||||
entry: entryJson as unknown as PrismaJson.PiSessionEntry,
|
assetId: userComment.assetId,
|
||||||
|
type: 'message',
|
||||||
|
parentId: prevId,
|
||||||
|
createdAt: c.createdAt,
|
||||||
|
data: { message },
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
prevId = entryId
|
prevId = entryId
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update leafId of the session
|
// Update leafId of the session
|
||||||
if (prevId) {
|
if (prevId && prevId !== session.leafId) {
|
||||||
await prisma.agentSession.update({
|
await prisma.agentSession.update({
|
||||||
where: { id: sessionId },
|
where: { id: sessionId },
|
||||||
data: { leafId: prevId },
|
data: { leafId: prevId },
|
||||||
|
|||||||
@@ -82,7 +82,18 @@ describe('DatabaseSessionStorage', () => {
|
|||||||
|
|
||||||
expect(await storage.getLeafId()).toBeNull()
|
expect(await storage.getLeafId()).toBeNull()
|
||||||
|
|
||||||
await storage.setLeafId('entry-1')
|
const entry: SessionTreeEntry = {
|
||||||
|
type: 'message',
|
||||||
|
id: 'entry-1',
|
||||||
|
parentId: null,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
message: {
|
||||||
|
role: 'user',
|
||||||
|
content: [{ type: 'text', text: 'Test' }],
|
||||||
|
timestamp: Date.now(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
await storage.appendEntry(entry)
|
||||||
expect(await storage.getLeafId()).toBe('entry-1')
|
expect(await storage.getLeafId()).toBe('entry-1')
|
||||||
|
|
||||||
await storage.setLeafId(null)
|
await storage.setLeafId(null)
|
||||||
@@ -223,10 +234,10 @@ describe('DatabaseSessionStorage', () => {
|
|||||||
|
|
||||||
await storage.appendEntry(entry)
|
await storage.appendEntry(entry)
|
||||||
|
|
||||||
// Record entry is generic Json
|
// Record data is generic Json
|
||||||
const record = await prisma.agentSessionEntry.findUnique({ where: { id: 'msg-1' } })
|
const record = await prisma.agentSessionEntry.findUnique({ where: { id: 'msg-1' } })
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const savedEntry = record?.entry as any
|
const savedEntry = record?.data as any
|
||||||
expect(savedEntry.message.content[0].data).toBe('__S3_DATA__')
|
expect(savedEntry.message.content[0].data).toBe('__S3_DATA__')
|
||||||
|
|
||||||
// Verify retrieval reinjects data
|
// Verify retrieval reinjects data
|
||||||
@@ -270,7 +281,7 @@ describe('DatabaseSessionStorage', () => {
|
|||||||
// Verify saved entry is stripped
|
// Verify saved entry is stripped
|
||||||
const record = await prisma.agentSessionEntry.findUnique({ where: { id: 'msg-skill' } })
|
const record = await prisma.agentSessionEntry.findUnique({ where: { id: 'msg-skill' } })
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const savedEntry = record?.entry as any
|
const savedEntry = record?.data as any
|
||||||
expect(savedEntry.message.content[0].text).toBe('__SKILL_CONTENT__')
|
expect(savedEntry.message.content[0].text).toBe('__SKILL_CONTENT__')
|
||||||
|
|
||||||
// Verify retrieval reinjects data
|
// Verify retrieval reinjects data
|
||||||
@@ -503,4 +514,74 @@ describe('DatabaseSessionStorage', () => {
|
|||||||
expect(createScreenshotToolSpy).toHaveBeenCalledWith(user.id, 'new-comment-456')
|
expect(createScreenshotToolSpy).toHaveBeenCalledWith(user.id, 'new-comment-456')
|
||||||
expect(createAnalyzeImageToolSpy).toHaveBeenCalledWith(user.id, 'new-comment-456')
|
expect(createAnalyzeImageToolSpy).toHaveBeenCalledWith(user.id, 'new-comment-456')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('P1 Bug Reproductions', () => {
|
||||||
|
it('should persist a leaf entry and validate targetId when setLeafId is called', async () => {
|
||||||
|
const { agent } = await setupTestData()
|
||||||
|
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
|
||||||
|
|
||||||
|
const msgEntry: SessionTreeEntry = {
|
||||||
|
type: 'message',
|
||||||
|
id: 'msg-100',
|
||||||
|
parentId: null,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
message: {
|
||||||
|
role: 'user',
|
||||||
|
content: [{ type: 'text', text: 'Hello' }],
|
||||||
|
timestamp: Date.now(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
await storage.appendEntry(msgEntry)
|
||||||
|
expect(await storage.getLeafId()).toBe('msg-100')
|
||||||
|
|
||||||
|
// setLeafId to an existing entry
|
||||||
|
await storage.setLeafId('msg-100')
|
||||||
|
|
||||||
|
// Verify that a 'leaf' entry was appended to database entries
|
||||||
|
const entries = await storage.getEntries()
|
||||||
|
const leafEntries = entries.filter((e) => e.type === 'leaf')
|
||||||
|
expect(leafEntries.length).toBe(1)
|
||||||
|
expect(leafEntries[0]).toMatchObject({
|
||||||
|
type: 'leaf',
|
||||||
|
targetId: 'msg-100',
|
||||||
|
})
|
||||||
|
|
||||||
|
// Calling setLeafId with non-existent targetId should throw not_found error
|
||||||
|
await expect(storage.setLeafId('non-existent-id')).rejects.toThrow(
|
||||||
|
'Entry non-existent-id not found',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should execute appendEntry in a single atomic transaction', async () => {
|
||||||
|
const { agent } = await setupTestData()
|
||||||
|
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
|
||||||
|
|
||||||
|
// Mock prisma.agentSession.update to throw an error during setLeafId inside appendEntry
|
||||||
|
const updateSpy = vi
|
||||||
|
.spyOn(prisma.agentSession, 'update')
|
||||||
|
.mockRejectedValueOnce(new Error('DB Update Failed'))
|
||||||
|
|
||||||
|
const entry: SessionTreeEntry = {
|
||||||
|
type: 'message',
|
||||||
|
id: 'atomic-msg-1',
|
||||||
|
parentId: null,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
message: {
|
||||||
|
role: 'user',
|
||||||
|
content: [{ type: 'text', text: 'Atomic test' }],
|
||||||
|
timestamp: Date.now(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
await expect(storage.appendEntry(entry)).rejects.toThrow('DB Update Failed')
|
||||||
|
|
||||||
|
// Because appendEntry should be atomic, atomic-msg-1 must NOT exist in the database
|
||||||
|
const dbEntry = await prisma.agentSessionEntry.findUnique({
|
||||||
|
where: { id: 'atomic-msg-1' },
|
||||||
|
})
|
||||||
|
expect(dbEntry).toBeNull()
|
||||||
|
|
||||||
|
updateSpy.mockRestore()
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import {
|
|||||||
type SessionMetadata,
|
type SessionMetadata,
|
||||||
type SessionStorage,
|
type SessionStorage,
|
||||||
type SessionTreeEntry,
|
type SessionTreeEntry,
|
||||||
type SessionTreeEntryBase,
|
|
||||||
} from '@earendil-works/pi-agent-core'
|
} from '@earendil-works/pi-agent-core'
|
||||||
import { agentService } from '@shumai/core/src/agent/agent'
|
import { agentService } from '@shumai/core/src/agent/agent'
|
||||||
|
|
||||||
@@ -46,16 +45,53 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
|||||||
}
|
}
|
||||||
|
|
||||||
async setLeafId(leafId: string | null): Promise<void> {
|
async setLeafId(leafId: string | null): Promise<void> {
|
||||||
await prisma.agentSession.update({
|
if (leafId === null) {
|
||||||
where: { id: this.sessionId },
|
await prisma.agentSession.update({
|
||||||
data: { leafId },
|
where: { id: this.sessionId },
|
||||||
|
data: { leafId: null },
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.agentSessionEntry.findFirst({
|
||||||
|
where: { id: leafId },
|
||||||
})
|
})
|
||||||
|
if (!existing) {
|
||||||
|
throw new Error(`Entry ${leafId} not found`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentLeafId = await this.getLeafId()
|
||||||
|
const leafEntry: SessionTreeEntry = {
|
||||||
|
type: 'leaf',
|
||||||
|
id: await this.createEntryId(),
|
||||||
|
parentId: currentLeafId,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
targetId: leafId,
|
||||||
|
}
|
||||||
|
await this.appendEntry(leafEntry)
|
||||||
}
|
}
|
||||||
|
|
||||||
async createEntryId(): Promise<string> {
|
async createEntryId(): Promise<string> {
|
||||||
return ulid()
|
return ulid()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private recordToEntry(record: {
|
||||||
|
id: string
|
||||||
|
type: string | null
|
||||||
|
parentId: string | null
|
||||||
|
createdAt: Date
|
||||||
|
data: unknown
|
||||||
|
}): SessionTreeEntry {
|
||||||
|
const payload = (record.data as Record<string, unknown>) || {}
|
||||||
|
return {
|
||||||
|
id: record.id,
|
||||||
|
type: (record.type || 'message') as SessionTreeEntry['type'],
|
||||||
|
parentId: record.parentId,
|
||||||
|
timestamp: record.createdAt.toISOString(),
|
||||||
|
...payload,
|
||||||
|
} as unknown as SessionTreeEntry
|
||||||
|
}
|
||||||
|
|
||||||
async appendEntry(entry: SessionTreeEntry): Promise<void> {
|
async appendEntry(entry: SessionTreeEntry): Promise<void> {
|
||||||
const strippedEntry = structuredClone(entry)
|
const strippedEntry = structuredClone(entry)
|
||||||
|
|
||||||
@@ -96,16 +132,37 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await prisma.agentSessionEntry.create({
|
const targetLeafId = entry.type === 'leaf' ? entry.targetId : entry.id
|
||||||
data: {
|
|
||||||
id: entry.id,
|
// Extract base fields and store type-specific properties in data payload
|
||||||
sessionId: this.sessionId,
|
const payload = { ...strippedEntry } as Record<string, unknown>
|
||||||
entry: strippedEntry,
|
delete payload.id
|
||||||
},
|
delete payload.type
|
||||||
|
delete payload.parentId
|
||||||
|
delete payload.timestamp
|
||||||
|
|
||||||
|
const session = await prisma.agentSession.findUnique({
|
||||||
|
where: { id: this.sessionId },
|
||||||
|
select: { assetId: true },
|
||||||
})
|
})
|
||||||
|
|
||||||
// Auto-update leafId on append
|
await prisma.$transaction([
|
||||||
await this.setLeafId(entry.id)
|
prisma.agentSessionEntry.create({
|
||||||
|
data: {
|
||||||
|
id: entry.id,
|
||||||
|
sessionId: this.sessionId,
|
||||||
|
assetId: session?.assetId || null,
|
||||||
|
type: entry.type,
|
||||||
|
parentId: entry.parentId || null,
|
||||||
|
createdAt: entry.timestamp ? new Date(entry.timestamp) : new Date(),
|
||||||
|
data: payload as PrismaJson.PiSessionEntryData,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.agentSession.update({
|
||||||
|
where: { id: this.sessionId },
|
||||||
|
data: { leafId: targetLeafId },
|
||||||
|
}),
|
||||||
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
async getEntry(id: string): Promise<SessionTreeEntry | undefined> {
|
async getEntry(id: string): Promise<SessionTreeEntry | undefined> {
|
||||||
@@ -113,7 +170,7 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
|||||||
where: { id },
|
where: { id },
|
||||||
})
|
})
|
||||||
if (!record) return undefined
|
if (!record) return undefined
|
||||||
const entry = record.entry as unknown as SessionTreeEntry
|
const entry = this.recordToEntry(record)
|
||||||
await this.reinjectImageDataAsync(entry)
|
await this.reinjectImageDataAsync(entry)
|
||||||
await this.reinjectSkillContentAsync(entry)
|
await this.reinjectSkillContentAsync(entry)
|
||||||
return entry
|
return entry
|
||||||
@@ -125,14 +182,11 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
|||||||
const records = await prisma.agentSessionEntry.findMany({
|
const records = await prisma.agentSessionEntry.findMany({
|
||||||
where: {
|
where: {
|
||||||
sessionId: this.sessionId,
|
sessionId: this.sessionId,
|
||||||
entry: {
|
type,
|
||||||
path: ['type'],
|
|
||||||
equals: type,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
orderBy: { id: 'asc' },
|
orderBy: { id: 'asc' },
|
||||||
})
|
})
|
||||||
const entries = records.map((r) => r.entry as unknown as SessionTreeEntry) as Array<
|
const entries = records.map((r) => this.recordToEntry(r)) as Array<
|
||||||
Extract<SessionTreeEntry, { type: TType }>
|
Extract<SessionTreeEntry, { type: TType }>
|
||||||
>
|
>
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
@@ -143,43 +197,49 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getLabel(id: string): Promise<string | undefined> {
|
async getLabel(id: string): Promise<string | undefined> {
|
||||||
const record = await prisma.agentSessionEntry.findFirst({
|
const entry = await this.getEntry(id)
|
||||||
where: {
|
return (entry as { label?: string } | undefined)?.label
|
||||||
sessionId: this.sessionId,
|
|
||||||
entry: {
|
|
||||||
path: ['id'],
|
|
||||||
equals: id,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
// Entry is generic Json
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
return (record?.entry as any)?.label
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {
|
async getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {
|
||||||
if (!leafId) return []
|
if (!leafId) return []
|
||||||
|
|
||||||
// Fetch all entries for this session in a single query to avoid N+1 problem
|
interface EntryRow {
|
||||||
const records = await prisma.agentSessionEntry.findMany({
|
id: string
|
||||||
where: { sessionId: this.sessionId },
|
type: string | null
|
||||||
})
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||||
|
parent_id: string | null
|
||||||
// Build a map for fast lookup
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||||
const entryMap = new Map<string, SessionTreeEntry>()
|
created_at: Date
|
||||||
for (const record of records) {
|
data: unknown
|
||||||
entryMap.set(record.id, record.entry as unknown as SessionTreeEntry)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const pathEntries: SessionTreeEntry[] = []
|
const rows = await prisma.$queryRaw<EntryRow[]>`
|
||||||
let currentId: string | null = leafId
|
WITH RECURSIVE entry_path AS (
|
||||||
|
SELECT id, type, parent_id, created_at, data, 1 AS depth
|
||||||
|
FROM agent_session_entries
|
||||||
|
WHERE id = ${leafId}
|
||||||
|
|
||||||
while (currentId) {
|
UNION ALL
|
||||||
const entry = entryMap.get(currentId)
|
|
||||||
if (!entry) break
|
SELECT e.id, e.type, e.parent_id, e.created_at, e.data, ep.depth + 1
|
||||||
pathEntries.unshift(entry)
|
FROM agent_session_entries e
|
||||||
currentId = (entry as SessionTreeEntryBase).parentId
|
INNER JOIN entry_path ep ON e.id = ep.parent_id
|
||||||
}
|
)
|
||||||
|
SELECT id, type, parent_id, created_at, data
|
||||||
|
FROM entry_path
|
||||||
|
ORDER BY depth DESC;
|
||||||
|
`
|
||||||
|
|
||||||
|
const pathEntries: SessionTreeEntry[] = rows.map((r) =>
|
||||||
|
this.recordToEntry({
|
||||||
|
id: r.id,
|
||||||
|
type: r.type,
|
||||||
|
parentId: r.parent_id,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
data: r.data,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
// Only reinject image data (which may involve S3 calls) for the entries in the path
|
// Only reinject image data (which may involve S3 calls) for the entries in the path
|
||||||
for (const entry of pathEntries) {
|
for (const entry of pathEntries) {
|
||||||
@@ -187,6 +247,39 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
|||||||
await this.reinjectSkillContentAsync(entry)
|
await this.reinjectSkillContentAsync(entry)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dynamically tag comments that currently have reply threads
|
||||||
|
const entryIds = pathEntries.map((e) => e.id)
|
||||||
|
if (entryIds.length > 0) {
|
||||||
|
const threadCounts = await prisma.assetComment.groupBy({
|
||||||
|
by: ['replyToId'],
|
||||||
|
where: {
|
||||||
|
replyToId: { in: entryIds },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const commentIdsWithThreads = new Set<string>()
|
||||||
|
for (const tc of threadCounts) {
|
||||||
|
if (tc.replyToId) commentIdsWithThreads.add(tc.replyToId)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (commentIdsWithThreads.size > 0) {
|
||||||
|
for (let i = 0; i < pathEntries.length; i++) {
|
||||||
|
const entry = pathEntries[i]
|
||||||
|
if (commentIdsWithThreads.has(entry.id) && entry.type === 'message') {
|
||||||
|
const cloned = structuredClone(entry)
|
||||||
|
const msg = cloned.message as unknown as {
|
||||||
|
content?: Array<{ type: string; text: string }>
|
||||||
|
}
|
||||||
|
if (Array.isArray(msg.content) && msg.content[0] && msg.content[0].type === 'text') {
|
||||||
|
if (!msg.content[0].text.startsWith(`[Thread ID: ${entry.id}]`)) {
|
||||||
|
msg.content[0].text = `[Thread ID: ${entry.id}] ${msg.content[0].text}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pathEntries[i] = cloned
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return pathEntries
|
return pathEntries
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,7 +288,7 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
|||||||
where: { sessionId: this.sessionId },
|
where: { sessionId: this.sessionId },
|
||||||
orderBy: { id: 'asc' },
|
orderBy: { id: 'asc' },
|
||||||
})
|
})
|
||||||
const entries = records.map((r) => r.entry as unknown as SessionTreeEntry)
|
const entries = records.map((r) => this.recordToEntry(r))
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
await this.reinjectImageDataAsync(entry)
|
await this.reinjectImageDataAsync(entry)
|
||||||
await this.reinjectSkillContentAsync(entry)
|
await this.reinjectSkillContentAsync(entry)
|
||||||
|
|||||||
@@ -411,3 +411,78 @@ describe('getModelFromDb', () => {
|
|||||||
expect(model?.api).toBe('google-generative-ai')
|
expect(model?.api).toBe('google-generative-ai')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('createAgentSession sandbox options', () => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
it('should set enableWeakerNestedSandbox based on ENABLE_WEAKER_NESTED_SANDBOX env var', async () => {
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'Test Sandbox Team Env' },
|
||||||
|
})
|
||||||
|
|
||||||
|
await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
id: 'test-agent-env',
|
||||||
|
name: 'Ai Agent Env',
|
||||||
|
email: 'test-agent-env@shumai.ai',
|
||||||
|
type: 'agent',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await prisma.agent.create({
|
||||||
|
data: {
|
||||||
|
id: 'test-agent-env',
|
||||||
|
teamId: team.id,
|
||||||
|
type: 'chat',
|
||||||
|
config: {
|
||||||
|
provider: 'openai',
|
||||||
|
model: 'gpt-4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
||||||
|
vi.spyOn(SandboxManager, 'wrapWithSandbox').mockImplementation(async (cmd) => cmd)
|
||||||
|
|
||||||
|
// Default should be false when env var is unset
|
||||||
|
const oldEnv = process.env.ENABLE_WEAKER_NESTED_SANDBOX
|
||||||
|
delete process.env.ENABLE_WEAKER_NESTED_SANDBOX
|
||||||
|
await createAgentSession({
|
||||||
|
teamId: team.id,
|
||||||
|
agentId: 'test-agent-env',
|
||||||
|
providerName: 'google',
|
||||||
|
modelId: 'gemini',
|
||||||
|
systemPrompt: 'prompt',
|
||||||
|
teamSkills: [],
|
||||||
|
allowedDomains: [],
|
||||||
|
providers: [],
|
||||||
|
})
|
||||||
|
expect(initializeSpy).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ enableWeakerNestedSandbox: false }),
|
||||||
|
expect.any(Function),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Should be true when env var is 'true'
|
||||||
|
process.env.ENABLE_WEAKER_NESTED_SANDBOX = 'true'
|
||||||
|
await createAgentSession({
|
||||||
|
teamId: team.id,
|
||||||
|
agentId: 'test-agent-env',
|
||||||
|
providerName: 'google',
|
||||||
|
modelId: 'gemini',
|
||||||
|
systemPrompt: 'prompt',
|
||||||
|
teamSkills: [],
|
||||||
|
allowedDomains: [],
|
||||||
|
providers: [],
|
||||||
|
})
|
||||||
|
expect(initializeSpy).toHaveBeenLastCalledWith(
|
||||||
|
expect.objectContaining({ enableWeakerNestedSandbox: true }),
|
||||||
|
expect.any(Function),
|
||||||
|
)
|
||||||
|
|
||||||
|
if (oldEnv !== undefined) {
|
||||||
|
process.env.ENABLE_WEAKER_NESTED_SANDBOX = oldEnv
|
||||||
|
} else {
|
||||||
|
delete process.env.ENABLE_WEAKER_NESTED_SANDBOX
|
||||||
|
}
|
||||||
|
initializeSpy.mockRestore()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import { createCreateVersionTool } from './tools/create-version'
|
|||||||
import { createListAssetsTool } from './tools/list-assets'
|
import { createListAssetsTool } from './tools/list-assets'
|
||||||
import { createReadPdfPagesTool } from './tools/read-pdf-pages'
|
import { createReadPdfPagesTool } from './tools/read-pdf-pages'
|
||||||
import { createReadSkillTool } from './tools/read-skill'
|
import { createReadSkillTool } from './tools/read-skill'
|
||||||
|
import { createReadThreadTool } from './tools/read-thread'
|
||||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||||
import { createScreenshotTool } from './tools/screenshot'
|
import { createScreenshotTool } from './tools/screenshot'
|
||||||
|
|
||||||
@@ -196,6 +197,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
|||||||
allowWrite,
|
allowWrite,
|
||||||
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
|
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
|
||||||
},
|
},
|
||||||
|
enableWeakerNestedSandbox: process.env.ENABLE_WEAKER_NESTED_SANDBOX === 'true',
|
||||||
},
|
},
|
||||||
sandboxAskCallback,
|
sandboxAskCallback,
|
||||||
)
|
)
|
||||||
@@ -264,8 +266,15 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
|||||||
})
|
})
|
||||||
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
|
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
|
||||||
const deniedTools = agentConfig?.deniedTools || []
|
const deniedTools = agentConfig?.deniedTools || []
|
||||||
|
const readThread = createReadThreadTool()
|
||||||
const allTools = [...mediaTools, readSkill, sandboxedBash, ...systemTools, ...customTools]
|
const allTools = [
|
||||||
|
...mediaTools,
|
||||||
|
readSkill,
|
||||||
|
readThread,
|
||||||
|
sandboxedBash,
|
||||||
|
...systemTools,
|
||||||
|
...customTools,
|
||||||
|
]
|
||||||
const enabledTools = allTools.filter((tool) => !deniedTools.includes(tool.name))
|
const enabledTools = allTools.filter((tool) => !deniedTools.includes(tool.name))
|
||||||
|
|
||||||
const harness = new AgentHarness({
|
const harness = new AgentHarness({
|
||||||
|
|||||||
@@ -106,11 +106,14 @@ export function createAnalyzeImageTool(
|
|||||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||||
const { buffer, contentType } = await s3Service.getObject(bucket, keyToUse)
|
const { buffer, contentType } = await s3Service.getObject(bucket, keyToUse)
|
||||||
|
|
||||||
|
const mimeType =
|
||||||
|
contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp'
|
||||||
|
|
||||||
const content: ImageContent[] = [
|
const content: ImageContent[] = [
|
||||||
{
|
{
|
||||||
type: 'image',
|
type: 'image',
|
||||||
data: buffer.toString('base64'),
|
data: buffer.toString('base64'),
|
||||||
mimeType: contentType || 'image/webp',
|
mimeType,
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -121,10 +121,12 @@ export function createReadPdfPagesTool(
|
|||||||
|
|
||||||
for (const pageItem of pages) {
|
for (const pageItem of pages) {
|
||||||
const { buffer, contentType } = await s3Service.getObject(bucket, pageItem.key)
|
const { buffer, contentType } = await s3Service.getObject(bucket, pageItem.key)
|
||||||
|
const mimeType =
|
||||||
|
contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp'
|
||||||
content.push({
|
content.push({
|
||||||
type: 'image',
|
type: 'image',
|
||||||
data: buffer.toString('base64'),
|
data: buffer.toString('base64'),
|
||||||
mimeType: contentType || 'image/webp',
|
mimeType,
|
||||||
})
|
})
|
||||||
sourceKeys.push(pageItem.key)
|
sourceKeys.push(pageItem.key)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
|
import { createReadThreadTool } from './read-thread'
|
||||||
|
import { prisma } from '@shumai/db'
|
||||||
|
|
||||||
|
vi.mock('@shumai/db', async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import('@shumai/db')>()
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
prisma: {
|
||||||
|
assetComment: {
|
||||||
|
findUnique: vi.fn(),
|
||||||
|
findMany: vi.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('createReadThreadTool', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return error text when thread root comment is not found', async () => {
|
||||||
|
vi.mocked(prisma.assetComment.findUnique).mockResolvedValue(null)
|
||||||
|
|
||||||
|
const tool = createReadThreadTool()
|
||||||
|
const result = await tool.execute('call-1', { threadId: 'non-existent' })
|
||||||
|
const textContent = (result.content[0] as { text: string }).text
|
||||||
|
|
||||||
|
expect(textContent).toContain('Comment thread with ID "non-existent" not found.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return thread root message and notice when there are no replies', async () => {
|
||||||
|
vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({
|
||||||
|
id: 'root-1',
|
||||||
|
message: 'Initial top-level question',
|
||||||
|
creator: { name: 'Alice' },
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
} as any)
|
||||||
|
vi.mocked(prisma.assetComment.findMany).mockResolvedValue([])
|
||||||
|
|
||||||
|
const tool = createReadThreadTool()
|
||||||
|
const result = await tool.execute('call-2', { threadId: 'root-1' })
|
||||||
|
const textContent = (result.content[0] as { text: string }).text
|
||||||
|
|
||||||
|
expect(textContent).toContain('Thread Root [Alice] (root-1): Initial top-level question')
|
||||||
|
expect(textContent).toContain('(No replies in this thread yet)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return thread root message and formatted replies when replies exist', async () => {
|
||||||
|
vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({
|
||||||
|
id: 'root-1',
|
||||||
|
message: 'Initial top-level question',
|
||||||
|
creator: { name: 'Alice' },
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
} as any)
|
||||||
|
vi.mocked(prisma.assetComment.findMany).mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'reply-1',
|
||||||
|
message: 'First reply to thread',
|
||||||
|
creator: { name: 'Bob' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'reply-2',
|
||||||
|
message: 'Second reply to thread',
|
||||||
|
creator: { name: 'Charlie' },
|
||||||
|
},
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
] as any)
|
||||||
|
|
||||||
|
const tool = createReadThreadTool()
|
||||||
|
const result = await tool.execute('call-3', { threadId: 'root-1' })
|
||||||
|
const textContent = (result.content[0] as { text: string }).text
|
||||||
|
|
||||||
|
expect(textContent).toContain('Thread Root [Alice] (root-1): Initial top-level question')
|
||||||
|
expect(textContent).toContain('- [Bob]: First reply to thread')
|
||||||
|
expect(textContent).toContain('- [Charlie]: Second reply to thread')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { prisma } from '@shumai/db'
|
||||||
|
import { Type } from '@sinclair/typebox'
|
||||||
|
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||||
|
|
||||||
|
const readThreadSchema = Type.Object({
|
||||||
|
threadId: Type.String({ description: 'The comment ID of the thread root' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const createReadThreadTool = (): AgentTool<
|
||||||
|
typeof readThreadSchema,
|
||||||
|
{ threadId: string }
|
||||||
|
> => ({
|
||||||
|
name: 'read_thread',
|
||||||
|
label: 'Read Comment Thread',
|
||||||
|
description: 'Reads all comments and replies inside a specific comment thread.',
|
||||||
|
parameters: readThreadSchema,
|
||||||
|
execute: async (_toolCallId, params) => {
|
||||||
|
const rootComment = await prisma.assetComment.findUnique({
|
||||||
|
where: { id: params.threadId },
|
||||||
|
include: { creator: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!rootComment) {
|
||||||
|
return {
|
||||||
|
content: [{ type: 'text', text: `Comment thread with ID "${params.threadId}" not found.` }],
|
||||||
|
details: { threadId: params.threadId },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const replies = await prisma.assetComment.findMany({
|
||||||
|
where: { replyToId: rootComment.id },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
include: { creator: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
const rootAuthor = rootComment.creator?.name || 'User'
|
||||||
|
let output = `Thread Root [${rootAuthor}] (${rootComment.id}): ${rootComment.message || ''}\n\nReplies (${replies.length}):`
|
||||||
|
|
||||||
|
if (replies.length === 0) {
|
||||||
|
output += '\n(No replies in this thread yet)'
|
||||||
|
} else {
|
||||||
|
for (const reply of replies) {
|
||||||
|
const author = reply.creator?.name || 'User'
|
||||||
|
output += `\n- [${author}]: ${reply.message || ''}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{ type: 'text', text: output }],
|
||||||
|
details: { threadId: params.threadId },
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -102,10 +102,12 @@ export function createScreenshotTool(
|
|||||||
|
|
||||||
for (const shot of screenshots) {
|
for (const shot of screenshots) {
|
||||||
const { buffer, contentType } = await s3Service.getObject(bucket, shot.key)
|
const { buffer, contentType } = await s3Service.getObject(bucket, shot.key)
|
||||||
|
const mimeType =
|
||||||
|
contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp'
|
||||||
content.push({
|
content.push({
|
||||||
type: 'image',
|
type: 'image',
|
||||||
data: buffer.toString('base64'),
|
data: buffer.toString('base64'),
|
||||||
mimeType: contentType || 'image/webp',
|
mimeType,
|
||||||
})
|
})
|
||||||
sourceKeys.push(shot.key)
|
sourceKeys.push(shot.key)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,19 +2,11 @@ import { describe, it, expect } from 'vitest'
|
|||||||
import { AgentChatPromptBuilder } from './agent-chat-prompt-builder'
|
import { AgentChatPromptBuilder } from './agent-chat-prompt-builder'
|
||||||
|
|
||||||
describe('AgentChatPromptBuilder', () => {
|
describe('AgentChatPromptBuilder', () => {
|
||||||
it('should build prompt with baseline configurations (implicit mention, other asset type)', () => {
|
it('should build prompt with baseline configurations', () => {
|
||||||
const builder = new AgentChatPromptBuilder('a1')
|
const builder = new AgentChatPromptBuilder('a1')
|
||||||
const result = builder.build()
|
const result = builder.build()
|
||||||
|
|
||||||
expect(result).toContain('The user is discussing an asset with ID: a1.')
|
expect(result).toContain('The user is discussing an asset with ID: a1.')
|
||||||
expect(result).toContain('The user did not explicitly mention you')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should build prompt with explicit mention', () => {
|
|
||||||
const builder = new AgentChatPromptBuilder('a1').withExplicitMention(true)
|
|
||||||
const result = builder.build()
|
|
||||||
|
|
||||||
expect(result).toContain('The user explicitly mentioned you')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should build prompt with path context', () => {
|
it('should build prompt with path context', () => {
|
||||||
@@ -105,7 +97,6 @@ describe('AgentChatPromptBuilder', () => {
|
|||||||
|
|
||||||
it('should build prompt with all fields combined', () => {
|
it('should build prompt with all fields combined', () => {
|
||||||
const builder = new AgentChatPromptBuilder('a1')
|
const builder = new AgentChatPromptBuilder('a1')
|
||||||
.withExplicitMention(true)
|
|
||||||
.withPathContext('src/main.ts')
|
.withPathContext('src/main.ts')
|
||||||
.withAssetDetails('movie.mp4', 'video/mp4', 12.34, undefined, 'video')
|
.withAssetDetails('movie.mp4', 'video/mp4', 12.34, undefined, 'video')
|
||||||
.withCommentTimestamp(8.2)
|
.withCommentTimestamp(8.2)
|
||||||
@@ -118,7 +109,6 @@ describe('AgentChatPromptBuilder', () => {
|
|||||||
expect(result).toContain('Comment Timestamp: 8.20 seconds')
|
expect(result).toContain('Comment Timestamp: 8.20 seconds')
|
||||||
expect(result).toContain('Asset Path Context:\nsrc/main.ts')
|
expect(result).toContain('Asset Path Context:\nsrc/main.ts')
|
||||||
expect(result).toContain("call the 'screenshot' tool")
|
expect(result).toContain("call the 'screenshot' tool")
|
||||||
expect(result).toContain('The user explicitly mentioned you')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should build prompt with attached files and referenced assets', () => {
|
it('should build prompt with attached files and referenced assets', () => {
|
||||||
@@ -164,4 +154,11 @@ describe('AgentChatPromptBuilder', () => {
|
|||||||
expect(result).toContain('File Name: new-folder')
|
expect(result).toContain('File Name: new-folder')
|
||||||
expect(result).toContain('Asset Path Context:\nprojects/my-proj/new-folder')
|
expect(result).toContain('Asset Path Context:\nprojects/my-proj/new-folder')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('should build prompt with user info when provided and not continuation', () => {
|
||||||
|
const builder = new AgentChatPromptBuilder('a1').withUserInfo('Alice', 'owner')
|
||||||
|
const result = builder.build()
|
||||||
|
|
||||||
|
expect(result).toContain('User Info:\nName: Alice\nRole: owner')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ export class AgentChatPromptBuilder {
|
|||||||
private totalPages?: number
|
private totalPages?: number
|
||||||
private commentTimestamp?: number
|
private commentTimestamp?: number
|
||||||
private pathContext?: string
|
private pathContext?: string
|
||||||
private explicitMention = false
|
|
||||||
private attachedFiles: string[] = []
|
private attachedFiles: string[] = []
|
||||||
private referencedAssets: string[] = []
|
private referencedAssets: string[] = []
|
||||||
|
private userInfo?: { name: string; role: string }
|
||||||
|
|
||||||
private isContinuation = false
|
private isContinuation = false
|
||||||
private hasAssetChanged = false
|
private hasAssetChanged = false
|
||||||
@@ -25,6 +25,13 @@ export class AgentChatPromptBuilder {
|
|||||||
this.assetId = assetId
|
this.assetId = assetId
|
||||||
}
|
}
|
||||||
|
|
||||||
|
withUserInfo(name?: string, role?: string): this {
|
||||||
|
if (name) {
|
||||||
|
this.userInfo = { name, role: role || 'user' }
|
||||||
|
}
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
withContinuation(isContinuation: boolean): this {
|
withContinuation(isContinuation: boolean): this {
|
||||||
this.isContinuation = isContinuation
|
this.isContinuation = isContinuation
|
||||||
return this
|
return this
|
||||||
@@ -76,11 +83,6 @@ export class AgentChatPromptBuilder {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
withExplicitMention(explicitMention?: boolean): this {
|
|
||||||
this.explicitMention = !!explicitMention
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
build(): string {
|
build(): string {
|
||||||
const effectiveType = this.proxyType
|
const effectiveType = this.proxyType
|
||||||
|
|
||||||
@@ -164,7 +166,7 @@ export class AgentChatPromptBuilder {
|
|||||||
if (effectiveType) {
|
if (effectiveType) {
|
||||||
const type = getSimpleMediaType(effectiveType)
|
const type = getSimpleMediaType(effectiveType)
|
||||||
if (type === 'image') {
|
if (type === 'image') {
|
||||||
instruction += `\n\nIf you need to view the image data, call the 'analyze_image' tool. It does not require any parameters.`
|
instruction += `\n\nIf you need to view the image data, call the 'analyze_image' tool with assetId "${this.assetId}".`
|
||||||
} else if (type === 'video') {
|
} else if (type === 'video') {
|
||||||
instruction += `\n\nIf you need to view visual frames or take screenshots of the video, call the 'screenshot' tool. You must specify the 'start' (seconds), 'end' (seconds), and 'count' (number of screenshots) parameters.`
|
instruction += `\n\nIf you need to view visual frames or take screenshots of the video, call the 'screenshot' tool. You must specify the 'start' (seconds), 'end' (seconds), and 'count' (number of screenshots) parameters.`
|
||||||
} else if (type === 'pdf') {
|
} else if (type === 'pdf') {
|
||||||
@@ -172,10 +174,8 @@ export class AgentChatPromptBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.explicitMention) {
|
if (this.userInfo) {
|
||||||
instruction += `\n\nThe user explicitly mentioned you in their message. You MUST reply to this message.`
|
instruction += `\n\nUser Info:\nName: ${this.userInfo.name}\nRole: ${this.userInfo.role}`
|
||||||
} else {
|
|
||||||
instruction += `\n\nThe user did not explicitly mention you, but is replying in a thread where you are the participant. Let's decide if you should reply or not. If the user is not directly addressing you or doesn't need a response from you, you may choose to not reply. To choose not to reply, respond with exactly and only the text: __NO_REPLY__.`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return instruction
|
return instruction
|
||||||
|
|||||||
@@ -49,12 +49,16 @@ describe('Agent Chat Workflow', () => {
|
|||||||
generateSessionNameActivity: Object.assign(vi.fn(), {
|
generateSessionNameActivity: Object.assign(vi.fn(), {
|
||||||
_activityName: 'generateSessionNameActivity',
|
_activityName: 'generateSessionNameActivity',
|
||||||
}),
|
}),
|
||||||
|
getUserTeamInfoActivity: Object.assign(vi.fn(), {
|
||||||
|
_activityName: 'getUserTeamInfoActivity',
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
|
|
||||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||||
mockActivities.generateSessionNameActivity.mockResolvedValue(undefined)
|
mockActivities.generateSessionNameActivity.mockResolvedValue(undefined)
|
||||||
|
mockActivities.getUserTeamInfoActivity.mockResolvedValue({ name: 'Test User', role: 'owner' })
|
||||||
mockActivities.getAssetActivity.mockResolvedValue({
|
mockActivities.getAssetActivity.mockResolvedValue({
|
||||||
id: 'a1',
|
id: 'a1',
|
||||||
project: { teamId: 't1' },
|
project: { teamId: 't1' },
|
||||||
@@ -95,7 +99,7 @@ describe('Agent Chat Workflow', () => {
|
|||||||
assetId: 'a1',
|
assetId: 'a1',
|
||||||
payload: {
|
payload: {
|
||||||
projectId: 'p1',
|
projectId: 'p1',
|
||||||
agent: { userCommentId: 'c1', agentId: 'b1', explicitMention: true },
|
agent: { userCommentId: 'c1', agentId: 'b1' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -136,7 +140,6 @@ describe('Agent Chat Workflow', () => {
|
|||||||
.withPathContext('Path: folder/subfolder/file.png')
|
.withPathContext('Path: folder/subfolder/file.png')
|
||||||
.withAssetDetails('test-file.png', 'image/png', undefined, undefined, 'image')
|
.withAssetDetails('test-file.png', 'image/png', undefined, undefined, 'image')
|
||||||
.withCommentTimestamp(null)
|
.withCommentTimestamp(null)
|
||||||
.withExplicitMention(true)
|
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||||
@@ -203,7 +206,6 @@ describe('Agent Chat Workflow', () => {
|
|||||||
.withPathContext('Path: folder/subfolder/file.png')
|
.withPathContext('Path: folder/subfolder/file.png')
|
||||||
.withAssetDetails('test-file.png', 'image/png', undefined)
|
.withAssetDetails('test-file.png', 'image/png', undefined)
|
||||||
.withCommentTimestamp(null)
|
.withCommentTimestamp(null)
|
||||||
.withExplicitMention(false)
|
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||||
@@ -217,52 +219,6 @@ describe('Agent Chat Workflow', () => {
|
|||||||
expect(mockActivities.generateSessionNameActivity).not.toHaveBeenCalled()
|
expect(mockActivities.generateSessionNameActivity).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should delete placeholder comment and finish when AI responds with __NO_REPLY__', async () => {
|
|
||||||
mockActivities.agentChatActivity.mockResolvedValue({
|
|
||||||
text: '__NO_REPLY__',
|
|
||||||
sessionId: 'session-123',
|
|
||||||
})
|
|
||||||
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'chat',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: 'a1',
|
|
||||||
payload: {
|
|
||||||
projectId: 'p1',
|
|
||||||
agent: { userCommentId: 'c1', agentId: 'b1', explicitMention: false },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
await agentChat(task)
|
|
||||||
|
|
||||||
// Verify instruction contains not explicitly mentioned instructions
|
|
||||||
const expectedInstruction3 = new AgentChatPromptBuilder('a1')
|
|
||||||
.withPathContext('Path: folder/subfolder/file.png')
|
|
||||||
.withAssetDetails('test-file.png', 'image/png', undefined, undefined, 'image')
|
|
||||||
.withCommentTimestamp(null)
|
|
||||||
.withExplicitMention(false)
|
|
||||||
.build()
|
|
||||||
|
|
||||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
agentsInstruction: expectedInstruction3,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Verify placeholder comment is deleted
|
|
||||||
expect(mockActivities.deleteCommentActivity).toHaveBeenCalledWith('comment-placeholder-id')
|
|
||||||
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
|
|
||||||
|
|
||||||
// Verify task still completes successfully
|
|
||||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
|
||||||
taskId: task.id,
|
|
||||||
status: 'completed',
|
|
||||||
output: { sessionId: 'session-123' },
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should collect S3 keys for image attachments from the user comment', async () => {
|
it('should collect S3 keys for image attachments from the user comment', async () => {
|
||||||
mockActivities.getCommentActivity.mockResolvedValue({
|
mockActivities.getCommentActivity.mockResolvedValue({
|
||||||
id: 'c1',
|
id: 'c1',
|
||||||
@@ -311,7 +267,6 @@ describe('Agent Chat Workflow', () => {
|
|||||||
.withPathContext('Path: folder/subfolder/file.png')
|
.withPathContext('Path: folder/subfolder/file.png')
|
||||||
.withAssetDetails('test-file.png', 'image/png', undefined, undefined, 'image')
|
.withAssetDetails('test-file.png', 'image/png', undefined, undefined, 'image')
|
||||||
.withCommentTimestamp(null)
|
.withCommentTimestamp(null)
|
||||||
.withExplicitMention(false)
|
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||||
@@ -354,7 +309,6 @@ describe('Agent Chat Workflow', () => {
|
|||||||
.withPathContext('Path: folder/subfolder/file.png')
|
.withPathContext('Path: folder/subfolder/file.png')
|
||||||
.withAssetDetails('test-asset', 'video/mp4', 10)
|
.withAssetDetails('test-asset', 'video/mp4', 10)
|
||||||
.withCommentTimestamp(null)
|
.withCommentTimestamp(null)
|
||||||
.withExplicitMention(false)
|
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||||
@@ -468,7 +422,6 @@ describe('Agent Chat Workflow', () => {
|
|||||||
prompt: 'chatbot prompt',
|
prompt: 'chatbot prompt',
|
||||||
attachedFiles: ['file-attachment-1'],
|
attachedFiles: ['file-attachment-1'],
|
||||||
assetIds: ['referenced-asset-1'],
|
assetIds: ['referenced-asset-1'],
|
||||||
explicitMention: true,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -486,7 +439,6 @@ describe('Agent Chat Workflow', () => {
|
|||||||
.withPathContext('folder/subfolder/file.png')
|
.withPathContext('folder/subfolder/file.png')
|
||||||
.withAssetDetails('test-file.png', 'image/png', undefined)
|
.withAssetDetails('test-file.png', 'image/png', undefined)
|
||||||
.withCommentTimestamp(undefined)
|
.withCommentTimestamp(undefined)
|
||||||
.withExplicitMention(true)
|
|
||||||
.withAttachedFiles([
|
.withAttachedFiles([
|
||||||
'- Name: attachment.png (ID: file-attachment-1, Type: file, Media Type: image/png, Project ID: p1, Path: attachment.png)',
|
'- Name: attachment.png (ID: file-attachment-1, Type: file, Media Type: image/png, Project ID: p1, Path: attachment.png)',
|
||||||
])
|
])
|
||||||
@@ -507,7 +459,6 @@ describe('Agent Chat Workflow', () => {
|
|||||||
sessionId: 'session-direct-123',
|
sessionId: 'session-direct-123',
|
||||||
userId: undefined,
|
userId: undefined,
|
||||||
userCommentId: undefined,
|
userCommentId: undefined,
|
||||||
explicitMention: true,
|
|
||||||
context: { agent: { id: 'b1' } },
|
context: { agent: { id: 'b1' } },
|
||||||
attachedAssets: [
|
attachedAssets: [
|
||||||
{ id: 'file-attachment-1', name: 'attachment.png', type: 'file' },
|
{ id: 'file-attachment-1', name: 'attachment.png', type: 'file' },
|
||||||
@@ -567,4 +518,37 @@ describe('Agent Chat Workflow', () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('should inject user info for 1-on-1 new chat sessions', async () => {
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'chat',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: 'a1',
|
||||||
|
payload: {
|
||||||
|
projectId: 'p1',
|
||||||
|
agent: {
|
||||||
|
prompt: 'Hello agent from 1-on-1 chat',
|
||||||
|
sessionId: 'session-new-1-on-1',
|
||||||
|
agentId: 'b1',
|
||||||
|
userId: 'user-alice',
|
||||||
|
isNewChat: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await agentChat(task)
|
||||||
|
|
||||||
|
expect(mockActivities.getUserTeamInfoActivity).toHaveBeenCalledWith({
|
||||||
|
userId: 'user-alice',
|
||||||
|
teamId: 't1',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
agentsInstruction: expect.stringContaining('User Info:\nName: Test User\nRole: owner'),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -14,10 +14,10 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
updateCommentActivity,
|
updateCommentActivity,
|
||||||
updateTaskUsageActivity,
|
updateTaskUsageActivity,
|
||||||
getAgentWorkerQueueActivity,
|
getAgentWorkerQueueActivity,
|
||||||
deleteCommentActivity,
|
|
||||||
initializeAgentSessionActivity,
|
initializeAgentSessionActivity,
|
||||||
getAssetPathContextActivity,
|
getAssetPathContextActivity,
|
||||||
generateSessionNameActivity,
|
generateSessionNameActivity,
|
||||||
|
getUserTeamInfoActivity,
|
||||||
} = getActivities()
|
} = getActivities()
|
||||||
|
|
||||||
let placeholderCommentId: string | undefined
|
let placeholderCommentId: string | undefined
|
||||||
@@ -162,17 +162,29 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let userInfo: { name: string; role: string } | null = null
|
||||||
|
if (!userCommentId && isNewChat && payload.agent?.userId) {
|
||||||
|
userInfo = await executeActivity(agentWorkerQueue, getUserTeamInfoActivity, {
|
||||||
|
userId: payload.agent.userId,
|
||||||
|
teamId,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const proxyType = (asset.media as PrismaJson.MediaInfo | null)?.proxyType
|
const proxyType = (asset.media as PrismaJson.MediaInfo | null)?.proxyType
|
||||||
const instruction = new AgentChatPromptBuilder(asset.id)
|
const promptBuilder = new AgentChatPromptBuilder(asset.id)
|
||||||
.withContinuation(!isNewChat)
|
.withContinuation(!isNewChat)
|
||||||
.withAssetChanged(payload.agent?.hasAssetChanged)
|
.withAssetChanged(payload.agent?.hasAssetChanged)
|
||||||
.withPathContext(pathContext)
|
.withPathContext(pathContext)
|
||||||
.withAssetDetails(asset.name, asset.mediaType, duration, totalPages, proxyType)
|
.withAssetDetails(asset.name, asset.mediaType, duration, totalPages, proxyType)
|
||||||
.withCommentTimestamp(commentTimestamp)
|
.withCommentTimestamp(commentTimestamp)
|
||||||
.withExplicitMention(payload.agent?.explicitMention)
|
|
||||||
.withAttachedFiles(attachedFileDetailsList)
|
.withAttachedFiles(attachedFileDetailsList)
|
||||||
.withReferencedAssets(referencedAssetDetailsList)
|
.withReferencedAssets(referencedAssetDetailsList)
|
||||||
.build()
|
|
||||||
|
if (userInfo) {
|
||||||
|
promptBuilder.withUserInfo(userInfo.name, userInfo.role)
|
||||||
|
}
|
||||||
|
|
||||||
|
const instruction = promptBuilder.build()
|
||||||
|
|
||||||
// 6. Call AI Chat
|
// 6. Call AI Chat
|
||||||
let folderId = ''
|
let folderId = ''
|
||||||
@@ -194,7 +206,6 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
sessionId,
|
sessionId,
|
||||||
userId: payload.agent?.userId,
|
userId: payload.agent?.userId,
|
||||||
userCommentId: userCommentId || undefined,
|
userCommentId: userCommentId || undefined,
|
||||||
explicitMention: payload.agent?.explicitMention,
|
|
||||||
context,
|
context,
|
||||||
attachedAssets,
|
attachedAssets,
|
||||||
})
|
})
|
||||||
@@ -213,15 +224,11 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
// 7. Update Placeholder Comment
|
// 7. Update Placeholder Comment
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId) {
|
||||||
if (aiResult.text.trim() === '__NO_REPLY__') {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
await executeActivity(agentWorkerQueue, deleteCommentActivity, placeholderCommentId)
|
commentId: placeholderCommentId,
|
||||||
} else {
|
message: aiResult.text,
|
||||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
sessionId: aiResult.sessionId,
|
||||||
commentId: placeholderCommentId,
|
})
|
||||||
message: aiResult.text,
|
|
||||||
sessionId: aiResult.sessionId,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 8. Update Usage
|
// 8. Update Usage
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/api",
|
"name": "@shumai/api",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/core",
|
"name": "@shumai/core",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
|
|||||||
@@ -286,5 +286,57 @@ describe('AgentService', () => {
|
|||||||
expect(agents[0].provider).toBeDefined()
|
expect(agents[0].provider).toBeDefined()
|
||||||
expect(agents[0].modelRef).toBeDefined()
|
expect(agents[0].modelRef).toBeDefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('getSessionEntries follows parentId across shared sessions', async () => {
|
||||||
|
const db = prisma
|
||||||
|
const svc = new AgentService()
|
||||||
|
const { agent } = await setupTestData(db)
|
||||||
|
|
||||||
|
const mainSession = await db.agentSession.create({
|
||||||
|
data: {
|
||||||
|
agentId: agent.id,
|
||||||
|
type: 'comment',
|
||||||
|
cwd: '/tmp',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const threadSession = await db.agentSession.create({
|
||||||
|
data: {
|
||||||
|
agentId: agent.id,
|
||||||
|
type: 'comment',
|
||||||
|
cwd: '/tmp',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const entry1 = await db.agentSessionEntry.create({
|
||||||
|
data: {
|
||||||
|
id: '01ENTRY0000000000000000001',
|
||||||
|
sessionId: mainSession.id,
|
||||||
|
type: 'message',
|
||||||
|
parentId: null,
|
||||||
|
data: { text: 'Main Entry 1' },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const entry2 = await db.agentSessionEntry.create({
|
||||||
|
data: {
|
||||||
|
id: '01ENTRY0000000000000000002',
|
||||||
|
sessionId: threadSession.id,
|
||||||
|
type: 'message',
|
||||||
|
parentId: entry1.id,
|
||||||
|
data: { text: 'Thread Entry 2' },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await db.agentSession.update({
|
||||||
|
where: { id: threadSession.id },
|
||||||
|
data: { leafId: entry2.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const entries = await svc.getSessionEntries({ sessionId: threadSession.id })
|
||||||
|
expect(entries).toHaveLength(2)
|
||||||
|
expect(entries[0].id).toBe(entry1.id)
|
||||||
|
expect(entries[1].id).toBe(entry2.id)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -330,9 +330,62 @@ export class AgentService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getSessionEntries(params: { sessionId: string }) {
|
async getSessionEntries(params: { sessionId: string }) {
|
||||||
return this.prismaClient.agentSessionEntry.findMany({
|
const session = await this.prismaClient.agentSession.findUnique({
|
||||||
where: { sessionId: params.sessionId },
|
where: { id: params.sessionId },
|
||||||
orderBy: { id: 'asc' },
|
select: { leafId: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!session?.leafId) {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EntryRow {
|
||||||
|
id: string
|
||||||
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||||
|
session_id: string | null
|
||||||
|
type: string | null
|
||||||
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||||
|
parent_id: string | null
|
||||||
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||||
|
created_at: Date
|
||||||
|
data: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await this.prismaClient.$queryRaw<EntryRow[]>`
|
||||||
|
WITH RECURSIVE entry_path AS (
|
||||||
|
SELECT id, session_id, type, parent_id, created_at, data, 1 AS depth
|
||||||
|
FROM agent_session_entries
|
||||||
|
WHERE id = ${session.leafId}
|
||||||
|
|
||||||
|
UNION ALL
|
||||||
|
|
||||||
|
SELECT e.id, e.session_id, e.type, e.parent_id, e.created_at, e.data, ep.depth + 1
|
||||||
|
FROM agent_session_entries e
|
||||||
|
INNER JOIN entry_path ep ON e.id = ep.parent_id
|
||||||
|
)
|
||||||
|
SELECT id, session_id, type, parent_id, created_at, data
|
||||||
|
FROM entry_path
|
||||||
|
ORDER BY depth DESC;
|
||||||
|
`
|
||||||
|
|
||||||
|
return rows.map((r) => {
|
||||||
|
const payload = (r.data as Record<string, unknown>) || {}
|
||||||
|
const entryObj = {
|
||||||
|
id: r.id,
|
||||||
|
type: r.type || 'message',
|
||||||
|
parentId: r.parent_id,
|
||||||
|
timestamp: r.created_at.toISOString(),
|
||||||
|
...payload,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: r.id,
|
||||||
|
sessionId: r.session_id || params.sessionId,
|
||||||
|
type: r.type,
|
||||||
|
parentId: r.parent_id,
|
||||||
|
data: r.data,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
entry: entryObj,
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1144,7 +1144,6 @@ describe('AssetService', () => {
|
|||||||
const p1 = tasksRule1[0].payload
|
const p1 = tasksRule1[0].payload
|
||||||
expect(p1?.agent?.agentId).toBe(agent.id)
|
expect(p1?.agent?.agentId).toBe(agent.id)
|
||||||
expect(p1?.agent?.sessionId).toBeUndefined()
|
expect(p1?.agent?.sessionId).toBeUndefined()
|
||||||
expect(p1?.agent?.explicitMention).toBe(true)
|
|
||||||
expect(p1?.agent?.userId).toBe(user.id)
|
expect(p1?.agent?.userId).toBe(user.id)
|
||||||
|
|
||||||
// Rule 2: user mentions agent in reply, and root is not an agent comment
|
// Rule 2: user mentions agent in reply, and root is not an agent comment
|
||||||
@@ -1163,7 +1162,6 @@ describe('AssetService', () => {
|
|||||||
const p2 = tasksRule2[0].payload
|
const p2 = tasksRule2[0].payload
|
||||||
expect(p2?.agent?.agentId).toBe(agent.id)
|
expect(p2?.agent?.agentId).toBe(agent.id)
|
||||||
expect(p2?.agent?.sessionId).toBeUndefined()
|
expect(p2?.agent?.sessionId).toBeUndefined()
|
||||||
expect(p2?.agent?.explicitMention).toBe(true)
|
|
||||||
expect(p2?.agent?.userId).toBe(user.id)
|
expect(p2?.agent?.userId).toBe(user.id)
|
||||||
|
|
||||||
// Create a root user comment
|
// Create a root user comment
|
||||||
@@ -1195,7 +1193,7 @@ describe('AssetService', () => {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// Rule 3a: any user creates a reply directly to the agent comment, no explicit mention
|
// Rule 3a: any user creates a reply directly to the agent comment, no explicit mention -> NO task created
|
||||||
const reply3a = await assetService.createComment({
|
const reply3a = await assetService.createComment({
|
||||||
assetId: file.id,
|
assetId: file.id,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
@@ -1216,12 +1214,7 @@ describe('AssetService', () => {
|
|||||||
payload: { path: ['agent', 'userCommentId'], equals: reply3a.id },
|
payload: { path: ['agent', 'userCommentId'], equals: reply3a.id },
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
expect(tasksRule3a.length).toBe(1)
|
expect(tasksRule3a.length).toBe(0)
|
||||||
const p3a = tasksRule3a[0].payload
|
|
||||||
expect(p3a?.agent?.agentId).toBe(botUser.id)
|
|
||||||
expect(p3a?.agent?.sessionId).toBe('test-session-rule3')
|
|
||||||
expect(p3a?.agent?.explicitMention).toBe(false)
|
|
||||||
expect(p3a?.agent?.userId).toBe(user.id)
|
|
||||||
|
|
||||||
// Rule 3b: any user creates a reply directly to the agent comment, explicitly mentions agent
|
// Rule 3b: any user creates a reply directly to the agent comment, explicitly mentions agent
|
||||||
const reply3b = await assetService.createComment({
|
const reply3b = await assetService.createComment({
|
||||||
@@ -1248,7 +1241,6 @@ describe('AssetService', () => {
|
|||||||
const p3b = tasksRule3b[0].payload
|
const p3b = tasksRule3b[0].payload
|
||||||
expect(p3b?.agent?.agentId).toBe(botUser.id)
|
expect(p3b?.agent?.agentId).toBe(botUser.id)
|
||||||
expect(p3b?.agent?.sessionId).toBe('test-session-rule3')
|
expect(p3b?.agent?.sessionId).toBe('test-session-rule3')
|
||||||
expect(p3b?.agent?.explicitMention).toBe(true)
|
|
||||||
expect(p3b?.agent?.userId).toBe(user.id)
|
expect(p3b?.agent?.userId).toBe(user.id)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1323,8 +1323,7 @@ export class AssetService {
|
|||||||
const isRootAgent = !!rootSessionId || parentComment.creator?.type === 'agent'
|
const isRootAgent = !!rootSessionId || parentComment.creator?.type === 'agent'
|
||||||
const rootAgentId = parentComment.creatorId
|
const rootAgentId = parentComment.creatorId
|
||||||
|
|
||||||
if (isRootAgent && rootAgentId) {
|
if (isRootAgent && rootAgentId && mentionedAgentIds.has(rootAgentId)) {
|
||||||
const explicitMention = mentionedAgentIds.has(rootAgentId)
|
|
||||||
await tx.workflowTask.create({
|
await tx.workflowTask.create({
|
||||||
data: {
|
data: {
|
||||||
assetId: a.id,
|
assetId: a.id,
|
||||||
@@ -1338,7 +1337,6 @@ export class AssetService {
|
|||||||
userCommentId: comment.id,
|
userCommentId: comment.id,
|
||||||
agentId: rootAgentId,
|
agentId: rootAgentId,
|
||||||
sessionId: rootSessionId || undefined,
|
sessionId: rootSessionId || undefined,
|
||||||
explicitMention,
|
|
||||||
userId: req.userId,
|
userId: req.userId,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1373,7 +1371,6 @@ export class AssetService {
|
|||||||
agent: {
|
agent: {
|
||||||
userCommentId: comment.id,
|
userCommentId: comment.id,
|
||||||
agentId: agentId,
|
agentId: agentId,
|
||||||
explicitMention: true,
|
|
||||||
userId: req.userId,
|
userId: req.userId,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -299,20 +299,23 @@ describe('ChatService', () => {
|
|||||||
data: {
|
data: {
|
||||||
id: 'test-entry-id',
|
id: 'test-entry-id',
|
||||||
sessionId,
|
sessionId,
|
||||||
entry: {
|
type: 'message',
|
||||||
type: 'message',
|
parentId: null,
|
||||||
id: 'test-entry-id',
|
data: {
|
||||||
parentId: null,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
message: {
|
message: {
|
||||||
role: 'user',
|
role: 'user',
|
||||||
content: [{ type: 'text', text: 'hello' }],
|
content: [{ type: 'text', text: 'hello' }],
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
},
|
},
|
||||||
},
|
} as PrismaJson.PiSessionEntryData,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await prisma.agentSession.update({
|
||||||
|
where: { id: sessionId },
|
||||||
|
data: { leafId: 'test-entry-id' },
|
||||||
|
})
|
||||||
|
|
||||||
const messages = await chatService.listMessages(user.id, team.id, sessionId)
|
const messages = await chatService.listMessages(user.id, team.id, sessionId)
|
||||||
expect(messages).toHaveLength(1)
|
expect(messages).toHaveLength(1)
|
||||||
// Casting to any to access properties of union in test assertions
|
// Casting to any to access properties of union in test assertions
|
||||||
@@ -336,17 +339,15 @@ describe('ChatService', () => {
|
|||||||
data: {
|
data: {
|
||||||
id: 'test-entry-1-user',
|
id: 'test-entry-1-user',
|
||||||
sessionId,
|
sessionId,
|
||||||
entry: {
|
type: 'message',
|
||||||
type: 'message',
|
parentId: null,
|
||||||
id: 'test-entry-1-user',
|
data: {
|
||||||
parentId: null,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
message: {
|
message: {
|
||||||
role: 'user',
|
role: 'user',
|
||||||
content: [{ type: 'text', text: 'hello' }],
|
content: [{ type: 'text', text: 'hello' }],
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
},
|
},
|
||||||
} as unknown as PrismaJson.PiSessionEntry,
|
} as PrismaJson.PiSessionEntryData,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -355,15 +356,13 @@ describe('ChatService', () => {
|
|||||||
data: {
|
data: {
|
||||||
id: 'test-entry-2-context',
|
id: 'test-entry-2-context',
|
||||||
sessionId,
|
sessionId,
|
||||||
entry: {
|
type: 'custom_message',
|
||||||
type: 'custom_message',
|
parentId: 'test-entry-1-user',
|
||||||
id: 'test-entry-2-context',
|
data: {
|
||||||
parentId: 'test-entry-1-user',
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
customType: 'context',
|
customType: 'context',
|
||||||
content: 'some context',
|
content: 'some context',
|
||||||
display: 'chat',
|
display: 'chat',
|
||||||
} as unknown as PrismaJson.PiSessionEntry,
|
} as PrismaJson.PiSessionEntryData,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -372,13 +371,11 @@ describe('ChatService', () => {
|
|||||||
data: {
|
data: {
|
||||||
id: 'test-entry-3-thinking',
|
id: 'test-entry-3-thinking',
|
||||||
sessionId,
|
sessionId,
|
||||||
entry: {
|
type: 'thinking_level_change',
|
||||||
type: 'thinking_level_change',
|
parentId: 'test-entry-2-context',
|
||||||
id: 'test-entry-3-thinking',
|
data: {
|
||||||
parentId: 'test-entry-2-context',
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
thinkingLevel: 'deep',
|
thinkingLevel: 'deep',
|
||||||
} as unknown as PrismaJson.PiSessionEntry,
|
} as PrismaJson.PiSessionEntryData,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -387,19 +384,22 @@ describe('ChatService', () => {
|
|||||||
data: {
|
data: {
|
||||||
id: 'test-entry-4-display',
|
id: 'test-entry-4-display',
|
||||||
sessionId,
|
sessionId,
|
||||||
entry: {
|
type: 'custom',
|
||||||
type: 'custom',
|
parentId: 'test-entry-3-thinking',
|
||||||
id: 'test-entry-4-display',
|
data: {
|
||||||
parentId: 'test-entry-3-thinking',
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
customType: 'context_display_info',
|
customType: 'context_display_info',
|
||||||
data: {
|
data: {
|
||||||
assets: [{ id: 'a1', name: 'File A', type: 'file' }],
|
assets: [{ id: 'a1', name: 'File A', type: 'file' }],
|
||||||
},
|
},
|
||||||
} as unknown as PrismaJson.PiSessionEntry,
|
} as PrismaJson.PiSessionEntryData,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await prisma.agentSession.update({
|
||||||
|
where: { id: sessionId },
|
||||||
|
data: { leafId: 'test-entry-4-display' },
|
||||||
|
})
|
||||||
|
|
||||||
// Verify listMessages returns only the user, thinking level change and custom display entry message
|
// Verify listMessages returns only the user, thinking level change and custom display entry message
|
||||||
const messages = await chatService.listMessages(user.id, team.id, sessionId)
|
const messages = await chatService.listMessages(user.id, team.id, sessionId)
|
||||||
expect(messages).toHaveLength(3)
|
expect(messages).toHaveLength(3)
|
||||||
@@ -539,16 +539,14 @@ describe('ChatService', () => {
|
|||||||
data: {
|
data: {
|
||||||
id: 'entry-id-1',
|
id: 'entry-id-1',
|
||||||
sessionId,
|
sessionId,
|
||||||
entry: {
|
type: 'message',
|
||||||
type: 'message',
|
parentId: null,
|
||||||
id: 'entry-id-1',
|
data: {
|
||||||
parentId: null,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
message: {
|
message: {
|
||||||
role: 'user',
|
role: 'user',
|
||||||
content: [{ type: 'text', text: 'msg 1' }],
|
content: [{ type: 'text', text: 'msg 1' }],
|
||||||
},
|
},
|
||||||
} as unknown as PrismaJson.PiSessionEntry,
|
} as PrismaJson.PiSessionEntryData,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -556,16 +554,14 @@ describe('ChatService', () => {
|
|||||||
data: {
|
data: {
|
||||||
id: 'entry-id-2',
|
id: 'entry-id-2',
|
||||||
sessionId,
|
sessionId,
|
||||||
entry: {
|
type: 'message',
|
||||||
type: 'message',
|
parentId: 'entry-id-1',
|
||||||
id: 'entry-id-2',
|
data: {
|
||||||
parentId: 'entry-id-1',
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
message: {
|
message: {
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: [{ type: 'text', text: 'msg 2' }],
|
content: [{ type: 'text', text: 'msg 2' }],
|
||||||
},
|
},
|
||||||
} as unknown as PrismaJson.PiSessionEntry,
|
} as PrismaJson.PiSessionEntryData,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { paginateQuery, type PaginatedData } from '@shumai/core/src/pagination'
|
|||||||
import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos'
|
import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos'
|
||||||
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||||
import { workflowService } from '@shumai/workflow-core'
|
import { workflowService } from '@shumai/workflow-core'
|
||||||
|
import { agentService } from '@shumai/core/src/agent/agent'
|
||||||
|
|
||||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||||
|
|
||||||
@@ -100,14 +101,22 @@ export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] {
|
|||||||
export function mapEntryToMessage(
|
export function mapEntryToMessage(
|
||||||
entryRecord: Prisma.AgentSessionEntryGetPayload<Record<string, never>>,
|
entryRecord: Prisma.AgentSessionEntryGetPayload<Record<string, never>>,
|
||||||
): ChatMessage | null {
|
): ChatMessage | null {
|
||||||
const entryObj = entryRecord.entry as unknown as SessionTreeEntry
|
const payload = (entryRecord.data as Record<string, unknown>) || {}
|
||||||
|
const entryObj = {
|
||||||
|
id: entryRecord.id,
|
||||||
|
type: (entryRecord.type || 'message') as SessionTreeEntry['type'],
|
||||||
|
parentId: entryRecord.parentId,
|
||||||
|
timestamp: entryRecord.createdAt.toISOString(),
|
||||||
|
...payload,
|
||||||
|
} as unknown as SessionTreeEntry
|
||||||
|
|
||||||
if (
|
if (
|
||||||
entryObj.type === 'custom_message' &&
|
entryObj.type === 'custom_message' &&
|
||||||
(entryObj as { customType?: string }).customType === 'context'
|
(entryObj as { customType?: string }).customType === 'context'
|
||||||
) {
|
) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
const pathEntries = [{ ...entryObj, id: entryRecord.id }]
|
const pathEntries = [entryObj]
|
||||||
const messages = buildSessionMessages(pathEntries)
|
const messages = buildSessionMessages(pathEntries)
|
||||||
if (messages.length > 0) {
|
if (messages.length > 0) {
|
||||||
return messages[0]
|
return messages[0]
|
||||||
@@ -116,6 +125,7 @@ export function mapEntryToMessage(
|
|||||||
id: entryRecord.id,
|
id: entryRecord.id,
|
||||||
role: 'user',
|
role: 'user',
|
||||||
content: '',
|
content: '',
|
||||||
|
timestamp: entryRecord.createdAt.getTime(),
|
||||||
} as unknown as ChatMessage
|
} as unknown as ChatMessage
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -317,7 +327,6 @@ export class ChatService {
|
|||||||
imageUrls: resolvedImageUrls,
|
imageUrls: resolvedImageUrls,
|
||||||
attachedFiles,
|
attachedFiles,
|
||||||
assetIds,
|
assetIds,
|
||||||
explicitMention: true,
|
|
||||||
agentId,
|
agentId,
|
||||||
sessionId: activeSessionId,
|
sessionId: activeSessionId,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
@@ -383,18 +392,26 @@ export class ChatService {
|
|||||||
throw new Error('Unauthorized session access')
|
throw new Error('Unauthorized session access')
|
||||||
}
|
}
|
||||||
|
|
||||||
const entries = await this.prismaClient.agentSessionEntry.findMany({
|
const entries = await agentService.getSessionEntries({ sessionId })
|
||||||
where: { sessionId },
|
|
||||||
orderBy: { id: 'asc' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const pathEntries = entries.map((e) => {
|
const pathEntries = entries.map(
|
||||||
const entryObj = e.entry as unknown as SessionTreeEntry
|
(e: {
|
||||||
return {
|
id: string
|
||||||
...entryObj,
|
type: string | null
|
||||||
id: e.id,
|
parentId: string | null
|
||||||
}
|
createdAt: Date
|
||||||
})
|
data: unknown
|
||||||
|
}) => {
|
||||||
|
const payload = (e.data as Record<string, unknown>) || {}
|
||||||
|
return {
|
||||||
|
id: e.id,
|
||||||
|
type: (e.type || 'message') as SessionTreeEntry['type'],
|
||||||
|
parentId: e.parentId,
|
||||||
|
timestamp: e.createdAt.toISOString(),
|
||||||
|
...payload,
|
||||||
|
} as unknown as SessionTreeEntry
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
return buildSessionMessages(pathEntries)
|
return buildSessionMessages(pathEntries)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import * as fs from 'fs'
|
|||||||
import * as path from 'path'
|
import * as path from 'path'
|
||||||
import { ulid } from 'ulid'
|
import { ulid } from 'ulid'
|
||||||
import { LruTtlCache } from '../cache/lru-ttl-cache'
|
import { LruTtlCache } from '../cache/lru-ttl-cache'
|
||||||
|
import { detectSupportedMimeType } from '../utils/mime'
|
||||||
|
|
||||||
export function signLocalUrl(bucket: string, key: string): string {
|
export function signLocalUrl(bucket: string, key: string): string {
|
||||||
const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
|
const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
|
||||||
@@ -99,9 +100,22 @@ export class S3StorageService implements S3Service {
|
|||||||
async getObject(bucket: string, key: string): Promise<S3Object> {
|
async getObject(bucket: string, key: string): Promise<S3Object> {
|
||||||
const file = this.client.file(key, { bucket })
|
const file = this.client.file(key, { bucket })
|
||||||
const arrayBuffer = await file.arrayBuffer()
|
const arrayBuffer = await file.arrayBuffer()
|
||||||
|
const buffer = Buffer.from(arrayBuffer)
|
||||||
|
let contentType = file.type
|
||||||
|
if (!contentType || contentType === 'application/octet-stream') {
|
||||||
|
const detected = detectSupportedMimeType(buffer)
|
||||||
|
if (detected) {
|
||||||
|
contentType = detected
|
||||||
|
} else {
|
||||||
|
const fileType = Bun.file(key).type
|
||||||
|
if (fileType && fileType !== 'application/octet-stream') {
|
||||||
|
contentType = fileType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
buffer: Buffer.from(arrayBuffer),
|
buffer,
|
||||||
contentType: file.type || 'application/octet-stream',
|
contentType: contentType || 'application/octet-stream',
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -646,6 +646,97 @@ describe('TranscodeService', () => {
|
|||||||
expect(b).toBeLessThan(100)
|
expect(b).toBeLessThan(100)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('should snap commentTimestamp and overlay annotations when start/end has rounding mismatch', async () => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
;(child_process.execFile as any).mockImplementation(
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(file: string, args: string[], cb: any) => {
|
||||||
|
if (file === 'ffmpeg') {
|
||||||
|
const outPath = args[args.length - 1]
|
||||||
|
fs.writeFileSync(outPath, 'fake-webp-image')
|
||||||
|
}
|
||||||
|
cb(null, { stdout: '', stderr: '' })
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const overlaySpy = vi
|
||||||
|
.spyOn(transcodeService, 'overlayAnnotationsOnBuffer')
|
||||||
|
.mockResolvedValue(Buffer.from('composited-buffer'))
|
||||||
|
|
||||||
|
const annotations: PrismaJson.AnnotationList = [
|
||||||
|
{
|
||||||
|
type: 'box',
|
||||||
|
color: '#ff0000',
|
||||||
|
points: [
|
||||||
|
[0.2, 0.2],
|
||||||
|
[0.8, 0.8],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const results = await transcodeService.takeScreenshots({
|
||||||
|
assetKey: 'test/video.mp4',
|
||||||
|
assetId: 'asset-123',
|
||||||
|
start: 4.57,
|
||||||
|
end: 4.57,
|
||||||
|
count: 1,
|
||||||
|
commentTimestamp: 4.566666666666667,
|
||||||
|
annotations,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(results).toHaveLength(1)
|
||||||
|
expect(results[0].timestamp).toBe(4.566666666666667)
|
||||||
|
expect(overlaySpy).toHaveBeenCalledWith(expect.any(Buffer), annotations)
|
||||||
|
|
||||||
|
overlaySpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should overlay annotation on ONLY the single snapped frame in a multi-screenshot range', async () => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
;(child_process.execFile as any).mockImplementation(
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(file: string, args: string[], cb: any) => {
|
||||||
|
if (file === 'ffmpeg') {
|
||||||
|
const outPath = args[args.length - 1]
|
||||||
|
fs.writeFileSync(outPath, 'fake-webp-image')
|
||||||
|
}
|
||||||
|
cb(null, { stdout: '', stderr: '' })
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const overlaySpy = vi
|
||||||
|
.spyOn(transcodeService, 'overlayAnnotationsOnBuffer')
|
||||||
|
.mockResolvedValue(Buffer.from('composited-buffer'))
|
||||||
|
|
||||||
|
const annotations: PrismaJson.AnnotationList = [
|
||||||
|
{
|
||||||
|
type: 'box',
|
||||||
|
color: '#ff0000',
|
||||||
|
points: [
|
||||||
|
[0.2, 0.2],
|
||||||
|
[0.8, 0.8],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const results = await transcodeService.takeScreenshots({
|
||||||
|
assetKey: 'test/video.mp4',
|
||||||
|
assetId: 'asset-123',
|
||||||
|
start: 0,
|
||||||
|
end: 1,
|
||||||
|
count: 30,
|
||||||
|
commentTimestamp: 0.566666666666667,
|
||||||
|
annotations,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(results).toHaveLength(30)
|
||||||
|
// Exactly 1 overlay call for the snapped timestamp out of 30 frames
|
||||||
|
expect(overlaySpy).toHaveBeenCalledTimes(1)
|
||||||
|
expect(overlaySpy).toHaveBeenCalledWith(expect.any(Buffer), annotations)
|
||||||
|
|
||||||
|
overlaySpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
it('should generate PDF from text file including CJK characters', async () => {
|
it('should generate PDF from text file including CJK characters', async () => {
|
||||||
const txtFile = path.join(tempDir, 'test.txt')
|
const txtFile = path.join(tempDir, 'test.txt')
|
||||||
const pdfFile = path.join(tempDir, 'output.pdf')
|
const pdfFile = path.join(tempDir, 'output.pdf')
|
||||||
|
|||||||
@@ -923,10 +923,13 @@ export class TranscodeService {
|
|||||||
timestamps = Array.from({ length: params.count }, (_, i) => params.start + i * step)
|
timestamps = Array.from({ length: params.count }, (_, i) => params.start + i * step)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Snap closest timestamp to commentTimestamp if within range
|
// 3. Snap closest timestamp to commentTimestamp if within range (with 100ms tolerance)
|
||||||
const commentTimestamp = params.commentTimestamp
|
const commentTimestamp = params.commentTimestamp
|
||||||
|
const EPSILON = 0.1
|
||||||
if (commentTimestamp !== undefined && commentTimestamp !== null) {
|
if (commentTimestamp !== undefined && commentTimestamp !== null) {
|
||||||
if (commentTimestamp >= params.start && commentTimestamp <= params.end) {
|
const inRange =
|
||||||
|
commentTimestamp >= params.start - EPSILON && commentTimestamp <= params.end + EPSILON
|
||||||
|
if (inRange) {
|
||||||
let closestIdx = 0
|
let closestIdx = 0
|
||||||
let minDiff = Math.abs(timestamps[0] - commentTimestamp)
|
let minDiff = Math.abs(timestamps[0] - commentTimestamp)
|
||||||
for (let i = 1; i < timestamps.length; i++) {
|
for (let i = 1; i < timestamps.length; i++) {
|
||||||
@@ -964,14 +967,13 @@ export class TranscodeService {
|
|||||||
]
|
]
|
||||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||||
|
|
||||||
// 5. Overlay annotations if timestamp matches commentTimestamp exactly
|
const isMatch =
|
||||||
if (
|
|
||||||
commentTimestamp !== undefined &&
|
commentTimestamp !== undefined &&
|
||||||
commentTimestamp !== null &&
|
commentTimestamp !== null &&
|
||||||
t === commentTimestamp &&
|
Math.abs(t - commentTimestamp) < 1e-4
|
||||||
params.annotations &&
|
|
||||||
params.annotations.length > 0
|
// 5. Overlay annotations if timestamp matches commentTimestamp (within float tolerance)
|
||||||
) {
|
if (isMatch && params.annotations && params.annotations.length > 0) {
|
||||||
const shotBuffer = fs.readFileSync(localShotPath)
|
const shotBuffer = fs.readFileSync(localShotPath)
|
||||||
const composited = await this.overlayAnnotationsOnBuffer(shotBuffer, params.annotations)
|
const composited = await this.overlayAnnotationsOnBuffer(shotBuffer, params.annotations)
|
||||||
fs.writeFileSync(localShotPath, composited)
|
fs.writeFileSync(localShotPath, composited)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/db",
|
"name": "@shumai/db",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
|
|||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "agent_session_entries" ADD COLUMN "asset_id" TEXT,
|
||||||
|
ADD COLUMN "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
ADD COLUMN "data" JSONB,
|
||||||
|
ADD COLUMN "parent_id" TEXT,
|
||||||
|
ADD COLUMN "type" TEXT,
|
||||||
|
ALTER COLUMN "session_id" DROP NOT NULL,
|
||||||
|
ALTER COLUMN "entry" DROP NOT NULL;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "agent_session_entries_parent_id_idx" ON "agent_session_entries"("parent_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "agent_session_entries_asset_id_idx" ON "agent_session_entries"("asset_id");
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
-- Migrate existing entry JSON data to new columns
|
||||||
|
UPDATE agent_session_entries
|
||||||
|
SET
|
||||||
|
type = entry->>'type',
|
||||||
|
parent_id = entry->>'parentId',
|
||||||
|
asset_id = (SELECT s.asset_id FROM agent_sessions s WHERE s.id = agent_session_entries.session_id),
|
||||||
|
created_at = CASE
|
||||||
|
WHEN entry->>'timestamp' IS NOT NULL THEN (entry->>'timestamp')::timestamptz
|
||||||
|
ELSE created_at
|
||||||
|
END,
|
||||||
|
data = (entry::jsonb - 'id' - 'type' - 'parentId' - 'timestamp')::text::json
|
||||||
|
WHERE entry IS NOT NULL;
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
/*
|
||||||
|
Warnings:
|
||||||
|
|
||||||
|
- You are about to drop the column `entry` on the `agent_session_entries` table. All the data in the column will be lost.
|
||||||
|
|
||||||
|
*/
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "agent_session_entries" DROP COLUMN "entry";
|
||||||
@@ -722,14 +722,20 @@ model AgentSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model AgentSessionEntry {
|
model AgentSessionEntry {
|
||||||
id String @id // Uses ULID generated by pi-coding-agent
|
id String @id // Uses ULID generated by pi-coding-agent
|
||||||
sessionId String @map("session_id")
|
sessionId String? @map("session_id")
|
||||||
session AgentSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
session AgentSession? @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
/// [PiSessionEntry]
|
assetId String? @map("asset_id")
|
||||||
entry Json
|
type String?
|
||||||
|
parentId String? @map("parent_id")
|
||||||
|
/// [PiSessionEntryData]
|
||||||
|
data Json?
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
@@map("agent_session_entries")
|
|
||||||
@@index([sessionId])
|
@@index([sessionId])
|
||||||
|
@@index([parentId])
|
||||||
|
@@index([assetId])
|
||||||
|
@@map("agent_session_entries")
|
||||||
}
|
}
|
||||||
|
|
||||||
model UserMetadata {
|
model UserMetadata {
|
||||||
|
|||||||
+4
-4
File diff suppressed because one or more lines are too long
@@ -3397,7 +3397,11 @@ export type AgentSessionScalarFieldEnum = (typeof AgentSessionScalarFieldEnum)[k
|
|||||||
export const AgentSessionEntryScalarFieldEnum = {
|
export const AgentSessionEntryScalarFieldEnum = {
|
||||||
id: 'id',
|
id: 'id',
|
||||||
sessionId: 'sessionId',
|
sessionId: 'sessionId',
|
||||||
entry: 'entry'
|
assetId: 'assetId',
|
||||||
|
type: 'type',
|
||||||
|
parentId: 'parentId',
|
||||||
|
data: 'data',
|
||||||
|
createdAt: 'createdAt'
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
export type AgentSessionEntryScalarFieldEnum = (typeof AgentSessionEntryScalarFieldEnum)[keyof typeof AgentSessionEntryScalarFieldEnum]
|
export type AgentSessionEntryScalarFieldEnum = (typeof AgentSessionEntryScalarFieldEnum)[keyof typeof AgentSessionEntryScalarFieldEnum]
|
||||||
|
|||||||
@@ -508,7 +508,11 @@ export type AgentSessionScalarFieldEnum = (typeof AgentSessionScalarFieldEnum)[k
|
|||||||
export const AgentSessionEntryScalarFieldEnum = {
|
export const AgentSessionEntryScalarFieldEnum = {
|
||||||
id: 'id',
|
id: 'id',
|
||||||
sessionId: 'sessionId',
|
sessionId: 'sessionId',
|
||||||
entry: 'entry'
|
assetId: 'assetId',
|
||||||
|
type: 'type',
|
||||||
|
parentId: 'parentId',
|
||||||
|
data: 'data',
|
||||||
|
createdAt: 'createdAt'
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
export type AgentSessionEntryScalarFieldEnum = (typeof AgentSessionEntryScalarFieldEnum)[keyof typeof AgentSessionEntryScalarFieldEnum]
|
export type AgentSessionEntryScalarFieldEnum = (typeof AgentSessionEntryScalarFieldEnum)[keyof typeof AgentSessionEntryScalarFieldEnum]
|
||||||
|
|||||||
+3
-6
@@ -474,11 +474,6 @@ export type AgentSessionMinOrderByAggregateInput = {
|
|||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionScalarRelationFilter = {
|
|
||||||
is?: Prisma.AgentSessionWhereInput
|
|
||||||
isNot?: Prisma.AgentSessionWhereInput
|
|
||||||
}
|
|
||||||
|
|
||||||
export type AgentSessionCreateNestedManyWithoutUserInput = {
|
export type AgentSessionCreateNestedManyWithoutUserInput = {
|
||||||
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutUserInput, Prisma.AgentSessionUncheckedCreateWithoutUserInput> | Prisma.AgentSessionCreateWithoutUserInput[] | Prisma.AgentSessionUncheckedCreateWithoutUserInput[]
|
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutUserInput, Prisma.AgentSessionUncheckedCreateWithoutUserInput> | Prisma.AgentSessionCreateWithoutUserInput[] | Prisma.AgentSessionUncheckedCreateWithoutUserInput[]
|
||||||
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutUserInput | Prisma.AgentSessionCreateOrConnectWithoutUserInput[]
|
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutUserInput | Prisma.AgentSessionCreateOrConnectWithoutUserInput[]
|
||||||
@@ -631,10 +626,12 @@ export type AgentSessionCreateNestedOneWithoutEntriesInput = {
|
|||||||
connect?: Prisma.AgentSessionWhereUniqueInput
|
connect?: Prisma.AgentSessionWhereUniqueInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionUpdateOneRequiredWithoutEntriesNestedInput = {
|
export type AgentSessionUpdateOneWithoutEntriesNestedInput = {
|
||||||
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutEntriesInput, Prisma.AgentSessionUncheckedCreateWithoutEntriesInput>
|
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutEntriesInput, Prisma.AgentSessionUncheckedCreateWithoutEntriesInput>
|
||||||
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutEntriesInput
|
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutEntriesInput
|
||||||
upsert?: Prisma.AgentSessionUpsertWithoutEntriesInput
|
upsert?: Prisma.AgentSessionUpsertWithoutEntriesInput
|
||||||
|
disconnect?: Prisma.AgentSessionWhereInput | boolean
|
||||||
|
delete?: Prisma.AgentSessionWhereInput | boolean
|
||||||
connect?: Prisma.AgentSessionWhereUniqueInput
|
connect?: Prisma.AgentSessionWhereUniqueInput
|
||||||
update?: Prisma.XOR<Prisma.XOR<Prisma.AgentSessionUpdateToOneWithWhereWithoutEntriesInput, Prisma.AgentSessionUpdateWithoutEntriesInput>, Prisma.AgentSessionUncheckedUpdateWithoutEntriesInput>
|
update?: Prisma.XOR<Prisma.XOR<Prisma.AgentSessionUpdateToOneWithWhereWithoutEntriesInput, Prisma.AgentSessionUpdateWithoutEntriesInput>, Prisma.AgentSessionUncheckedUpdateWithoutEntriesInput>
|
||||||
}
|
}
|
||||||
|
|||||||
+214
-55
@@ -29,17 +29,29 @@ export type AggregateAgentSessionEntry = {
|
|||||||
export type AgentSessionEntryMinAggregateOutputType = {
|
export type AgentSessionEntryMinAggregateOutputType = {
|
||||||
id: string | null
|
id: string | null
|
||||||
sessionId: string | null
|
sessionId: string | null
|
||||||
|
assetId: string | null
|
||||||
|
type: string | null
|
||||||
|
parentId: string | null
|
||||||
|
createdAt: Date | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryMaxAggregateOutputType = {
|
export type AgentSessionEntryMaxAggregateOutputType = {
|
||||||
id: string | null
|
id: string | null
|
||||||
sessionId: string | null
|
sessionId: string | null
|
||||||
|
assetId: string | null
|
||||||
|
type: string | null
|
||||||
|
parentId: string | null
|
||||||
|
createdAt: Date | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryCountAggregateOutputType = {
|
export type AgentSessionEntryCountAggregateOutputType = {
|
||||||
id: number
|
id: number
|
||||||
sessionId: number
|
sessionId: number
|
||||||
entry:PrismaJson.PiSessionEntry
|
assetId: number
|
||||||
|
type: number
|
||||||
|
parentId: number
|
||||||
|
data:PrismaJson.PiSessionEntryData
|
||||||
|
createdAt: number
|
||||||
_all: number
|
_all: number
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,17 +59,29 @@ export type AgentSessionEntryCountAggregateOutputType = {
|
|||||||
export type AgentSessionEntryMinAggregateInputType = {
|
export type AgentSessionEntryMinAggregateInputType = {
|
||||||
id?: true
|
id?: true
|
||||||
sessionId?: true
|
sessionId?: true
|
||||||
|
assetId?: true
|
||||||
|
type?: true
|
||||||
|
parentId?: true
|
||||||
|
createdAt?: true
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryMaxAggregateInputType = {
|
export type AgentSessionEntryMaxAggregateInputType = {
|
||||||
id?: true
|
id?: true
|
||||||
sessionId?: true
|
sessionId?: true
|
||||||
|
assetId?: true
|
||||||
|
type?: true
|
||||||
|
parentId?: true
|
||||||
|
createdAt?: true
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryCountAggregateInputType = {
|
export type AgentSessionEntryCountAggregateInputType = {
|
||||||
id?: true
|
id?: true
|
||||||
sessionId?: true
|
sessionId?: true
|
||||||
entry?: true
|
assetId?: true
|
||||||
|
type?: true
|
||||||
|
parentId?: true
|
||||||
|
data?: true
|
||||||
|
createdAt?: true
|
||||||
_all?: true
|
_all?: true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,8 +159,12 @@ export type AgentSessionEntryGroupByArgs<ExtArgs extends runtime.Types.Extension
|
|||||||
|
|
||||||
export type AgentSessionEntryGroupByOutputType = {
|
export type AgentSessionEntryGroupByOutputType = {
|
||||||
id: string
|
id: string
|
||||||
sessionId: string
|
sessionId: string | null
|
||||||
entry:PrismaJson.PiSessionEntry
|
assetId: string | null
|
||||||
|
type: string | null
|
||||||
|
parentId: string | null
|
||||||
|
data:PrismaJson.PiSessionEntryData | null
|
||||||
|
createdAt: Date
|
||||||
_count: AgentSessionEntryCountAggregateOutputType | null
|
_count: AgentSessionEntryCountAggregateOutputType | null
|
||||||
_min: AgentSessionEntryMinAggregateOutputType | null
|
_min: AgentSessionEntryMinAggregateOutputType | null
|
||||||
_max: AgentSessionEntryMaxAggregateOutputType | null
|
_max: AgentSessionEntryMaxAggregateOutputType | null
|
||||||
@@ -162,15 +190,23 @@ export type AgentSessionEntryWhereInput = {
|
|||||||
OR?: Prisma.AgentSessionEntryWhereInput[]
|
OR?: Prisma.AgentSessionEntryWhereInput[]
|
||||||
NOT?: Prisma.AgentSessionEntryWhereInput | Prisma.AgentSessionEntryWhereInput[]
|
NOT?: Prisma.AgentSessionEntryWhereInput | Prisma.AgentSessionEntryWhereInput[]
|
||||||
id?: Prisma.StringFilter<"AgentSessionEntry"> | string
|
id?: Prisma.StringFilter<"AgentSessionEntry"> | string
|
||||||
sessionId?: Prisma.StringFilter<"AgentSessionEntry"> | string
|
sessionId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
entry?: Prisma.JsonFilter<"AgentSessionEntry">
|
assetId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
session?: Prisma.XOR<Prisma.AgentSessionScalarRelationFilter, Prisma.AgentSessionWhereInput>
|
type?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
|
parentId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
|
data?: Prisma.JsonNullableFilter<"AgentSessionEntry">
|
||||||
|
createdAt?: Prisma.DateTimeFilter<"AgentSessionEntry"> | Date | string
|
||||||
|
session?: Prisma.XOR<Prisma.AgentSessionNullableScalarRelationFilter, Prisma.AgentSessionWhereInput> | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryOrderByWithRelationInput = {
|
export type AgentSessionEntryOrderByWithRelationInput = {
|
||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
sessionId?: Prisma.SortOrder
|
sessionId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
entry?: Prisma.SortOrder
|
assetId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
type?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
parentId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
data?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
createdAt?: Prisma.SortOrder
|
||||||
session?: Prisma.AgentSessionOrderByWithRelationInput
|
session?: Prisma.AgentSessionOrderByWithRelationInput
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,15 +215,23 @@ export type AgentSessionEntryWhereUniqueInput = Prisma.AtLeast<{
|
|||||||
AND?: Prisma.AgentSessionEntryWhereInput | Prisma.AgentSessionEntryWhereInput[]
|
AND?: Prisma.AgentSessionEntryWhereInput | Prisma.AgentSessionEntryWhereInput[]
|
||||||
OR?: Prisma.AgentSessionEntryWhereInput[]
|
OR?: Prisma.AgentSessionEntryWhereInput[]
|
||||||
NOT?: Prisma.AgentSessionEntryWhereInput | Prisma.AgentSessionEntryWhereInput[]
|
NOT?: Prisma.AgentSessionEntryWhereInput | Prisma.AgentSessionEntryWhereInput[]
|
||||||
sessionId?: Prisma.StringFilter<"AgentSessionEntry"> | string
|
sessionId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
entry?: Prisma.JsonFilter<"AgentSessionEntry">
|
assetId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
session?: Prisma.XOR<Prisma.AgentSessionScalarRelationFilter, Prisma.AgentSessionWhereInput>
|
type?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
|
parentId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
|
data?: Prisma.JsonNullableFilter<"AgentSessionEntry">
|
||||||
|
createdAt?: Prisma.DateTimeFilter<"AgentSessionEntry"> | Date | string
|
||||||
|
session?: Prisma.XOR<Prisma.AgentSessionNullableScalarRelationFilter, Prisma.AgentSessionWhereInput> | null
|
||||||
}, "id">
|
}, "id">
|
||||||
|
|
||||||
export type AgentSessionEntryOrderByWithAggregationInput = {
|
export type AgentSessionEntryOrderByWithAggregationInput = {
|
||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
sessionId?: Prisma.SortOrder
|
sessionId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
entry?: Prisma.SortOrder
|
assetId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
type?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
parentId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
data?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
createdAt?: Prisma.SortOrder
|
||||||
_count?: Prisma.AgentSessionEntryCountOrderByAggregateInput
|
_count?: Prisma.AgentSessionEntryCountOrderByAggregateInput
|
||||||
_max?: Prisma.AgentSessionEntryMaxOrderByAggregateInput
|
_max?: Prisma.AgentSessionEntryMaxOrderByAggregateInput
|
||||||
_min?: Prisma.AgentSessionEntryMinOrderByAggregateInput
|
_min?: Prisma.AgentSessionEntryMinOrderByAggregateInput
|
||||||
@@ -198,49 +242,81 @@ export type AgentSessionEntryScalarWhereWithAggregatesInput = {
|
|||||||
OR?: Prisma.AgentSessionEntryScalarWhereWithAggregatesInput[]
|
OR?: Prisma.AgentSessionEntryScalarWhereWithAggregatesInput[]
|
||||||
NOT?: Prisma.AgentSessionEntryScalarWhereWithAggregatesInput | Prisma.AgentSessionEntryScalarWhereWithAggregatesInput[]
|
NOT?: Prisma.AgentSessionEntryScalarWhereWithAggregatesInput | Prisma.AgentSessionEntryScalarWhereWithAggregatesInput[]
|
||||||
id?: Prisma.StringWithAggregatesFilter<"AgentSessionEntry"> | string
|
id?: Prisma.StringWithAggregatesFilter<"AgentSessionEntry"> | string
|
||||||
sessionId?: Prisma.StringWithAggregatesFilter<"AgentSessionEntry"> | string
|
sessionId?: Prisma.StringNullableWithAggregatesFilter<"AgentSessionEntry"> | string | null
|
||||||
entry?: Prisma.JsonWithAggregatesFilter<"AgentSessionEntry">
|
assetId?: Prisma.StringNullableWithAggregatesFilter<"AgentSessionEntry"> | string | null
|
||||||
|
type?: Prisma.StringNullableWithAggregatesFilter<"AgentSessionEntry"> | string | null
|
||||||
|
parentId?: Prisma.StringNullableWithAggregatesFilter<"AgentSessionEntry"> | string | null
|
||||||
|
data?: Prisma.JsonNullableWithAggregatesFilter<"AgentSessionEntry">
|
||||||
|
createdAt?: Prisma.DateTimeWithAggregatesFilter<"AgentSessionEntry"> | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryCreateInput = {
|
export type AgentSessionEntryCreateInput = {
|
||||||
id: string
|
id: string
|
||||||
entry:PrismaJson.PiSessionEntry
|
assetId?: string | null
|
||||||
session: Prisma.AgentSessionCreateNestedOneWithoutEntriesInput
|
type?: string | null
|
||||||
|
parentId?: string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Date | string
|
||||||
|
session?: Prisma.AgentSessionCreateNestedOneWithoutEntriesInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUncheckedCreateInput = {
|
export type AgentSessionEntryUncheckedCreateInput = {
|
||||||
id: string
|
id: string
|
||||||
sessionId: string
|
sessionId?: string | null
|
||||||
entry:PrismaJson.PiSessionEntry
|
assetId?: string | null
|
||||||
|
type?: string | null
|
||||||
|
parentId?: string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUpdateInput = {
|
export type AgentSessionEntryUpdateInput = {
|
||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
entry?:PrismaJson.PiSessionEntry
|
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
session?: Prisma.AgentSessionUpdateOneRequiredWithoutEntriesNestedInput
|
type?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
parentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
session?: Prisma.AgentSessionUpdateOneWithoutEntriesNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUncheckedUpdateInput = {
|
export type AgentSessionEntryUncheckedUpdateInput = {
|
||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
sessionId?: Prisma.StringFieldUpdateOperationsInput | string
|
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
entry?:PrismaJson.PiSessionEntry
|
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
type?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
parentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryCreateManyInput = {
|
export type AgentSessionEntryCreateManyInput = {
|
||||||
id: string
|
id: string
|
||||||
sessionId: string
|
sessionId?: string | null
|
||||||
entry:PrismaJson.PiSessionEntry
|
assetId?: string | null
|
||||||
|
type?: string | null
|
||||||
|
parentId?: string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUpdateManyMutationInput = {
|
export type AgentSessionEntryUpdateManyMutationInput = {
|
||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
entry?:PrismaJson.PiSessionEntry
|
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
type?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
parentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUncheckedUpdateManyInput = {
|
export type AgentSessionEntryUncheckedUpdateManyInput = {
|
||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
sessionId?: Prisma.StringFieldUpdateOperationsInput | string
|
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
entry?:PrismaJson.PiSessionEntry
|
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
type?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
parentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryListRelationFilter = {
|
export type AgentSessionEntryListRelationFilter = {
|
||||||
@@ -256,17 +332,29 @@ export type AgentSessionEntryOrderByRelationAggregateInput = {
|
|||||||
export type AgentSessionEntryCountOrderByAggregateInput = {
|
export type AgentSessionEntryCountOrderByAggregateInput = {
|
||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
sessionId?: Prisma.SortOrder
|
sessionId?: Prisma.SortOrder
|
||||||
entry?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
|
type?: Prisma.SortOrder
|
||||||
|
parentId?: Prisma.SortOrder
|
||||||
|
data?: Prisma.SortOrder
|
||||||
|
createdAt?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryMaxOrderByAggregateInput = {
|
export type AgentSessionEntryMaxOrderByAggregateInput = {
|
||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
sessionId?: Prisma.SortOrder
|
sessionId?: Prisma.SortOrder
|
||||||
|
assetId?: Prisma.SortOrder
|
||||||
|
type?: Prisma.SortOrder
|
||||||
|
parentId?: Prisma.SortOrder
|
||||||
|
createdAt?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryMinOrderByAggregateInput = {
|
export type AgentSessionEntryMinOrderByAggregateInput = {
|
||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
sessionId?: Prisma.SortOrder
|
sessionId?: Prisma.SortOrder
|
||||||
|
assetId?: Prisma.SortOrder
|
||||||
|
type?: Prisma.SortOrder
|
||||||
|
parentId?: Prisma.SortOrder
|
||||||
|
createdAt?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryCreateNestedManyWithoutSessionInput = {
|
export type AgentSessionEntryCreateNestedManyWithoutSessionInput = {
|
||||||
@@ -313,12 +401,20 @@ export type AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput = {
|
|||||||
|
|
||||||
export type AgentSessionEntryCreateWithoutSessionInput = {
|
export type AgentSessionEntryCreateWithoutSessionInput = {
|
||||||
id: string
|
id: string
|
||||||
entry:PrismaJson.PiSessionEntry
|
assetId?: string | null
|
||||||
|
type?: string | null
|
||||||
|
parentId?: string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUncheckedCreateWithoutSessionInput = {
|
export type AgentSessionEntryUncheckedCreateWithoutSessionInput = {
|
||||||
id: string
|
id: string
|
||||||
entry:PrismaJson.PiSessionEntry
|
assetId?: string | null
|
||||||
|
type?: string | null
|
||||||
|
parentId?: string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryCreateOrConnectWithoutSessionInput = {
|
export type AgentSessionEntryCreateOrConnectWithoutSessionInput = {
|
||||||
@@ -352,28 +448,48 @@ export type AgentSessionEntryScalarWhereInput = {
|
|||||||
OR?: Prisma.AgentSessionEntryScalarWhereInput[]
|
OR?: Prisma.AgentSessionEntryScalarWhereInput[]
|
||||||
NOT?: Prisma.AgentSessionEntryScalarWhereInput | Prisma.AgentSessionEntryScalarWhereInput[]
|
NOT?: Prisma.AgentSessionEntryScalarWhereInput | Prisma.AgentSessionEntryScalarWhereInput[]
|
||||||
id?: Prisma.StringFilter<"AgentSessionEntry"> | string
|
id?: Prisma.StringFilter<"AgentSessionEntry"> | string
|
||||||
sessionId?: Prisma.StringFilter<"AgentSessionEntry"> | string
|
sessionId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
entry?: Prisma.JsonFilter<"AgentSessionEntry">
|
assetId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
|
type?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
|
parentId?: Prisma.StringNullableFilter<"AgentSessionEntry"> | string | null
|
||||||
|
data?: Prisma.JsonNullableFilter<"AgentSessionEntry">
|
||||||
|
createdAt?: Prisma.DateTimeFilter<"AgentSessionEntry"> | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryCreateManySessionInput = {
|
export type AgentSessionEntryCreateManySessionInput = {
|
||||||
id: string
|
id: string
|
||||||
entry:PrismaJson.PiSessionEntry
|
assetId?: string | null
|
||||||
|
type?: string | null
|
||||||
|
parentId?: string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUpdateWithoutSessionInput = {
|
export type AgentSessionEntryUpdateWithoutSessionInput = {
|
||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
entry?:PrismaJson.PiSessionEntry
|
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
type?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
parentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUncheckedUpdateWithoutSessionInput = {
|
export type AgentSessionEntryUncheckedUpdateWithoutSessionInput = {
|
||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
entry?:PrismaJson.PiSessionEntry
|
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
type?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
parentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryUncheckedUpdateManyWithoutSessionInput = {
|
export type AgentSessionEntryUncheckedUpdateManyWithoutSessionInput = {
|
||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
entry?:PrismaJson.PiSessionEntry
|
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
type?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
parentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
data?:PrismaJson.PiSessionEntryData | Prisma.NullableJsonNullValueInput
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -381,53 +497,73 @@ export type AgentSessionEntryUncheckedUpdateManyWithoutSessionInput = {
|
|||||||
export type AgentSessionEntrySelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
export type AgentSessionEntrySelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
||||||
id?: boolean
|
id?: boolean
|
||||||
sessionId?: boolean
|
sessionId?: boolean
|
||||||
entry?: boolean
|
assetId?: boolean
|
||||||
session?: boolean | Prisma.AgentSessionDefaultArgs<ExtArgs>
|
type?: boolean
|
||||||
|
parentId?: boolean
|
||||||
|
data?: boolean
|
||||||
|
createdAt?: boolean
|
||||||
|
session?: boolean | Prisma.AgentSessionEntry$sessionArgs<ExtArgs>
|
||||||
}, ExtArgs["result"]["agentSessionEntry"]>
|
}, ExtArgs["result"]["agentSessionEntry"]>
|
||||||
|
|
||||||
export type AgentSessionEntrySelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
export type AgentSessionEntrySelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
||||||
id?: boolean
|
id?: boolean
|
||||||
sessionId?: boolean
|
sessionId?: boolean
|
||||||
entry?: boolean
|
assetId?: boolean
|
||||||
session?: boolean | Prisma.AgentSessionDefaultArgs<ExtArgs>
|
type?: boolean
|
||||||
|
parentId?: boolean
|
||||||
|
data?: boolean
|
||||||
|
createdAt?: boolean
|
||||||
|
session?: boolean | Prisma.AgentSessionEntry$sessionArgs<ExtArgs>
|
||||||
}, ExtArgs["result"]["agentSessionEntry"]>
|
}, ExtArgs["result"]["agentSessionEntry"]>
|
||||||
|
|
||||||
export type AgentSessionEntrySelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
export type AgentSessionEntrySelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
||||||
id?: boolean
|
id?: boolean
|
||||||
sessionId?: boolean
|
sessionId?: boolean
|
||||||
entry?: boolean
|
assetId?: boolean
|
||||||
session?: boolean | Prisma.AgentSessionDefaultArgs<ExtArgs>
|
type?: boolean
|
||||||
|
parentId?: boolean
|
||||||
|
data?: boolean
|
||||||
|
createdAt?: boolean
|
||||||
|
session?: boolean | Prisma.AgentSessionEntry$sessionArgs<ExtArgs>
|
||||||
}, ExtArgs["result"]["agentSessionEntry"]>
|
}, ExtArgs["result"]["agentSessionEntry"]>
|
||||||
|
|
||||||
export type AgentSessionEntrySelectScalar = {
|
export type AgentSessionEntrySelectScalar = {
|
||||||
id?: boolean
|
id?: boolean
|
||||||
sessionId?: boolean
|
sessionId?: boolean
|
||||||
entry?: boolean
|
assetId?: boolean
|
||||||
|
type?: boolean
|
||||||
|
parentId?: boolean
|
||||||
|
data?: boolean
|
||||||
|
createdAt?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentSessionEntryOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "sessionId" | "entry", ExtArgs["result"]["agentSessionEntry"]>
|
export type AgentSessionEntryOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "sessionId" | "assetId" | "type" | "parentId" | "data" | "createdAt", ExtArgs["result"]["agentSessionEntry"]>
|
||||||
export type AgentSessionEntryInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type AgentSessionEntryInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
session?: boolean | Prisma.AgentSessionDefaultArgs<ExtArgs>
|
session?: boolean | Prisma.AgentSessionEntry$sessionArgs<ExtArgs>
|
||||||
}
|
}
|
||||||
export type AgentSessionEntryIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type AgentSessionEntryIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
session?: boolean | Prisma.AgentSessionDefaultArgs<ExtArgs>
|
session?: boolean | Prisma.AgentSessionEntry$sessionArgs<ExtArgs>
|
||||||
}
|
}
|
||||||
export type AgentSessionEntryIncludeUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type AgentSessionEntryIncludeUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
session?: boolean | Prisma.AgentSessionDefaultArgs<ExtArgs>
|
session?: boolean | Prisma.AgentSessionEntry$sessionArgs<ExtArgs>
|
||||||
}
|
}
|
||||||
|
|
||||||
export type $AgentSessionEntryPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type $AgentSessionEntryPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
name: "AgentSessionEntry"
|
name: "AgentSessionEntry"
|
||||||
objects: {
|
objects: {
|
||||||
session: Prisma.$AgentSessionPayload<ExtArgs>
|
session: Prisma.$AgentSessionPayload<ExtArgs> | null
|
||||||
}
|
}
|
||||||
scalars: runtime.Types.Extensions.GetPayloadResult<{
|
scalars: runtime.Types.Extensions.GetPayloadResult<{
|
||||||
id: string
|
id: string
|
||||||
sessionId: string
|
sessionId: string | null
|
||||||
|
assetId: string | null
|
||||||
|
type: string | null
|
||||||
|
parentId: string | null
|
||||||
/**
|
/**
|
||||||
* [PiSessionEntry]
|
* [PiSessionEntryData]
|
||||||
*/
|
*/
|
||||||
entry:PrismaJson.PiSessionEntry
|
data:PrismaJson.PiSessionEntryData | null
|
||||||
|
createdAt: Date
|
||||||
}, ExtArgs["result"]["agentSessionEntry"]>
|
}, ExtArgs["result"]["agentSessionEntry"]>
|
||||||
composites: {}
|
composites: {}
|
||||||
}
|
}
|
||||||
@@ -822,7 +958,7 @@ readonly fields: AgentSessionEntryFieldRefs;
|
|||||||
*/
|
*/
|
||||||
export interface Prisma__AgentSessionEntryClient<T, Null = never, ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}> extends Prisma.PrismaPromise<T> {
|
export interface Prisma__AgentSessionEntryClient<T, Null = never, ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}> extends Prisma.PrismaPromise<T> {
|
||||||
readonly [Symbol.toStringTag]: "PrismaPromise"
|
readonly [Symbol.toStringTag]: "PrismaPromise"
|
||||||
session<T extends Prisma.AgentSessionDefaultArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AgentSessionDefaultArgs<ExtArgs>>): Prisma.Prisma__AgentSessionClient<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | Null, Null, ExtArgs, GlobalOmitOptions>
|
session<T extends Prisma.AgentSessionEntry$sessionArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.AgentSessionEntry$sessionArgs<ExtArgs>>): Prisma.Prisma__AgentSessionClient<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||||
/**
|
/**
|
||||||
* Attaches callbacks for the resolution and/or rejection of the Promise.
|
* Attaches callbacks for the resolution and/or rejection of the Promise.
|
||||||
* @param onfulfilled The callback to execute when the Promise is resolved.
|
* @param onfulfilled The callback to execute when the Promise is resolved.
|
||||||
@@ -854,7 +990,11 @@ export interface Prisma__AgentSessionEntryClient<T, Null = never, ExtArgs extend
|
|||||||
export interface AgentSessionEntryFieldRefs {
|
export interface AgentSessionEntryFieldRefs {
|
||||||
readonly id: Prisma.FieldRef<"AgentSessionEntry", 'String'>
|
readonly id: Prisma.FieldRef<"AgentSessionEntry", 'String'>
|
||||||
readonly sessionId: Prisma.FieldRef<"AgentSessionEntry", 'String'>
|
readonly sessionId: Prisma.FieldRef<"AgentSessionEntry", 'String'>
|
||||||
readonly entry: Prisma.FieldRef<"AgentSessionEntry", 'Json'>
|
readonly assetId: Prisma.FieldRef<"AgentSessionEntry", 'String'>
|
||||||
|
readonly type: Prisma.FieldRef<"AgentSessionEntry", 'String'>
|
||||||
|
readonly parentId: Prisma.FieldRef<"AgentSessionEntry", 'String'>
|
||||||
|
readonly data: Prisma.FieldRef<"AgentSessionEntry", 'Json'>
|
||||||
|
readonly createdAt: Prisma.FieldRef<"AgentSessionEntry", 'DateTime'>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -1255,6 +1395,25 @@ export type AgentSessionEntryDeleteManyArgs<ExtArgs extends runtime.Types.Extens
|
|||||||
limit?: number
|
limit?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AgentSessionEntry.session
|
||||||
|
*/
|
||||||
|
export type AgentSessionEntry$sessionArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
|
/**
|
||||||
|
* Select specific fields to fetch from the AgentSession
|
||||||
|
*/
|
||||||
|
select?: Prisma.AgentSessionSelect<ExtArgs> | null
|
||||||
|
/**
|
||||||
|
* Omit specific fields from the AgentSession
|
||||||
|
*/
|
||||||
|
omit?: Prisma.AgentSessionOmit<ExtArgs> | null
|
||||||
|
/**
|
||||||
|
* Choose, which related nodes to fetch as well
|
||||||
|
*/
|
||||||
|
include?: Prisma.AgentSessionInclude<ExtArgs> | null
|
||||||
|
where?: Prisma.AgentSessionWhereInput
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* AgentSessionEntry without action
|
* AgentSessionEntry without action
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
export {}
|
export {}
|
||||||
|
|
||||||
import { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||||
namespace PrismaJson {
|
namespace PrismaJson {
|
||||||
// ----------------------------------------------------------------------
|
export type PiSessionEntryData = Omit<
|
||||||
// Agent Session Entry
|
import('@earendil-works/pi-agent-core').SessionTreeEntry,
|
||||||
// ----------------------------------------------------------------------
|
'id' | 'type' | 'parentId' | 'timestamp'
|
||||||
export type PiSessionEntry = SessionTreeEntry
|
>
|
||||||
|
|
||||||
// ----------------------------------------------------------------------
|
// ----------------------------------------------------------------------
|
||||||
// User Agent Settings
|
// User Agent Settings
|
||||||
@@ -302,7 +300,6 @@ declare global {
|
|||||||
userId?: string
|
userId?: string
|
||||||
sessionId?: string
|
sessionId?: string
|
||||||
userCommentId?: string
|
userCommentId?: string
|
||||||
explicitMention?: boolean
|
|
||||||
prompt?: string
|
prompt?: string
|
||||||
imageUrls?: string[]
|
imageUrls?: string[]
|
||||||
attachedFiles?: string[]
|
attachedFiles?: string[]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/dtos",
|
"name": "@shumai/dtos",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/e2e",
|
"name": "@shumai/e2e",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shumai/db": "workspace:*",
|
|
||||||
"@shumai/core": "workspace:*",
|
|
||||||
"@shumai/workflow-core": "workspace:*",
|
|
||||||
"@shumai/agent": "workspace:*",
|
|
||||||
"@shumai/transcode": "workspace:*",
|
|
||||||
"@shumai/dtos": "workspace:*",
|
|
||||||
"@earendil-works/pi-agent-core": "0.78.0",
|
"@earendil-works/pi-agent-core": "0.78.0",
|
||||||
"@google/genai": "1.52.0"
|
"@google/genai": "1.52.0",
|
||||||
|
"@shumai/agent": "workspace:*",
|
||||||
|
"@shumai/core": "workspace:*",
|
||||||
|
"@shumai/db": "workspace:*",
|
||||||
|
"@shumai/dtos": "workspace:*",
|
||||||
|
"@shumai/transcode": "workspace:*",
|
||||||
|
"@shumai/workflow-core": "workspace:*",
|
||||||
|
"sharp": "0.34.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||||
|
import { prisma } from '@shumai/db'
|
||||||
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
|
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||||
|
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import * as path from 'path'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
|
||||||
|
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
||||||
|
const fixturesDir = path.resolve(currentDir, '../fixtures')
|
||||||
|
|
||||||
|
describe.each(['local', 'temporal'] as const)(
|
||||||
|
'Workflow E2E - overlayImageAnnotationWorkflow (executor: %s)',
|
||||||
|
(mode) => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
let transcodeWorkerPromise: Promise<void> | null = null
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-transcode'
|
||||||
|
|
||||||
|
workflowService.setExecutorType(mode)
|
||||||
|
initTranscodeWorkflows()
|
||||||
|
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Starting background worker for transcode Temporal E2E tests...')
|
||||||
|
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
|
||||||
|
workflowsPath: transcodeWorkflowsPath,
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||||
|
} else {
|
||||||
|
console.log('Starting local workflow service polling...')
|
||||||
|
workflowService.start()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Shutting down Temporal workers...')
|
||||||
|
await workflowService.shutdownWorkers()
|
||||||
|
await Promise.all([transcodeWorkerPromise].filter(Boolean))
|
||||||
|
}
|
||||||
|
workflowService.close()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
try {
|
||||||
|
console.log('Cleaning up local E2E storage files...')
|
||||||
|
await s3Service.deletePrefix('shumai-e2e-test-bucket-transcode', '')
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to clean up E2E storage folder:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should run transcodeMedia image annotation overlay successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E Image Annotation Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E Image Annotation Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/image-ann.png',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'image-ann.png',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'image/png',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from Fixture
|
||||||
|
const pngPath = path.join(fixturesDir, 'small.png')
|
||||||
|
const pngBuffer = fs.readFileSync(pngPath)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/image-ann.png',
|
||||||
|
pngBuffer,
|
||||||
|
pngBuffer.length,
|
||||||
|
'image/png',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_image_annotation',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
imageAnnotation: {
|
||||||
|
annotations: [
|
||||||
|
{
|
||||||
|
type: 'box',
|
||||||
|
color: '#ff0000',
|
||||||
|
points: [
|
||||||
|
[0.1, 0.1],
|
||||||
|
[0.9, 0.9],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E Image Annotation Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
// Verify task output contains overlay image key
|
||||||
|
const output = completedTask.output as unknown as { key: string }
|
||||||
|
expect(output).toBeDefined()
|
||||||
|
expect(output.key).toContain('annotations/')
|
||||||
|
}, 50000)
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||||
|
import { prisma } from '@shumai/db'
|
||||||
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
|
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||||
|
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import * as path from 'path'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
|
||||||
|
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
||||||
|
const fixturesDir = path.resolve(currentDir, '../fixtures')
|
||||||
|
|
||||||
|
describe.each(['local', 'temporal'] as const)(
|
||||||
|
'Workflow E2E - renderPdfPagesWorkflow (executor: %s)',
|
||||||
|
(mode) => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
let transcodeWorkerPromise: Promise<void> | null = null
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-transcode'
|
||||||
|
|
||||||
|
workflowService.setExecutorType(mode)
|
||||||
|
initTranscodeWorkflows()
|
||||||
|
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Starting background worker for transcode Temporal E2E tests...')
|
||||||
|
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
|
||||||
|
workflowsPath: transcodeWorkflowsPath,
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||||
|
} else {
|
||||||
|
console.log('Starting local workflow service polling...')
|
||||||
|
workflowService.start()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Shutting down Temporal workers...')
|
||||||
|
await workflowService.shutdownWorkers()
|
||||||
|
await Promise.all([transcodeWorkerPromise].filter(Boolean))
|
||||||
|
}
|
||||||
|
workflowService.close()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
try {
|
||||||
|
console.log('Cleaning up local E2E storage files...')
|
||||||
|
await s3Service.deletePrefix('shumai-e2e-test-bucket-transcode', '')
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to clean up E2E storage folder:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should run renderPdfPages workflow for a PDF asset successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E PDF Pages Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E PDF Pages Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/test-pages.pdf',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'test-pages.pdf',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'application/pdf',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from fixture test.pdf
|
||||||
|
const pdfPath = path.join(fixturesDir, 'test.pdf')
|
||||||
|
const pdfBuffer = fs.readFileSync(pdfPath)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/test-pages.pdf',
|
||||||
|
pdfBuffer,
|
||||||
|
pdfBuffer.length,
|
||||||
|
'application/pdf',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_pdf_pages',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
pdfPages: {
|
||||||
|
start: 1,
|
||||||
|
end: 2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(`Submitted E2E PDF Pages Workflow Task. ID: ${task.id}. Awaiting completion...`)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
// Verify output contains rendered pages
|
||||||
|
const output = completedTask.output as unknown as { pages: { key: string; page: number }[] }
|
||||||
|
expect(output).toBeDefined()
|
||||||
|
expect(output.pages).toBeDefined()
|
||||||
|
expect(output.pages.length).toBeGreaterThan(0)
|
||||||
|
}, 50000)
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||||
|
import { prisma } from '@shumai/db'
|
||||||
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
|
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||||
|
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import * as path from 'path'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
import sharp from 'sharp'
|
||||||
|
|
||||||
|
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
||||||
|
const fixturesDir = path.resolve(currentDir, '../fixtures')
|
||||||
|
|
||||||
|
describe.each(['local', 'temporal'] as const)(
|
||||||
|
'Workflow E2E - takeVideoScreenshotsWorkflow (executor: %s)',
|
||||||
|
(mode) => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
let transcodeWorkerPromise: Promise<void> | null = null
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-transcode'
|
||||||
|
|
||||||
|
workflowService.setExecutorType(mode)
|
||||||
|
initTranscodeWorkflows()
|
||||||
|
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Starting background worker for transcode Temporal E2E tests...')
|
||||||
|
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
|
||||||
|
workflowsPath: transcodeWorkflowsPath,
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||||
|
} else {
|
||||||
|
console.log('Starting local workflow service polling...')
|
||||||
|
workflowService.start()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Shutting down Temporal workers...')
|
||||||
|
await workflowService.shutdownWorkers()
|
||||||
|
await Promise.all([transcodeWorkerPromise].filter(Boolean))
|
||||||
|
}
|
||||||
|
workflowService.close()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
try {
|
||||||
|
console.log('Cleaning up local E2E storage files...')
|
||||||
|
await s3Service.deletePrefix('shumai-e2e-test-bucket-transcode', '')
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to clean up E2E storage folder:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should run transcodeMedia screenshot extraction successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E Video Screenshot Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E Video Screenshot Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/video-shot.mp4',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'video-shot.mp4',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from Fixture
|
||||||
|
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
||||||
|
const mp4Buffer = fs.readFileSync(mp4Path)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/video-shot.mp4',
|
||||||
|
mp4Buffer,
|
||||||
|
mp4Buffer.length,
|
||||||
|
'video/mp4',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_screenshot',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
screenshot: {
|
||||||
|
start: 0,
|
||||||
|
end: 1,
|
||||||
|
count: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E Video Screenshot Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
// Verify task output contains list of screenshots
|
||||||
|
const output = completedTask.output as unknown as { screenshots: { key: string }[] }
|
||||||
|
expect(output).toBeDefined()
|
||||||
|
expect(output.screenshots).toBeDefined()
|
||||||
|
expect(output.screenshots.length).toBe(1)
|
||||||
|
expect(output.screenshots[0].key).toContain('screenshots/')
|
||||||
|
}, 50000)
|
||||||
|
|
||||||
|
it('should draw annotation box correctly for 5 random comment timestamps', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E Video Screenshot Annotation Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E Video Screenshot Annotation Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/video-shot-ann.mp4',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'video-shot-ann.mp4',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from Fixture
|
||||||
|
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
||||||
|
const mp4Buffer = fs.readFileSync(mp4Path)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/video-shot-ann.mp4',
|
||||||
|
mp4Buffer,
|
||||||
|
mp4Buffer.length,
|
||||||
|
'video/mp4',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Generate 5 random comment timestamps between 0.05s and 0.95s
|
||||||
|
const randomTimestamps: number[] = []
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
const randomTs = 0.05 + Math.random() * 0.9
|
||||||
|
randomTimestamps.push(randomTs)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Testing random timestamps:', randomTimestamps)
|
||||||
|
|
||||||
|
const boxAnnotation = [
|
||||||
|
{
|
||||||
|
type: 'box' as const,
|
||||||
|
color: '#ff0000',
|
||||||
|
points: [
|
||||||
|
[0.2, 0.2],
|
||||||
|
[0.8, 0.8],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const commentTimestamp of randomTimestamps) {
|
||||||
|
// Create Workflow Task with commentTimestamp & annotations
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_screenshot',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
screenshot: {
|
||||||
|
start: 0,
|
||||||
|
end: 1,
|
||||||
|
count: 5,
|
||||||
|
commentTimestamp,
|
||||||
|
annotations: boxAnnotation,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
const output = completedTask.output as unknown as {
|
||||||
|
screenshots: { key: string; timestamp: number }[]
|
||||||
|
}
|
||||||
|
expect(output).toBeDefined()
|
||||||
|
expect(output.screenshots).toBeDefined()
|
||||||
|
|
||||||
|
// Find the screenshot matching commentTimestamp
|
||||||
|
const matchingShot = output.screenshots.find(
|
||||||
|
(s) => Math.abs(s.timestamp - commentTimestamp) < 1e-6,
|
||||||
|
)
|
||||||
|
expect(matchingShot).toBeDefined()
|
||||||
|
|
||||||
|
// Download screenshot buffer from S3
|
||||||
|
const s3Obj = await s3Service.getObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
matchingShot!.key,
|
||||||
|
)
|
||||||
|
const shotBuffer = s3Obj.buffer
|
||||||
|
|
||||||
|
// Verify pixel data using sharp to check if red box annotation was overlaid
|
||||||
|
const { data, info } = await sharp(shotBuffer).raw().toBuffer({ resolveWithObject: true })
|
||||||
|
|
||||||
|
// Target pixel inside box (e.g. x = 50%, y = 20% near top edge of red box)
|
||||||
|
const pixelX = Math.floor(info.width * 0.5)
|
||||||
|
const pixelY = Math.floor(info.height * 0.2)
|
||||||
|
const offset = (pixelY * info.width + pixelX) * info.channels
|
||||||
|
|
||||||
|
const r = data[offset]
|
||||||
|
const g = data[offset + 1]
|
||||||
|
const b = data[offset + 2]
|
||||||
|
|
||||||
|
// Red box color #ff0000 should result in high red channel and low green/blue channels
|
||||||
|
expect(r).toBeGreaterThan(150)
|
||||||
|
expect(g).toBeLessThan(120)
|
||||||
|
expect(b).toBeLessThan(120)
|
||||||
|
}
|
||||||
|
}, 90000)
|
||||||
|
|
||||||
|
it('should overlay annotation when commentTimestamp has rounding mismatch with start/end', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E Video Screenshot Rounding Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E Video Screenshot Rounding Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/video-shot-rounding.mp4',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'video-shot-rounding.mp4',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from Fixture
|
||||||
|
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
||||||
|
const mp4Buffer = fs.readFileSync(mp4Path)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/video-shot-rounding.mp4',
|
||||||
|
mp4Buffer,
|
||||||
|
mp4Buffer.length,
|
||||||
|
'video/mp4',
|
||||||
|
)
|
||||||
|
|
||||||
|
// Reproduce log scenario: exact timestamp is 0.566666666666667, Agent requested rounded 0.57
|
||||||
|
const commentTimestamp = 0.566666666666667
|
||||||
|
const start = 0.57
|
||||||
|
const end = 0.57
|
||||||
|
|
||||||
|
const boxAnnotation = [
|
||||||
|
{
|
||||||
|
type: 'box' as const,
|
||||||
|
color: '#ff0000',
|
||||||
|
points: [
|
||||||
|
[0.2, 0.2],
|
||||||
|
[0.8, 0.8],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_screenshot',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
screenshot: {
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
count: 1,
|
||||||
|
commentTimestamp,
|
||||||
|
annotations: boxAnnotation,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
const output = completedTask.output as unknown as {
|
||||||
|
screenshots: { key: string; timestamp: number }[]
|
||||||
|
}
|
||||||
|
expect(output).toBeDefined()
|
||||||
|
expect(output.screenshots).toBeDefined()
|
||||||
|
expect(output.screenshots.length).toBe(1)
|
||||||
|
|
||||||
|
const s3Obj = await s3Service.getObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
output.screenshots[0].key,
|
||||||
|
)
|
||||||
|
const shotBuffer = s3Obj.buffer
|
||||||
|
|
||||||
|
const { data, info } = await sharp(shotBuffer).raw().toBuffer({ resolveWithObject: true })
|
||||||
|
|
||||||
|
const pixelX = Math.floor(info.width * 0.5)
|
||||||
|
const pixelY = Math.floor(info.height * 0.2)
|
||||||
|
const offset = (pixelY * info.width + pixelX) * info.channels
|
||||||
|
|
||||||
|
const r = data[offset]
|
||||||
|
const g = data[offset + 1]
|
||||||
|
const b = data[offset + 2]
|
||||||
|
|
||||||
|
expect(r).toBeGreaterThan(150)
|
||||||
|
expect(g).toBeLessThan(120)
|
||||||
|
expect(b).toBeLessThan(120)
|
||||||
|
}, 50000)
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||||
|
import { prisma, AssetStatus } from '@shumai/db'
|
||||||
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
|
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||||
|
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import * as path from 'path'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
|
||||||
|
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
||||||
|
const fixturesDir = path.resolve(currentDir, '../fixtures')
|
||||||
|
|
||||||
|
describe.each(['local', 'temporal'] as const)(
|
||||||
|
'Workflow E2E - transcodeImageWorkflow (executor: %s)',
|
||||||
|
(mode) => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
let transcodeWorkerPromise: Promise<void> | null = null
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-transcode'
|
||||||
|
|
||||||
|
workflowService.setExecutorType(mode)
|
||||||
|
initTranscodeWorkflows()
|
||||||
|
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Starting background worker for transcode Temporal E2E tests...')
|
||||||
|
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
|
||||||
|
workflowsPath: transcodeWorkflowsPath,
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||||
|
} else {
|
||||||
|
console.log('Starting local workflow service polling...')
|
||||||
|
workflowService.start()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Shutting down Temporal workers...')
|
||||||
|
await workflowService.shutdownWorkers()
|
||||||
|
await Promise.all([transcodeWorkerPromise].filter(Boolean))
|
||||||
|
}
|
||||||
|
workflowService.close()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
try {
|
||||||
|
console.log('Cleaning up local E2E storage files...')
|
||||||
|
await s3Service.deletePrefix('shumai-e2e-test-bucket-transcode', '')
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to clean up E2E storage folder:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should run transcodeMedia workflow for an image asset successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E Image Transcode Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E Image Transcode Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/image-trans.png',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'image-trans.png',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'image/png',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from Fixture
|
||||||
|
const pngPath = path.join(fixturesDir, 'small.png')
|
||||||
|
const pngBuffer = fs.readFileSync(pngPath)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/image-trans.png',
|
||||||
|
pngBuffer,
|
||||||
|
pngBuffer.length,
|
||||||
|
'image/png',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_image',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
transcode: {
|
||||||
|
thumbnail: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E Image Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
const updatedAsset = await prisma.asset.findUnique({
|
||||||
|
where: { id: asset.id },
|
||||||
|
})
|
||||||
|
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||||
|
|
||||||
|
const mediaInfo = updatedAsset?.media as unknown as {
|
||||||
|
proxyType: string
|
||||||
|
imageTranscodes: unknown[]
|
||||||
|
thumbnail: unknown
|
||||||
|
}
|
||||||
|
expect(mediaInfo).toBeDefined()
|
||||||
|
expect(mediaInfo.proxyType).toBe('image')
|
||||||
|
expect(mediaInfo.imageTranscodes).toBeDefined()
|
||||||
|
expect(mediaInfo.imageTranscodes.length).toBeGreaterThan(0)
|
||||||
|
expect(mediaInfo.thumbnail).toBeDefined()
|
||||||
|
}, 50000)
|
||||||
|
|
||||||
|
it('should run transcodeMedia workflow for a PSD image asset successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E PSD Transcode Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E PSD Transcode Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/test.psd',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'test.psd',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'image/vnd.adobe.photoshop',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from fixture test.psd
|
||||||
|
const psdPath = path.join(fixturesDir, 'test.psd')
|
||||||
|
const psdBuffer = fs.readFileSync(psdPath)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/test.psd',
|
||||||
|
psdBuffer,
|
||||||
|
psdBuffer.length,
|
||||||
|
'image/vnd.adobe.photoshop',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_image',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
transcode: {
|
||||||
|
thumbnail: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E PSD Image Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
const updatedAsset = await prisma.asset.findUnique({
|
||||||
|
where: { id: asset.id },
|
||||||
|
})
|
||||||
|
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||||
|
|
||||||
|
const mediaInfo = updatedAsset?.media as unknown as {
|
||||||
|
proxyType: string
|
||||||
|
imageTranscodes: unknown[]
|
||||||
|
thumbnail: unknown
|
||||||
|
}
|
||||||
|
expect(mediaInfo).toBeDefined()
|
||||||
|
expect(mediaInfo.proxyType).toBe('image')
|
||||||
|
expect(mediaInfo.imageTranscodes).toBeDefined()
|
||||||
|
expect(mediaInfo.imageTranscodes.length).toBeGreaterThan(0)
|
||||||
|
expect(mediaInfo.thumbnail).toBeDefined()
|
||||||
|
}, 50000)
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||||
|
import { prisma, AssetStatus } from '@shumai/db'
|
||||||
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
|
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||||
|
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import * as path from 'path'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
|
||||||
|
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
||||||
|
const fixturesDir = path.resolve(currentDir, '../fixtures')
|
||||||
|
|
||||||
|
describe.each(['local', 'temporal'] as const)(
|
||||||
|
'Workflow E2E - transcodePdfWorkflow (executor: %s)',
|
||||||
|
(mode) => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
let transcodeWorkerPromise: Promise<void> | null = null
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-transcode'
|
||||||
|
|
||||||
|
workflowService.setExecutorType(mode)
|
||||||
|
initTranscodeWorkflows()
|
||||||
|
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Starting background worker for transcode Temporal E2E tests...')
|
||||||
|
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
|
||||||
|
workflowsPath: transcodeWorkflowsPath,
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||||
|
} else {
|
||||||
|
console.log('Starting local workflow service polling...')
|
||||||
|
workflowService.start()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Shutting down Temporal workers...')
|
||||||
|
await workflowService.shutdownWorkers()
|
||||||
|
await Promise.all([transcodeWorkerPromise].filter(Boolean))
|
||||||
|
}
|
||||||
|
workflowService.close()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
try {
|
||||||
|
console.log('Cleaning up local E2E storage files...')
|
||||||
|
await s3Service.deletePrefix('shumai-e2e-test-bucket-transcode', '')
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to clean up E2E storage folder:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should run transcodeMedia workflow for a PDF asset successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E PDF Transcode Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E PDF Transcode Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/test.pdf',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'test.pdf',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'application/pdf',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from fixture test.pdf
|
||||||
|
const pdfPath = path.join(fixturesDir, 'test.pdf')
|
||||||
|
const pdfBuffer = fs.readFileSync(pdfPath)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/test.pdf',
|
||||||
|
pdfBuffer,
|
||||||
|
pdfBuffer.length,
|
||||||
|
'application/pdf',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_pdf',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
transcode: {
|
||||||
|
poster: true,
|
||||||
|
sprite: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E PDF Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
// Verify Asset status is updated to processed
|
||||||
|
const updatedAsset = await prisma.asset.findUnique({
|
||||||
|
where: { id: asset.id },
|
||||||
|
})
|
||||||
|
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||||
|
|
||||||
|
// Verify media info contains pdf details, poster, sprite, and pageCount
|
||||||
|
const mediaInfo = updatedAsset?.media as unknown as {
|
||||||
|
proxyType: string
|
||||||
|
poster: { key: string }
|
||||||
|
sprite: { key: string }
|
||||||
|
frames?: number
|
||||||
|
pageCount?: number
|
||||||
|
metadata?: { totalFrames?: number; pageCount?: number }
|
||||||
|
}
|
||||||
|
expect(mediaInfo).toBeDefined()
|
||||||
|
expect(mediaInfo.proxyType).toBe('pdf')
|
||||||
|
expect(mediaInfo.poster).toBeDefined()
|
||||||
|
expect(mediaInfo.poster.key).toContain('poster.webp')
|
||||||
|
expect(mediaInfo.sprite).toBeDefined()
|
||||||
|
expect(mediaInfo.sprite.key).toContain('sprite.webp')
|
||||||
|
expect(mediaInfo.frames ?? mediaInfo.metadata?.totalFrames).toBeGreaterThan(0)
|
||||||
|
}, 50000)
|
||||||
|
|
||||||
|
it('should run transcodeMedia workflow for a TXT asset with CJK text to generate PDF proxy successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E CJK TXT Transcode Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E CJK TXT Transcode Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/cjk-test.txt',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'cjk-test.txt',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'text/plain',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage with CJK text
|
||||||
|
const cjkText =
|
||||||
|
'Hello World\n你好世界 (Chinese)\nこんにちは世界 (Japanese)\n안녕하세요世界 (Korean)\nLine 5 of random text.'
|
||||||
|
const txtBuffer = Buffer.from(cjkText, 'utf-8')
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/cjk-test.txt',
|
||||||
|
txtBuffer,
|
||||||
|
txtBuffer.length,
|
||||||
|
'text/plain',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_pdf',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
transcode: {
|
||||||
|
poster: true,
|
||||||
|
sprite: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E CJK TXT Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
const updatedAsset = await prisma.asset.findUnique({
|
||||||
|
where: { id: asset.id },
|
||||||
|
})
|
||||||
|
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||||
|
|
||||||
|
const mediaInfo = updatedAsset?.media as unknown as {
|
||||||
|
proxyType?: string
|
||||||
|
pdfTranscode?: { key: string }
|
||||||
|
poster?: { key: string }
|
||||||
|
sprite?: { key: string }
|
||||||
|
frames?: number
|
||||||
|
}
|
||||||
|
expect(mediaInfo).toBeDefined()
|
||||||
|
expect(mediaInfo.proxyType).toBe('pdf')
|
||||||
|
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
|
||||||
|
expect(mediaInfo.poster?.key).toContain('poster.webp')
|
||||||
|
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
|
||||||
|
expect(mediaInfo.frames).toBeGreaterThan(0)
|
||||||
|
}, 50000)
|
||||||
|
|
||||||
|
it('should process markdown (.md) transcode PDF task correctly', async () => {
|
||||||
|
// 1. Create Team, Project, Asset & StorageKey
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E MD Transcode Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E MD Transcode Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/doc.md',
|
||||||
|
status: 'active',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'doc.md',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'text/markdown',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage with Markdown text
|
||||||
|
const mdText = '# Heading\n\nThis is a **markdown** document to be rendered to PDF proxy.'
|
||||||
|
const mdBuffer = Buffer.from(mdText, 'utf-8')
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/doc.md',
|
||||||
|
mdBuffer,
|
||||||
|
mdBuffer.length,
|
||||||
|
'text/markdown',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_pdf',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
transcode: {
|
||||||
|
poster: true,
|
||||||
|
sprite: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E MD Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
const updatedAsset = await prisma.asset.findUnique({
|
||||||
|
where: { id: asset.id },
|
||||||
|
})
|
||||||
|
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||||
|
|
||||||
|
const mediaInfo = updatedAsset?.media as unknown as {
|
||||||
|
proxyType?: string
|
||||||
|
pdfTranscode?: { key: string }
|
||||||
|
poster?: { key: string }
|
||||||
|
sprite?: { key: string }
|
||||||
|
frames?: number
|
||||||
|
}
|
||||||
|
expect(mediaInfo).toBeDefined()
|
||||||
|
expect(mediaInfo.proxyType).toBe('pdf')
|
||||||
|
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
|
||||||
|
expect(mediaInfo.poster?.key).toContain('poster.webp')
|
||||||
|
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
|
||||||
|
expect(mediaInfo.frames).toBeGreaterThan(0)
|
||||||
|
}, 50000)
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||||
|
import { prisma, AssetStatus } from '@shumai/db'
|
||||||
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
|
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||||
|
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import * as path from 'path'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
|
||||||
|
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
||||||
|
const fixturesDir = path.resolve(currentDir, '../fixtures')
|
||||||
|
|
||||||
|
describe.each(['local', 'temporal'] as const)(
|
||||||
|
'Workflow E2E - transcodeVideoWorkflow (executor: %s)',
|
||||||
|
(mode) => {
|
||||||
|
setupTestDbHooks()
|
||||||
|
|
||||||
|
let transcodeWorkerPromise: Promise<void> | null = null
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-transcode'
|
||||||
|
|
||||||
|
workflowService.setExecutorType(mode)
|
||||||
|
initTranscodeWorkflows()
|
||||||
|
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Starting background worker for transcode Temporal E2E tests...')
|
||||||
|
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
|
||||||
|
workflowsPath: transcodeWorkflowsPath,
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||||
|
} else {
|
||||||
|
console.log('Starting local workflow service polling...')
|
||||||
|
workflowService.start()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (mode === 'temporal') {
|
||||||
|
console.log('Shutting down Temporal workers...')
|
||||||
|
await workflowService.shutdownWorkers()
|
||||||
|
await Promise.all([transcodeWorkerPromise].filter(Boolean))
|
||||||
|
}
|
||||||
|
workflowService.close()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
try {
|
||||||
|
console.log('Cleaning up local E2E storage files...')
|
||||||
|
await s3Service.deletePrefix('shumai-e2e-test-bucket-transcode', '')
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to clean up E2E storage folder:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should run transcodeMedia workflow for a video asset successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E Video Transcode Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E Video Transcode Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/video-trans.mp4',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'video-trans.mp4',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from Fixture
|
||||||
|
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
||||||
|
const mp4Buffer = fs.readFileSync(mp4Path)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/video-trans.mp4',
|
||||||
|
mp4Buffer,
|
||||||
|
mp4Buffer.length,
|
||||||
|
'video/mp4',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_video',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
transcode: {
|
||||||
|
videoStrategy: 'best_match',
|
||||||
|
thumbnail: false,
|
||||||
|
poster: true,
|
||||||
|
sprite: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E Video Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
// Verify Asset status is updated to processed
|
||||||
|
const updatedAsset = await prisma.asset.findUnique({
|
||||||
|
where: { id: asset.id },
|
||||||
|
})
|
||||||
|
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||||
|
|
||||||
|
// Verify media info contains videoTranscodes, poster, sprite, and duration details
|
||||||
|
const mediaInfo = updatedAsset?.media as unknown as {
|
||||||
|
proxyType: string
|
||||||
|
duration: number
|
||||||
|
videoTranscodes: { key: string }[]
|
||||||
|
poster: unknown
|
||||||
|
sprite: unknown
|
||||||
|
}
|
||||||
|
expect(mediaInfo).toBeDefined()
|
||||||
|
expect(mediaInfo.proxyType).toBe('video')
|
||||||
|
expect(mediaInfo.duration).toBeCloseTo(1.0, 1)
|
||||||
|
expect(mediaInfo.videoTranscodes).toBeDefined()
|
||||||
|
expect(mediaInfo.videoTranscodes.length).toBeGreaterThan(0)
|
||||||
|
expect(mediaInfo.poster).toBeDefined()
|
||||||
|
expect(mediaInfo.sprite).toBeDefined()
|
||||||
|
}, 50000)
|
||||||
|
|
||||||
|
it('should run transcodeMedia workflow for an audio asset successfully', async () => {
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E Audio Transcode Team' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const project = await prisma.project.create({
|
||||||
|
data: { name: 'E2E Audio Transcode Project', teamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const storageKey = await prisma.storageKey.create({
|
||||||
|
data: {
|
||||||
|
key: 'projects/e2e/audio-trans.wav',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'audio-trans.wav',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'audio/wav',
|
||||||
|
projectId: project.id,
|
||||||
|
storageKeyId: storageKey.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. Seed S3 Storage from Fixture
|
||||||
|
const wavPath = path.join(fixturesDir, 'small.wav')
|
||||||
|
const wavBuffer = fs.readFileSync(wavPath)
|
||||||
|
await s3Service.putObject(
|
||||||
|
'shumai-e2e-test-bucket-transcode',
|
||||||
|
'projects/e2e/audio-trans.wav',
|
||||||
|
wavBuffer,
|
||||||
|
wavBuffer.length,
|
||||||
|
'audio/wav',
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Create Workflow Task
|
||||||
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'transcode_video',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
transcode: {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 4. Wait for workflow to complete
|
||||||
|
console.log(
|
||||||
|
`Submitted E2E Audio Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
|
)
|
||||||
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
|
|
||||||
|
// 5. Verification
|
||||||
|
expect(completedTask.status).toBe('completed')
|
||||||
|
|
||||||
|
const updatedAsset = await prisma.asset.findUnique({
|
||||||
|
where: { id: asset.id },
|
||||||
|
})
|
||||||
|
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||||
|
|
||||||
|
const mediaInfo = updatedAsset?.media as unknown as {
|
||||||
|
proxyType: string
|
||||||
|
videoTranscodes: { key: string }[]
|
||||||
|
}
|
||||||
|
expect(mediaInfo).toBeDefined()
|
||||||
|
expect(mediaInfo.proxyType).toBe('audio')
|
||||||
|
expect(mediaInfo.videoTranscodes).toBeDefined()
|
||||||
|
expect(mediaInfo.videoTranscodes.length).toBeGreaterThan(0)
|
||||||
|
// Audio proxy key should end with -audio-proxy.mp4
|
||||||
|
expect(mediaInfo.videoTranscodes[0].key).toContain('-audio-proxy.mp4')
|
||||||
|
}, 50000)
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -1,871 +0,0 @@
|
|||||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
|
||||||
import { prisma, AssetStatus } from '@shumai/db'
|
|
||||||
import { setupTestDbHooks } from '@shumai/db/test'
|
|
||||||
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
|
||||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
|
||||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
|
||||||
import { fileURLToPath } from 'url'
|
|
||||||
import * as path from 'path'
|
|
||||||
import * as fs from 'fs'
|
|
||||||
|
|
||||||
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
|
||||||
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
|
||||||
const fixturesDir = path.resolve(currentDir, '../fixtures')
|
|
||||||
|
|
||||||
describe.each(['local', 'temporal'] as const)(
|
|
||||||
'Workflow E2E - transcodeMedia (executor: %s)',
|
|
||||||
(mode) => {
|
|
||||||
setupTestDbHooks()
|
|
||||||
|
|
||||||
let transcodeWorkerPromise: Promise<void> | null = null
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
|
||||||
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-transcode'
|
|
||||||
|
|
||||||
workflowService.setExecutorType(mode)
|
|
||||||
initTranscodeWorkflows()
|
|
||||||
|
|
||||||
if (mode === 'temporal') {
|
|
||||||
console.log('Starting background worker for transcode Temporal E2E tests...')
|
|
||||||
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
|
|
||||||
workflowsPath: transcodeWorkflowsPath,
|
|
||||||
})
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 2000))
|
|
||||||
} else {
|
|
||||||
console.log('Starting local workflow service polling...')
|
|
||||||
workflowService.start()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
afterAll(async () => {
|
|
||||||
if (mode === 'temporal') {
|
|
||||||
console.log('Shutting down Temporal workers...')
|
|
||||||
await workflowService.shutdownWorkers()
|
|
||||||
await Promise.all([transcodeWorkerPromise].filter(Boolean))
|
|
||||||
}
|
|
||||||
workflowService.close()
|
|
||||||
vi.restoreAllMocks()
|
|
||||||
try {
|
|
||||||
console.log('Cleaning up local E2E storage files...')
|
|
||||||
await s3Service.deletePrefix('shumai-e2e-test-bucket-transcode', '')
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to clean up E2E storage folder:', err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should run transcodeMedia workflow for a video asset successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E Video Transcode Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E Video Transcode Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/video-trans.mp4',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'video-trans.mp4',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'video/mp4',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage from Fixture
|
|
||||||
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
|
||||||
const mp4Buffer = fs.readFileSync(mp4Path)
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/video-trans.mp4',
|
|
||||||
mp4Buffer,
|
|
||||||
mp4Buffer.length,
|
|
||||||
'video/mp4',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_video',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
transcode: {
|
|
||||||
videoStrategy: 'best_match',
|
|
||||||
thumbnail: false,
|
|
||||||
poster: true,
|
|
||||||
sprite: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E Video Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
// Verify Asset status is updated to processed
|
|
||||||
const updatedAsset = await prisma.asset.findUnique({
|
|
||||||
where: { id: asset.id },
|
|
||||||
})
|
|
||||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
|
||||||
|
|
||||||
// Verify media info contains videoTranscodes, poster, sprite, and duration details
|
|
||||||
const mediaInfo = updatedAsset?.media as unknown as {
|
|
||||||
proxyType: string
|
|
||||||
duration: number
|
|
||||||
videoTranscodes: { key: string }[]
|
|
||||||
poster: unknown
|
|
||||||
sprite: unknown
|
|
||||||
}
|
|
||||||
expect(mediaInfo).toBeDefined()
|
|
||||||
expect(mediaInfo.proxyType).toBe('video')
|
|
||||||
expect(mediaInfo.duration).toBeCloseTo(1.0, 1)
|
|
||||||
expect(mediaInfo.videoTranscodes).toBeDefined()
|
|
||||||
expect(mediaInfo.videoTranscodes.length).toBeGreaterThan(0)
|
|
||||||
expect(mediaInfo.poster).toBeDefined()
|
|
||||||
expect(mediaInfo.sprite).toBeDefined()
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should run transcodeMedia workflow for an image asset successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E Image Transcode Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E Image Transcode Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/image-trans.png',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'image-trans.png',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'image/png',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage from Fixture
|
|
||||||
const pngPath = path.join(fixturesDir, 'small.png')
|
|
||||||
const pngBuffer = fs.readFileSync(pngPath)
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/image-trans.png',
|
|
||||||
pngBuffer,
|
|
||||||
pngBuffer.length,
|
|
||||||
'image/png',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_image',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
transcode: {
|
|
||||||
thumbnail: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E Image Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
const updatedAsset = await prisma.asset.findUnique({
|
|
||||||
where: { id: asset.id },
|
|
||||||
})
|
|
||||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
|
||||||
|
|
||||||
const mediaInfo = updatedAsset?.media as unknown as {
|
|
||||||
proxyType: string
|
|
||||||
imageTranscodes: unknown[]
|
|
||||||
thumbnail: unknown
|
|
||||||
}
|
|
||||||
expect(mediaInfo).toBeDefined()
|
|
||||||
expect(mediaInfo.proxyType).toBe('image')
|
|
||||||
expect(mediaInfo.imageTranscodes).toBeDefined()
|
|
||||||
expect(mediaInfo.imageTranscodes.length).toBeGreaterThan(0)
|
|
||||||
expect(mediaInfo.thumbnail).toBeDefined()
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should run transcodeMedia workflow for a PSD image asset successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E PSD Transcode Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E PSD Transcode Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/test.psd',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'test.psd',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'image/vnd.adobe.photoshop',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage from fixture test.psd
|
|
||||||
const psdPath = path.join(fixturesDir, 'test.psd')
|
|
||||||
const psdBuffer = fs.readFileSync(psdPath)
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/test.psd',
|
|
||||||
psdBuffer,
|
|
||||||
psdBuffer.length,
|
|
||||||
'image/vnd.adobe.photoshop',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_image',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
transcode: {
|
|
||||||
thumbnail: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E PSD Image Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
const updatedAsset = await prisma.asset.findUnique({
|
|
||||||
where: { id: asset.id },
|
|
||||||
})
|
|
||||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
|
||||||
|
|
||||||
const mediaInfo = updatedAsset?.media as unknown as {
|
|
||||||
proxyType: string
|
|
||||||
imageTranscodes: unknown[]
|
|
||||||
thumbnail: unknown
|
|
||||||
}
|
|
||||||
expect(mediaInfo).toBeDefined()
|
|
||||||
expect(mediaInfo.proxyType).toBe('image')
|
|
||||||
expect(mediaInfo.imageTranscodes).toBeDefined()
|
|
||||||
expect(mediaInfo.imageTranscodes.length).toBeGreaterThan(0)
|
|
||||||
expect(mediaInfo.thumbnail).toBeDefined()
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should run transcodeMedia workflow for an audio asset successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E Audio Transcode Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E Audio Transcode Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/audio-trans.wav',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'audio-trans.wav',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'audio/wav',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage from Fixture
|
|
||||||
const wavPath = path.join(fixturesDir, 'small.wav')
|
|
||||||
const wavBuffer = fs.readFileSync(wavPath)
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/audio-trans.wav',
|
|
||||||
wavBuffer,
|
|
||||||
wavBuffer.length,
|
|
||||||
'audio/wav',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_video',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
transcode: {},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E Audio Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
const updatedAsset = await prisma.asset.findUnique({
|
|
||||||
where: { id: asset.id },
|
|
||||||
})
|
|
||||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
|
||||||
|
|
||||||
const mediaInfo = updatedAsset?.media as unknown as {
|
|
||||||
proxyType: string
|
|
||||||
videoTranscodes: { key: string }[]
|
|
||||||
}
|
|
||||||
expect(mediaInfo).toBeDefined()
|
|
||||||
expect(mediaInfo.proxyType).toBe('audio')
|
|
||||||
expect(mediaInfo.videoTranscodes).toBeDefined()
|
|
||||||
expect(mediaInfo.videoTranscodes.length).toBeGreaterThan(0)
|
|
||||||
// Audio proxy key should end with -audio-proxy.mp4
|
|
||||||
expect(mediaInfo.videoTranscodes[0].key).toContain('-audio-proxy.mp4')
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should run transcodeMedia screenshot extraction successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E Video Screenshot Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E Video Screenshot Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/video-shot.mp4',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'video-shot.mp4',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'video/mp4',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage from Fixture
|
|
||||||
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
|
||||||
const mp4Buffer = fs.readFileSync(mp4Path)
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/video-shot.mp4',
|
|
||||||
mp4Buffer,
|
|
||||||
mp4Buffer.length,
|
|
||||||
'video/mp4',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_screenshot',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
screenshot: {
|
|
||||||
start: 0,
|
|
||||||
end: 1,
|
|
||||||
count: 1,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E Video Screenshot Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
// Verify task output contains list of screenshots
|
|
||||||
const output = completedTask.output as unknown as { screenshots: { key: string }[] }
|
|
||||||
expect(output).toBeDefined()
|
|
||||||
expect(output.screenshots).toBeDefined()
|
|
||||||
expect(output.screenshots.length).toBe(1)
|
|
||||||
expect(output.screenshots[0].key).toContain('screenshots/')
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should run transcodeMedia image annotation overlay successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E Image Annotation Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E Image Annotation Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/image-ann.png',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'image-ann.png',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'image/png',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage from Fixture
|
|
||||||
const pngPath = path.join(fixturesDir, 'small.png')
|
|
||||||
const pngBuffer = fs.readFileSync(pngPath)
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/image-ann.png',
|
|
||||||
pngBuffer,
|
|
||||||
pngBuffer.length,
|
|
||||||
'image/png',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_image_annotation',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
imageAnnotation: {
|
|
||||||
annotations: [
|
|
||||||
{
|
|
||||||
type: 'box',
|
|
||||||
color: '#ff0000',
|
|
||||||
points: [
|
|
||||||
[0.1, 0.1],
|
|
||||||
[0.9, 0.9],
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E Image Annotation Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
// Verify task output contains overlay image key
|
|
||||||
const output = completedTask.output as unknown as { key: string }
|
|
||||||
expect(output).toBeDefined()
|
|
||||||
expect(output.key).toContain('annotations/')
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should run transcodeMedia workflow for a PDF asset successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E PDF Transcode Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E PDF Transcode Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/test.pdf',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'test.pdf',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'application/pdf',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage from fixture test.pdf
|
|
||||||
const pdfPath = path.join(fixturesDir, 'test.pdf')
|
|
||||||
const pdfBuffer = fs.readFileSync(pdfPath)
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/test.pdf',
|
|
||||||
pdfBuffer,
|
|
||||||
pdfBuffer.length,
|
|
||||||
'application/pdf',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_pdf',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
transcode: {
|
|
||||||
poster: true,
|
|
||||||
sprite: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E PDF Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
// Verify Asset status is updated to processed
|
|
||||||
const updatedAsset = await prisma.asset.findUnique({
|
|
||||||
where: { id: asset.id },
|
|
||||||
})
|
|
||||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
|
||||||
|
|
||||||
// Verify media info contains pdf details, poster, sprite, and pageCount
|
|
||||||
const mediaInfo = updatedAsset?.media as unknown as {
|
|
||||||
proxyType: string
|
|
||||||
poster: { key: string }
|
|
||||||
sprite: { key: string }
|
|
||||||
frames?: number
|
|
||||||
pageCount?: number
|
|
||||||
metadata?: { totalFrames?: number; pageCount?: number }
|
|
||||||
}
|
|
||||||
expect(mediaInfo).toBeDefined()
|
|
||||||
expect(mediaInfo.proxyType).toBe('pdf')
|
|
||||||
expect(mediaInfo.poster).toBeDefined()
|
|
||||||
expect(mediaInfo.poster.key).toContain('poster.webp')
|
|
||||||
expect(mediaInfo.sprite).toBeDefined()
|
|
||||||
expect(mediaInfo.sprite.key).toContain('sprite.webp')
|
|
||||||
expect(mediaInfo.frames ?? mediaInfo.metadata?.totalFrames).toBeGreaterThan(0)
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should run renderPdfPages workflow for a PDF asset successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E PDF Pages Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E PDF Pages Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/test-pages.pdf',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'test-pages.pdf',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'application/pdf',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage from fixture test.pdf
|
|
||||||
const pdfPath = path.join(fixturesDir, 'test.pdf')
|
|
||||||
const pdfBuffer = fs.readFileSync(pdfPath)
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/test-pages.pdf',
|
|
||||||
pdfBuffer,
|
|
||||||
pdfBuffer.length,
|
|
||||||
'application/pdf',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_pdf_pages',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
pdfPages: {
|
|
||||||
start: 1,
|
|
||||||
end: 2,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(`Submitted E2E PDF Pages Workflow Task. ID: ${task.id}. Awaiting completion...`)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
// Verify output contains rendered pages
|
|
||||||
const output = completedTask.output as unknown as { pages: { key: string; page: number }[] }
|
|
||||||
expect(output).toBeDefined()
|
|
||||||
expect(output.pages).toBeDefined()
|
|
||||||
expect(output.pages.length).toBeGreaterThan(0)
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should run transcodeMedia workflow for a TXT asset with CJK text to generate PDF proxy successfully', async () => {
|
|
||||||
// 1. Seed Database
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E CJK TXT Transcode Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E CJK TXT Transcode Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/cjk-test.txt',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'cjk-test.txt',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'text/plain',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage with CJK text
|
|
||||||
const cjkText =
|
|
||||||
'Hello World\n你好世界 (Chinese)\nこんにちは世界 (Japanese)\n안녕하세요世界 (Korean)\nLine 5 of random text.'
|
|
||||||
const txtBuffer = Buffer.from(cjkText, 'utf-8')
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/cjk-test.txt',
|
|
||||||
txtBuffer,
|
|
||||||
txtBuffer.length,
|
|
||||||
'text/plain',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_pdf',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
transcode: {
|
|
||||||
poster: true,
|
|
||||||
sprite: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E CJK TXT Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
const updatedAsset = await prisma.asset.findUnique({
|
|
||||||
where: { id: asset.id },
|
|
||||||
})
|
|
||||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
|
||||||
|
|
||||||
const mediaInfo = updatedAsset?.media as unknown as {
|
|
||||||
proxyType?: string
|
|
||||||
pdfTranscode?: { key: string }
|
|
||||||
poster?: { key: string }
|
|
||||||
sprite?: { key: string }
|
|
||||||
frames?: number
|
|
||||||
}
|
|
||||||
expect(mediaInfo).toBeDefined()
|
|
||||||
expect(mediaInfo.proxyType).toBe('pdf')
|
|
||||||
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
|
|
||||||
expect(mediaInfo.poster?.key).toContain('poster.webp')
|
|
||||||
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
|
|
||||||
expect(mediaInfo.frames).toBeGreaterThan(0)
|
|
||||||
}, 50000)
|
|
||||||
|
|
||||||
it('should process markdown (.md) transcode PDF task correctly', async () => {
|
|
||||||
// 1. Create Team, Project, Asset & StorageKey
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: { name: 'E2E MD Transcode Team' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
|
||||||
data: { name: 'E2E MD Transcode Project', teamId: team.id },
|
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
|
||||||
data: {
|
|
||||||
key: 'projects/e2e/doc.md',
|
|
||||||
status: 'active',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
|
||||||
data: {
|
|
||||||
name: 'doc.md',
|
|
||||||
type: 'file',
|
|
||||||
status: 'uploaded',
|
|
||||||
mediaType: 'text/markdown',
|
|
||||||
projectId: project.id,
|
|
||||||
storageKeyId: storageKey.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. Seed S3 Storage with Markdown text
|
|
||||||
const mdText = '# Heading\n\nThis is a **markdown** document to be rendered to PDF proxy.'
|
|
||||||
const mdBuffer = Buffer.from(mdText, 'utf-8')
|
|
||||||
await s3Service.putObject(
|
|
||||||
'shumai-e2e-test-bucket-transcode',
|
|
||||||
'projects/e2e/doc.md',
|
|
||||||
mdBuffer,
|
|
||||||
mdBuffer.length,
|
|
||||||
'text/markdown',
|
|
||||||
)
|
|
||||||
|
|
||||||
// 3. Create Workflow Task
|
|
||||||
const task = await prisma.workflowTask.create({
|
|
||||||
data: {
|
|
||||||
type: 'transcode_pdf',
|
|
||||||
status: 'pending',
|
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
|
||||||
teamId: team.id,
|
|
||||||
payload: {
|
|
||||||
projectId: project.id,
|
|
||||||
transcode: {
|
|
||||||
poster: true,
|
|
||||||
sprite: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
|
||||||
console.log(
|
|
||||||
`Submitted E2E MD Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
|
||||||
)
|
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
|
||||||
|
|
||||||
// 5. Verification
|
|
||||||
expect(completedTask.status).toBe('completed')
|
|
||||||
|
|
||||||
const updatedAsset = await prisma.asset.findUnique({
|
|
||||||
where: { id: asset.id },
|
|
||||||
})
|
|
||||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
|
||||||
|
|
||||||
const mediaInfo = updatedAsset?.media as unknown as {
|
|
||||||
proxyType?: string
|
|
||||||
pdfTranscode?: { key: string }
|
|
||||||
poster?: { key: string }
|
|
||||||
sprite?: { key: string }
|
|
||||||
frames?: number
|
|
||||||
}
|
|
||||||
expect(mediaInfo).toBeDefined()
|
|
||||||
expect(mediaInfo.proxyType).toBe('pdf')
|
|
||||||
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
|
|
||||||
expect(mediaInfo.poster?.key).toContain('poster.webp')
|
|
||||||
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
|
|
||||||
expect(mediaInfo.frames).toBeGreaterThan(0)
|
|
||||||
}, 50000)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/tableprinter",
|
"name": "@shumai/tableprinter",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/transcode",
|
"name": "@shumai/transcode",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { useChatbotStore } from '@/ui/stores/chatbot'
|
|||||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||||
import { useDroppable } from '@dnd-kit/react'
|
import { useDroppable } from '@dnd-kit/react'
|
||||||
import type { ChatMessage } from '@shumai/dtos'
|
import type { ChatMessage } from '@shumai/dtos'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
ArrowUp,
|
ArrowUp,
|
||||||
@@ -26,7 +26,7 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
Wrench,
|
Wrench,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
import Markdown from 'react-markdown'
|
import Markdown from 'react-markdown'
|
||||||
import { formatTimeAgo } from '../lib/time'
|
import { formatTimeAgo } from '../lib/time'
|
||||||
|
|
||||||
@@ -171,9 +171,20 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
|||||||
}
|
}
|
||||||
}, [isHistoryMode, fetchHistorySessions, teamId])
|
}, [isHistoryMode, fetchHistorySessions, teamId])
|
||||||
|
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const handleAssetMutation = useCallback(() => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['search'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['folders'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['files'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['file'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['version_stacks'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['projects'] })
|
||||||
|
}, [queryClient])
|
||||||
|
|
||||||
const handleSend = () => {
|
const handleSend = () => {
|
||||||
if (!inputText.trim() || isStreaming || !teamId) return
|
if (!inputText.trim() || isStreaming || !teamId) return
|
||||||
sendMessage(teamId, inputText, projectId, contextAssetId)
|
sendMessage(teamId, inputText, projectId, contextAssetId, handleAssetMutation)
|
||||||
setInputText('')
|
setInputText('')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ interface FileBrowserContextMenuProps {
|
|||||||
onRename: (item: AssetInfo) => void
|
onRename: (item: AssetInfo) => void
|
||||||
onDelete: (items: AssetInfo[]) => void
|
onDelete: (items: AssetInfo[]) => void
|
||||||
onDownload: (items: AssetInfo[]) => void
|
onDownload: (items: AssetInfo[]) => void
|
||||||
|
onCopyNameAndDownloadLink?: (items: AssetInfo[]) => void
|
||||||
onRestore: (items: AssetInfo[]) => void
|
onRestore: (items: AssetInfo[]) => void
|
||||||
onNewFolder: (name: string) => void
|
onNewFolder: (name: string) => void
|
||||||
onUploadFile: () => void
|
onUploadFile: () => void
|
||||||
@@ -55,6 +56,7 @@ export function FileBrowserContextMenu({
|
|||||||
onRename,
|
onRename,
|
||||||
onDelete,
|
onDelete,
|
||||||
onDownload,
|
onDownload,
|
||||||
|
onCopyNameAndDownloadLink,
|
||||||
onRestore,
|
onRestore,
|
||||||
onNewFolder,
|
onNewFolder,
|
||||||
onUploadFile,
|
onUploadFile,
|
||||||
@@ -98,6 +100,14 @@ export function FileBrowserContextMenu({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleCopyNameAndDownloadLink = () => {
|
||||||
|
if (isItemSelected) {
|
||||||
|
onCopyNameAndDownloadLink?.(selectedItems)
|
||||||
|
} else if (item) {
|
||||||
|
onCopyNameAndDownloadLink?.([item])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const handleRestore = () => {
|
const handleRestore = () => {
|
||||||
onRestore(itemsToRestore)
|
onRestore(itemsToRestore)
|
||||||
}
|
}
|
||||||
@@ -110,6 +120,10 @@ export function FileBrowserContextMenu({
|
|||||||
<Download className="mr-2 h-4 w-4" />
|
<Download className="mr-2 h-4 w-4" />
|
||||||
<span>{m.download()}</span>
|
<span>{m.download()}</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
|
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink}>
|
||||||
|
<Copy className="mr-2 h-4 w-4" />
|
||||||
|
<span>{m.copy_name_and_download_link()}</span>
|
||||||
|
</ContextMenuItem>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<ContextMenuItem
|
<ContextMenuItem
|
||||||
onSelect={() => onRemoveFromShare?.(itemsToModify)}
|
onSelect={() => onRemoveFromShare?.(itemsToModify)}
|
||||||
@@ -177,6 +191,10 @@ export function FileBrowserContextMenu({
|
|||||||
<Download className="mr-2 h-4 w-4" />
|
<Download className="mr-2 h-4 w-4" />
|
||||||
<span>{m.download()}</span>
|
<span>{m.download()}</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
|
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink}>
|
||||||
|
<Copy className="mr-2 h-4 w-4" />
|
||||||
|
<span>{m.copy_name_and_download_link()}</span>
|
||||||
|
</ContextMenuItem>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||||
<ArrowRight className="mr-2 h-4 w-4" />
|
<ArrowRight className="mr-2 h-4 w-4" />
|
||||||
@@ -247,6 +265,10 @@ export function FileBrowserContextMenu({
|
|||||||
<Download className="mr-2 h-4 w-4" />
|
<Download className="mr-2 h-4 w-4" />
|
||||||
<span>{m.download()}</span>
|
<span>{m.download()}</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
|
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink}>
|
||||||
|
<Copy className="mr-2 h-4 w-4" />
|
||||||
|
<span>{m.copy_name_and_download_link()}</span>
|
||||||
|
</ContextMenuItem>
|
||||||
|
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||||
|
|||||||
@@ -400,6 +400,7 @@ export function FileBrowser({
|
|||||||
handleRename,
|
handleRename,
|
||||||
handleRestore,
|
handleRestore,
|
||||||
handleDownload,
|
handleDownload,
|
||||||
|
handleCopyNameAndDownloadLink,
|
||||||
handleAction,
|
handleAction,
|
||||||
onRenameSubmit,
|
onRenameSubmit,
|
||||||
isDeleteDialogOpen,
|
isDeleteDialogOpen,
|
||||||
@@ -1161,6 +1162,7 @@ export function FileBrowser({
|
|||||||
onRename={handleRename}
|
onRename={handleRename}
|
||||||
onDelete={handleDelete}
|
onDelete={handleDelete}
|
||||||
onDownload={handleDownload}
|
onDownload={handleDownload}
|
||||||
|
onCopyNameAndDownloadLink={handleCopyNameAndDownloadLink}
|
||||||
onNewFolder={handleNewFolder}
|
onNewFolder={handleNewFolder}
|
||||||
onUploadFile={handleUploadFilesClick}
|
onUploadFile={handleUploadFilesClick}
|
||||||
onUploadFolder={handleUploadFolderClick}
|
onUploadFolder={handleUploadFolderClick}
|
||||||
|
|||||||
@@ -223,8 +223,8 @@ export function FileCard({
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className={cn(
|
className={cn(
|
||||||
'group relative flex cursor-pointer select-none flex-col overflow-hidden rounded-xl border border-border bg-card transition-all hover:border-primary h-full m-1',
|
'group relative flex cursor-pointer select-none flex-col overflow-hidden rounded-xl border border-border bg-card transition-all hover:border-primary h-full m-1 outline-none focus:outline-none focus-visible:outline-none',
|
||||||
isSelected && 'outline-1 outline-primary border-primary',
|
(isSelected || isChecked) && 'outline-1 outline-primary border-primary',
|
||||||
showDropFeedback && 'border-primary outline-1 outline-primary',
|
showDropFeedback && 'border-primary outline-1 outline-primary',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -183,12 +183,12 @@ export function FileListItem({
|
|||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className="group cursor-pointer select-none transition-colors whitespace-nowrap flex w-full"
|
className="group cursor-pointer select-none transition-colors whitespace-nowrap flex w-full outline-none focus:outline-none focus-visible:outline-none"
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
'px-4 py-2 sticky left-0 z-10 transition-colors border-r shrink-0',
|
'px-4 py-2 sticky left-0 z-10 transition-colors border-r shrink-0',
|
||||||
isSelected ? 'bg-muted' : 'bg-card group-hover:bg-muted',
|
isSelected || isChecked ? 'bg-muted' : 'bg-card group-hover:bg-muted',
|
||||||
)}
|
)}
|
||||||
style={{
|
style={{
|
||||||
width: columnSizing?.['name'] || 300,
|
width: columnSizing?.['name'] || 300,
|
||||||
|
|||||||
@@ -272,7 +272,7 @@ export function FolderCard({
|
|||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
className={cn(
|
className={cn(
|
||||||
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full',
|
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full outline-none focus:outline-none focus-visible:outline-none',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="absolute inset-0 z-10 pointer-events-none">
|
<div className="absolute inset-0 z-10 pointer-events-none">
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ function ListRow({
|
|||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
className={cn(
|
className={cn(
|
||||||
'group border-b border-border transition-colors hover:bg-primary/20 absolute top-0 left-0 w-full flex flex-col',
|
'group border-b border-border transition-colors hover:bg-primary/20 absolute top-0 left-0 w-full flex flex-col outline-none focus:outline-none focus-visible:outline-none',
|
||||||
isSelected && 'bg-primary/10',
|
isSelected && 'bg-primary/10',
|
||||||
showDropFeedback && 'bg-primary/10',
|
showDropFeedback && 'bg-primary/10',
|
||||||
isTopOver && 'border-t-2 border-t-primary',
|
isTopOver && 'border-t-2 border-t-primary',
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
|
|||||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import { copyToClipboard } from '@/ui/lib/clipboard'
|
||||||
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
|
||||||
interface UseFileActionsProps {
|
interface UseFileActionsProps {
|
||||||
teamId: string
|
teamId: string
|
||||||
@@ -226,6 +228,32 @@ export function useFileActions({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleCopyNameAndDownloadLink = async (items: AssetInfo[]) => {
|
||||||
|
if (items.length === 0) return
|
||||||
|
try {
|
||||||
|
const res = await getDownloadLinks({
|
||||||
|
json: { ids: items.map((i) => i.id!) },
|
||||||
|
})
|
||||||
|
const files = res.files
|
||||||
|
if (files.length === 0) return
|
||||||
|
|
||||||
|
let text = ''
|
||||||
|
if (files.length === 1) {
|
||||||
|
text = `Name: ${files[0].name}\nPath: ${files[0].url}`
|
||||||
|
} else {
|
||||||
|
text = files.map((f) => `${f.name}\t${f.url}`).join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = await copyToClipboard(text)
|
||||||
|
if (ok) {
|
||||||
|
toast.success(m.copied_name_and_download_link_to_clipboard())
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
toast.error('Failed to copy name and download link')
|
||||||
|
console.error(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const startDownload = () => {
|
const startDownload = () => {
|
||||||
const files = [...resolvedFiles]
|
const files = [...resolvedFiles]
|
||||||
setIsDownloadDialogOpen(false)
|
setIsDownloadDialogOpen(false)
|
||||||
@@ -321,7 +349,10 @@ export function useFileActions({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleAction = (action: 'rename' | 'delete' | 'download' | 'restore', item: AssetInfo) => {
|
const handleAction = (
|
||||||
|
action: 'rename' | 'delete' | 'download' | 'restore' | 'copy-name-and-download-link',
|
||||||
|
item: AssetInfo,
|
||||||
|
) => {
|
||||||
const isSelected = selectedIds.has(item.id!)
|
const isSelected = selectedIds.has(item.id!)
|
||||||
const targetItems = isSelected
|
const targetItems = isSelected
|
||||||
? [...folders, ...files].filter((i) => selectedIds.has(i.id!))
|
? [...folders, ...files].filter((i) => selectedIds.has(i.id!))
|
||||||
@@ -340,6 +371,9 @@ export function useFileActions({
|
|||||||
case 'restore':
|
case 'restore':
|
||||||
handleRestore(targetItems)
|
handleRestore(targetItems)
|
||||||
break
|
break
|
||||||
|
case 'copy-name-and-download-link':
|
||||||
|
handleCopyNameAndDownloadLink(targetItems)
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,6 +384,7 @@ export function useFileActions({
|
|||||||
handleDelete,
|
handleDelete,
|
||||||
handleRestore,
|
handleRestore,
|
||||||
handleDownload,
|
handleDownload,
|
||||||
|
handleCopyNameAndDownloadLink,
|
||||||
handleNewFolder,
|
handleNewFolder,
|
||||||
handleAction,
|
handleAction,
|
||||||
onRenameSubmit,
|
onRenameSubmit,
|
||||||
|
|||||||
@@ -19,11 +19,12 @@ import { useTopNavStore } from '@/ui/stores/top-nav'
|
|||||||
import { useUiStore } from '@/ui/stores/ui'
|
import { useUiStore } from '@/ui/stores/ui'
|
||||||
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
|
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
|
||||||
import { Feedback, PointerActivationConstraints } from '@dnd-kit/dom'
|
import { Feedback, PointerActivationConstraints } from '@dnd-kit/dom'
|
||||||
import { DragDropProvider, DragOverlay, KeyboardSensor, PointerSensor } from '@dnd-kit/react'
|
import { DragDropProvider, DragOverlay, PointerSensor } from '@dnd-kit/react'
|
||||||
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { cn } from '../lib/utils'
|
import { cn } from '../lib/utils'
|
||||||
|
import { getSelectedRangeIds } from '../lib/selection-utils'
|
||||||
import { ChatbotSidebar } from './chatbot-sidebar'
|
import { ChatbotSidebar } from './chatbot-sidebar'
|
||||||
import { SnapToPointer } from './dnd-modifiers'
|
import { SnapToPointer } from './dnd-modifiers'
|
||||||
import { FileBrowser } from './file-browser/file-browser'
|
import { FileBrowser } from './file-browser/file-browser'
|
||||||
@@ -337,27 +338,18 @@ export default function FileSystemManager({
|
|||||||
const lastSelectedItem = allItems.find((i) => i.id === lastSelectedId)
|
const lastSelectedItem = allItems.find((i) => i.id === lastSelectedId)
|
||||||
|
|
||||||
if (lastSelectedItem) {
|
if (lastSelectedItem) {
|
||||||
if (lastSelectedItem.type === item.type) {
|
const newSelectedIds = getSelectedRangeIds(
|
||||||
// Only select range if they are the same type
|
lastSelectedItem,
|
||||||
const typeItems = item.type === 'folder' ? folders : files
|
item,
|
||||||
const lastIndex = typeItems.findIndex((i) => i.id === lastSelectedId)
|
lastSelectedId,
|
||||||
const currentIndex = typeItems.findIndex((i) => i.id === item.id)
|
folders,
|
||||||
|
files,
|
||||||
|
selectedIds,
|
||||||
|
)
|
||||||
|
|
||||||
if (lastIndex !== -1 && currentIndex !== -1) {
|
if (newSelectedIds) {
|
||||||
const start = Math.min(lastIndex, currentIndex)
|
setSelectedIds(newSelectedIds)
|
||||||
const end = Math.max(lastIndex, currentIndex)
|
setSelectedItem(item)
|
||||||
const rangeItems = typeItems.slice(start, end + 1)
|
|
||||||
|
|
||||||
const newSelectedIds = new Set(selectedIds)
|
|
||||||
rangeItems.forEach((rangeItem) => {
|
|
||||||
newSelectedIds.add(rangeItem.id)
|
|
||||||
})
|
|
||||||
setSelectedIds(newSelectedIds)
|
|
||||||
setSelectedItem(item)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// If types are different, do nothing (as requested by user)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -426,7 +418,6 @@ export default function FileSystemManager({
|
|||||||
PointerSensor.configure({
|
PointerSensor.configure({
|
||||||
activationConstraints: [new PointerActivationConstraints.Distance({ value: 10 })],
|
activationConstraints: [new PointerActivationConstraints.Distance({ value: 10 })],
|
||||||
}),
|
}),
|
||||||
KeyboardSensor,
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
onDragStart={handleDragStart}
|
onDragStart={handleDragStart}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { Input } from '@/ui/components/ui/input'
|
|||||||
import { ChevronDown, Copy, Loader2, Trash2 } from 'lucide-react'
|
import { ChevronDown, Copy, Loader2, Trash2 } from 'lucide-react'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import { copyToClipboard as copyTextToClipboard } from '@/ui/lib/clipboard'
|
||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
|
||||||
export interface Member {
|
export interface Member {
|
||||||
@@ -131,10 +132,12 @@ export function MembersDialog({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const copyToClipboard = () => {
|
const copyToClipboard = async () => {
|
||||||
if (inviteLink) {
|
if (inviteLink) {
|
||||||
navigator.clipboard.writeText(inviteLink)
|
const ok = await copyTextToClipboard(inviteLink)
|
||||||
toast.success(m.invite_link_copied())
|
if (ok) {
|
||||||
|
toast.success(m.invite_link_copied())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
} from '@/ui/components/ui/table'
|
} from '@/ui/components/ui/table'
|
||||||
import { Loader2, Plus, Trash2, Copy, Check } from 'lucide-react'
|
import { Loader2, Plus, Trash2, Copy, Check } from 'lucide-react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import { copyToClipboard } from '@/ui/lib/clipboard'
|
||||||
import type { ApiTokenResponse } from '@shumai/dtos'
|
import type { ApiTokenResponse } from '@shumai/dtos'
|
||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
|
||||||
@@ -75,8 +76,8 @@ export function DeveloperSettings({ teamId }: { teamId: string }) {
|
|||||||
createToken(tokenName.trim())
|
createToken(tokenName.trim())
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCopy = (id: string, token: string) => {
|
const handleCopy = async (id: string, token: string) => {
|
||||||
navigator.clipboard.writeText(token)
|
await copyToClipboard(token)
|
||||||
setCopiedId(id)
|
setCopiedId(id)
|
||||||
toast.success(m.copied_api_token_to_clipboard())
|
toast.success(m.copied_api_token_to_clipboard())
|
||||||
setTimeout(() => setCopiedId(null), 2000)
|
setTimeout(() => setCopiedId(null), 2000)
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import { ShareSettingsSidebar } from './share-settings-sidebar'
|
|||||||
import { FolderTree } from './folder-tree'
|
import { FolderTree } from './folder-tree'
|
||||||
import { ResizeHandle } from './resize-handle'
|
import { ResizeHandle } from './resize-handle'
|
||||||
import { useFileSystemDnd } from './use-file-system-dnd'
|
import { useFileSystemDnd } from './use-file-system-dnd'
|
||||||
import { DragDropProvider, DragOverlay, KeyboardSensor, PointerSensor } from '@dnd-kit/react'
|
import { DragDropProvider, DragOverlay, PointerSensor } from '@dnd-kit/react'
|
||||||
import { PointerActivationConstraints } from '@dnd-kit/dom'
|
import { PointerActivationConstraints } from '@dnd-kit/dom'
|
||||||
import { SnapToPointer } from './dnd-modifiers'
|
import { SnapToPointer } from './dnd-modifiers'
|
||||||
import { useUiStore } from '@/ui/stores/ui'
|
import { useUiStore } from '@/ui/stores/ui'
|
||||||
@@ -268,7 +268,6 @@ export default function ShareManager({
|
|||||||
PointerSensor.configure({
|
PointerSensor.configure({
|
||||||
activationConstraints: [new PointerActivationConstraints.Distance({ value: 10 })],
|
activationConstraints: [new PointerActivationConstraints.Distance({ value: 10 })],
|
||||||
}),
|
}),
|
||||||
KeyboardSensor,
|
|
||||||
]}
|
]}
|
||||||
onDragStart={handleDragStart}
|
onDragStart={handleDragStart}
|
||||||
onDragEnd={handleDragEnd}
|
onDragEnd={handleDragEnd}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import React, { useState } from 'react'
|
import React, { useState } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import { copyToClipboard as copyTextToClipboard } from '@/ui/lib/clipboard'
|
||||||
import { DateTimePicker } from '@/ui/components/datetime-picker'
|
import { DateTimePicker } from '@/ui/components/datetime-picker'
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
@@ -88,9 +89,11 @@ export function ShareSettingsSidebar({
|
|||||||
|
|
||||||
const shareUrl = `${window.location.origin}/share/${shareLink.id}`
|
const shareUrl = `${window.location.origin}/share/${shareLink.id}`
|
||||||
|
|
||||||
const copyToClipboard = (text: string) => {
|
const copyToClipboard = async (text: string) => {
|
||||||
navigator.clipboard.writeText(text)
|
const ok = await copyTextToClipboard(text)
|
||||||
toast.success(m.copied_to_clipboard())
|
if (ok) {
|
||||||
|
toast.success(m.copied_to_clipboard())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const toggleFieldVisibility = (fieldId: string) => {
|
const toggleFieldVisibility = (fieldId: string) => {
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
// @vitest-environment happy-dom
|
||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
import { copyToClipboard } from './clipboard'
|
||||||
|
|
||||||
|
describe('copyToClipboard', () => {
|
||||||
|
const originalClipboard = navigator.clipboard
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
Object.defineProperty(navigator, 'clipboard', {
|
||||||
|
value: originalClipboard,
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses navigator.clipboard.writeText when available', async () => {
|
||||||
|
const mockWriteText = vi.fn().mockResolvedValue(undefined)
|
||||||
|
Object.defineProperty(navigator, 'clipboard', {
|
||||||
|
value: { writeText: mockWriteText },
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const success = await copyToClipboard('test text')
|
||||||
|
expect(success).toBe(true)
|
||||||
|
expect(mockWriteText).toHaveBeenCalledWith('test text')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to execCommand when navigator.clipboard is missing', async () => {
|
||||||
|
Object.defineProperty(navigator, 'clipboard', {
|
||||||
|
value: undefined,
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const execCommandFn = vi.fn().mockReturnValue(true)
|
||||||
|
Object.defineProperty(document, 'execCommand', {
|
||||||
|
value: execCommandFn,
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const success = await copyToClipboard('fallback text')
|
||||||
|
expect(success).toBe(true)
|
||||||
|
expect(execCommandFn).toHaveBeenCalledWith('copy')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* Copies text to clipboard across both HTTP (non-secure context) and HTTPS (secure context).
|
||||||
|
*/
|
||||||
|
export async function copyToClipboard(text: string): Promise<boolean> {
|
||||||
|
if (
|
||||||
|
typeof navigator !== 'undefined' &&
|
||||||
|
navigator.clipboard &&
|
||||||
|
typeof navigator.clipboard.writeText === 'function'
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text)
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
// Fallback if navigator.clipboard fails or permission is denied
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback for non-secure HTTP context using execCommand
|
||||||
|
try {
|
||||||
|
const textArea = document.createElement('textarea')
|
||||||
|
textArea.value = text
|
||||||
|
textArea.style.position = 'fixed'
|
||||||
|
textArea.style.top = '0'
|
||||||
|
textArea.style.left = '0'
|
||||||
|
textArea.style.width = '2em'
|
||||||
|
textArea.style.height = '2em'
|
||||||
|
textArea.style.padding = '0'
|
||||||
|
textArea.style.border = 'none'
|
||||||
|
textArea.style.outline = 'none'
|
||||||
|
textArea.style.boxShadow = 'none'
|
||||||
|
textArea.style.background = 'transparent'
|
||||||
|
textArea.style.opacity = '0'
|
||||||
|
document.body.appendChild(textArea)
|
||||||
|
textArea.focus()
|
||||||
|
textArea.select()
|
||||||
|
const successful = document.execCommand('copy')
|
||||||
|
document.body.removeChild(textArea)
|
||||||
|
return successful
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to copy text to clipboard:', err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { getSelectedRangeIds } from './selection-utils'
|
||||||
|
import type { AssetInfo } from '@shumai/dtos'
|
||||||
|
|
||||||
|
describe('getSelectedRangeIds', () => {
|
||||||
|
const folders = [
|
||||||
|
{ id: 'folder1', name: 'Folder 1', type: 'folder', status: 'processed' },
|
||||||
|
{ id: 'folder2', name: 'Folder 2', type: 'folder', status: 'processed' },
|
||||||
|
] as unknown as AssetInfo[]
|
||||||
|
|
||||||
|
const files = [
|
||||||
|
{ id: 'stack1', name: 'Version Stack 1', type: 'version_stack', status: 'processed' },
|
||||||
|
{ id: 'file1', name: 'Image 1.png', type: 'file', status: 'processed' },
|
||||||
|
{ id: 'file2', name: 'Image 2.png', type: 'file', status: 'processed' },
|
||||||
|
] as unknown as AssetInfo[]
|
||||||
|
|
||||||
|
it('selects range when starting with version_stack and ending with a regular file', () => {
|
||||||
|
const lastSelectedItem = files[0] // version_stack
|
||||||
|
const currentItem = files[2] // file2
|
||||||
|
|
||||||
|
const result = getSelectedRangeIds(
|
||||||
|
lastSelectedItem,
|
||||||
|
currentItem,
|
||||||
|
'stack1',
|
||||||
|
folders,
|
||||||
|
files,
|
||||||
|
new Set(['stack1']),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(result).not.toBeNull()
|
||||||
|
expect(result?.size).toBe(3)
|
||||||
|
expect(result?.has('stack1')).toBe(true)
|
||||||
|
expect(result?.has('file1')).toBe(true)
|
||||||
|
expect(result?.has('file2')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('selects range when starting with a regular file and ending with version_stack', () => {
|
||||||
|
const lastSelectedItem = files[2] // file2
|
||||||
|
const currentItem = files[0] // stack1
|
||||||
|
|
||||||
|
const result = getSelectedRangeIds(
|
||||||
|
lastSelectedItem,
|
||||||
|
currentItem,
|
||||||
|
'file2',
|
||||||
|
folders,
|
||||||
|
files,
|
||||||
|
new Set(['file2']),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(result).not.toBeNull()
|
||||||
|
expect(result?.size).toBe(3)
|
||||||
|
expect(result?.has('stack1')).toBe(true)
|
||||||
|
expect(result?.has('file1')).toBe(true)
|
||||||
|
expect(result?.has('file2')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns null when range selecting across folder and file', () => {
|
||||||
|
const lastSelectedItem = folders[0] // folder1
|
||||||
|
const currentItem = files[1] // file1
|
||||||
|
|
||||||
|
const result = getSelectedRangeIds(
|
||||||
|
lastSelectedItem,
|
||||||
|
currentItem,
|
||||||
|
'folder1',
|
||||||
|
folders,
|
||||||
|
files,
|
||||||
|
new Set(['folder1']),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(result).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('selects range between folders', () => {
|
||||||
|
const lastSelectedItem = folders[0] // folder1
|
||||||
|
const currentItem = folders[1] // folder2
|
||||||
|
|
||||||
|
const result = getSelectedRangeIds(
|
||||||
|
lastSelectedItem,
|
||||||
|
currentItem,
|
||||||
|
'folder1',
|
||||||
|
folders,
|
||||||
|
files,
|
||||||
|
new Set(['folder1']),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(result).not.toBeNull()
|
||||||
|
expect(result?.size).toBe(2)
|
||||||
|
expect(result?.has('folder1')).toBe(true)
|
||||||
|
expect(result?.has('folder2')).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import type { AssetInfo } from '@shumai/dtos'
|
||||||
|
|
||||||
|
export function getSelectedRangeIds(
|
||||||
|
lastSelectedItem: AssetInfo,
|
||||||
|
currentItem: AssetInfo,
|
||||||
|
lastSelectedId: string,
|
||||||
|
folders: AssetInfo[],
|
||||||
|
files: AssetInfo[],
|
||||||
|
currentSelectedIds: Set<string>,
|
||||||
|
): Set<string> | null {
|
||||||
|
const isLastFolder = lastSelectedItem.type === 'folder'
|
||||||
|
const isCurrentFolder = currentItem.type === 'folder'
|
||||||
|
|
||||||
|
if (isLastFolder !== isCurrentFolder) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const typeItems = isCurrentFolder ? folders : files
|
||||||
|
const lastIndex = typeItems.findIndex((i) => i.id === lastSelectedId)
|
||||||
|
const currentIndex = typeItems.findIndex((i) => i.id === currentItem.id)
|
||||||
|
|
||||||
|
if (lastIndex === -1 || currentIndex === -1) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const start = Math.min(lastIndex, currentIndex)
|
||||||
|
const end = Math.max(lastIndex, currentIndex)
|
||||||
|
const rangeItems = typeItems.slice(start, end + 1)
|
||||||
|
|
||||||
|
const newSelectedIds = new Set(currentSelectedIds)
|
||||||
|
rangeItems.forEach((rangeItem) => {
|
||||||
|
if (rangeItem.id) {
|
||||||
|
newSelectedIds.add(rangeItem.id)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return newSelectedIds
|
||||||
|
}
|
||||||
@@ -269,6 +269,8 @@
|
|||||||
"failed_to_revoke_token": "Failed to revoke token",
|
"failed_to_revoke_token": "Failed to revoke token",
|
||||||
"copied_to_clipboard": "Copied to clipboard",
|
"copied_to_clipboard": "Copied to clipboard",
|
||||||
"copied_api_token_to_clipboard": "Copied API token to clipboard",
|
"copied_api_token_to_clipboard": "Copied API token to clipboard",
|
||||||
|
"copy_name_and_download_link": "Copy name and download link",
|
||||||
|
"copied_name_and_download_link_to_clipboard": "Copied name and download link to clipboard",
|
||||||
|
|
||||||
"ai": "AI",
|
"ai": "AI",
|
||||||
"providers": "Providers",
|
"providers": "Providers",
|
||||||
|
|||||||
@@ -269,6 +269,8 @@
|
|||||||
"failed_to_revoke_token": "撤销令牌失败",
|
"failed_to_revoke_token": "撤销令牌失败",
|
||||||
"copied_to_clipboard": "已复制到剪贴板",
|
"copied_to_clipboard": "已复制到剪贴板",
|
||||||
"copied_api_token_to_clipboard": "已将 API 令牌复制到剪贴板",
|
"copied_api_token_to_clipboard": "已将 API 令牌复制到剪贴板",
|
||||||
|
"copy_name_and_download_link": "复制名称和下载链接",
|
||||||
|
"copied_name_and_download_link_to_clipboard": "已复制名称和下载链接到剪贴板",
|
||||||
|
|
||||||
"ai": "AI",
|
"ai": "AI",
|
||||||
"providers": "提供商",
|
"providers": "提供商",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/webui",
|
"name": "@shumai/webui",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./index.html",
|
"main": "./index.html",
|
||||||
|
|||||||
+2
@@ -254,6 +254,8 @@ export * from "./api_token_revoked_successfully.js";
|
|||||||
export * from "./failed_to_revoke_token.js";
|
export * from "./failed_to_revoke_token.js";
|
||||||
export * from "./copied_to_clipboard.js";
|
export * from "./copied_to_clipboard.js";
|
||||||
export * from "./copied_api_token_to_clipboard.js";
|
export * from "./copied_api_token_to_clipboard.js";
|
||||||
|
export * from "./copy_name_and_download_link.js";
|
||||||
|
export * from "./copied_name_and_download_link_to_clipboard.js";
|
||||||
export * from "./ai.js";
|
export * from "./ai.js";
|
||||||
export * from "./providers.js";
|
export * from "./providers.js";
|
||||||
export * from "./providers_description.js";
|
export * from "./providers_description.js";
|
||||||
|
|||||||
+2
@@ -256,6 +256,8 @@ export * from './api_token_revoked_successfully.js'
|
|||||||
export * from './failed_to_revoke_token.js'
|
export * from './failed_to_revoke_token.js'
|
||||||
export * from './copied_to_clipboard.js'
|
export * from './copied_to_clipboard.js'
|
||||||
export * from './copied_api_token_to_clipboard.js'
|
export * from './copied_api_token_to_clipboard.js'
|
||||||
|
export * from './copy_name_and_download_link.js'
|
||||||
|
export * from './copied_name_and_download_link_to_clipboard.js'
|
||||||
export * from './ai.js'
|
export * from './ai.js'
|
||||||
export * from './providers.js'
|
export * from './providers.js'
|
||||||
export * from './providers_description.js'
|
export * from './providers_description.js'
|
||||||
|
|||||||
Generated
Vendored
+16
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* | output |
|
||||||
|
* | --- |
|
||||||
|
* | "Copied name and download link to clipboard" |
|
||||||
|
*
|
||||||
|
* @param {Copied_Name_And_Download_Link_To_ClipboardInputs} inputs
|
||||||
|
* @param {{ locale?: "en" | "zh" }} options
|
||||||
|
* @returns {LocalizedString}
|
||||||
|
*/
|
||||||
|
export const copied_name_and_download_link_to_clipboard: ((inputs?: Copied_Name_And_Download_Link_To_ClipboardInputs, options?: {
|
||||||
|
locale?: "en" | "zh";
|
||||||
|
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Copied_Name_And_Download_Link_To_ClipboardInputs, {
|
||||||
|
locale?: "en" | "zh";
|
||||||
|
}, {}>;
|
||||||
|
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||||
|
export type Copied_Name_And_Download_Link_To_ClipboardInputs = {};
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||||
|
|
||||||
|
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||||
|
|
||||||
|
/** @typedef {{}} Copied_Name_And_Download_Link_To_ClipboardInputs */
|
||||||
|
|
||||||
|
const en_copied_name_and_download_link_to_clipboard = /** @type {(inputs: Copied_Name_And_Download_Link_To_ClipboardInputs) => LocalizedString} */ () => {
|
||||||
|
return /** @type {LocalizedString} */ (`Copied name and download link to clipboard`)
|
||||||
|
};
|
||||||
|
|
||||||
|
const zh_copied_name_and_download_link_to_clipboard = /** @type {(inputs: Copied_Name_And_Download_Link_To_ClipboardInputs) => LocalizedString} */ () => {
|
||||||
|
return /** @type {LocalizedString} */ (`已复制名称和下载链接到剪贴板`)
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* | output |
|
||||||
|
* | --- |
|
||||||
|
* | "Copied name and download link to clipboard" |
|
||||||
|
*
|
||||||
|
* @param {Copied_Name_And_Download_Link_To_ClipboardInputs} inputs
|
||||||
|
* @param {{ locale?: "en" | "zh" }} options
|
||||||
|
* @returns {LocalizedString}
|
||||||
|
*/
|
||||||
|
export const copied_name_and_download_link_to_clipboard = /** @type {((inputs?: Copied_Name_And_Download_Link_To_ClipboardInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Copied_Name_And_Download_Link_To_ClipboardInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||||
|
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||||
|
if (locale === "en") return en_copied_name_and_download_link_to_clipboard(inputs)
|
||||||
|
return zh_copied_name_and_download_link_to_clipboard(inputs)
|
||||||
|
});
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* | output |
|
||||||
|
* | --- |
|
||||||
|
* | "Copy name and download link" |
|
||||||
|
*
|
||||||
|
* @param {Copy_Name_And_Download_LinkInputs} inputs
|
||||||
|
* @param {{ locale?: "en" | "zh" }} options
|
||||||
|
* @returns {LocalizedString}
|
||||||
|
*/
|
||||||
|
export const copy_name_and_download_link: ((inputs?: Copy_Name_And_Download_LinkInputs, options?: {
|
||||||
|
locale?: "en" | "zh";
|
||||||
|
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Copy_Name_And_Download_LinkInputs, {
|
||||||
|
locale?: "en" | "zh";
|
||||||
|
}, {}>;
|
||||||
|
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||||
|
export type Copy_Name_And_Download_LinkInputs = {};
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||||
|
|
||||||
|
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||||
|
|
||||||
|
/** @typedef {{}} Copy_Name_And_Download_LinkInputs */
|
||||||
|
|
||||||
|
const en_copy_name_and_download_link = /** @type {(inputs: Copy_Name_And_Download_LinkInputs) => LocalizedString} */ () => {
|
||||||
|
return /** @type {LocalizedString} */ (`Copy name and download link`)
|
||||||
|
};
|
||||||
|
|
||||||
|
const zh_copy_name_and_download_link = /** @type {(inputs: Copy_Name_And_Download_LinkInputs) => LocalizedString} */ () => {
|
||||||
|
return /** @type {LocalizedString} */ (`复制名称和下载链接`)
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* | output |
|
||||||
|
* | --- |
|
||||||
|
* | "Copy name and download link" |
|
||||||
|
*
|
||||||
|
* @param {Copy_Name_And_Download_LinkInputs} inputs
|
||||||
|
* @param {{ locale?: "en" | "zh" }} options
|
||||||
|
* @returns {LocalizedString}
|
||||||
|
*/
|
||||||
|
export const copy_name_and_download_link = /** @type {((inputs?: Copy_Name_And_Download_LinkInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Copy_Name_And_Download_LinkInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||||
|
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||||
|
if (locale === "en") return en_copy_name_and_download_link(inputs)
|
||||||
|
return zh_copy_name_and_download_link(inputs)
|
||||||
|
});
|
||||||
@@ -3,6 +3,7 @@ import { client } from '@/ui/api/client'
|
|||||||
import { FolderTree } from '@/ui/components/folder-tree'
|
import { FolderTree } from '@/ui/components/folder-tree'
|
||||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||||
import { m } from '@/ui/paraglide/messages.js'
|
import { m } from '@/ui/paraglide/messages.js'
|
||||||
|
import { copyToClipboard } from '@/ui/lib/clipboard'
|
||||||
import { Switch } from '@/ui/components/ui/switch'
|
import { Switch } from '@/ui/components/ui/switch'
|
||||||
import { Button } from '@/ui/components/ui/button'
|
import { Button } from '@/ui/components/ui/button'
|
||||||
import {
|
import {
|
||||||
@@ -117,10 +118,12 @@ function SharesPage() {
|
|||||||
return <ProjectFolderSkeleton />
|
return <ProjectFolderSkeleton />
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCopyLink = (shareId: string) => {
|
const handleCopyLink = async (shareId: string) => {
|
||||||
const url = `${window.location.origin}/share/${shareId}`
|
const url = `${window.location.origin}/share/${shareId}`
|
||||||
navigator.clipboard.writeText(url)
|
const ok = await copyToClipboard(url)
|
||||||
toast.success(m.link_copied())
|
if (ok) {
|
||||||
|
toast.success(m.link_copied())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -259,4 +259,44 @@ describe('useChatbotStore', () => {
|
|||||||
expect(finalState.messages[0].id).toBe('context-display-ulid')
|
expect(finalState.messages[0].id).toBe('context-display-ulid')
|
||||||
expect(finalState.messages[1].id).toBe('user-msg-ulid')
|
expect(finalState.messages[1].id).toBe('user-msg-ulid')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('should invoke onAssetMutation callback when asset creation tool result arrives', async () => {
|
||||||
|
const mockEvents = [
|
||||||
|
'data: {"type":"session","sessionId":"sess-123"}\n\n',
|
||||||
|
'data: {"type":"entry","entry":{"id":"user-msg-ulid","role":"user","content":[{"type":"text","text":"create a file"}],"timestamp":123}}\n\n',
|
||||||
|
'data: {"type":"entry","entry":{"id":"tool-res-ulid","role":"toolResult","toolName":"create_file","isError":false,"content":"File created","timestamp":124}}\n\n',
|
||||||
|
'data: {"type":"done","status":"completed"}\n\n',
|
||||||
|
]
|
||||||
|
|
||||||
|
let eventIdx = 0
|
||||||
|
const mockReader = {
|
||||||
|
read: vi.fn(async () => {
|
||||||
|
if (eventIdx < mockEvents.length) {
|
||||||
|
const value = new TextEncoder().encode(mockEvents[eventIdx++])
|
||||||
|
return { done: false, value }
|
||||||
|
}
|
||||||
|
return { done: true, value: undefined }
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
const mockResponse = {
|
||||||
|
ok: true,
|
||||||
|
headers: {
|
||||||
|
get: vi.fn(() => 'sess-123'),
|
||||||
|
},
|
||||||
|
body: {
|
||||||
|
getReader: () => mockReader,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
|
||||||
|
|
||||||
|
const onAssetMutation = vi.fn()
|
||||||
|
await useChatbotStore
|
||||||
|
.getState()
|
||||||
|
.sendMessage('team-123', 'create a file', 'proj-123', undefined, onAssetMutation)
|
||||||
|
|
||||||
|
expect(onAssetMutation).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ interface ChatbotState {
|
|||||||
text: string,
|
text: string,
|
||||||
projectId: string,
|
projectId: string,
|
||||||
contextAssetId?: string,
|
contextAssetId?: string,
|
||||||
|
onAssetMutation?: () => void,
|
||||||
) => Promise<void>
|
) => Promise<void>
|
||||||
abortActiveSession: (teamId: string) => Promise<void>
|
abortActiveSession: (teamId: string) => Promise<void>
|
||||||
}
|
}
|
||||||
@@ -151,7 +152,7 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
sendMessage: async (teamId, text, projectId, contextAssetId) => {
|
sendMessage: async (teamId, text, projectId, contextAssetId, onAssetMutation) => {
|
||||||
const state = useChatbotStore.getState()
|
const state = useChatbotStore.getState()
|
||||||
if (state.isStreaming) return
|
if (state.isStreaming) return
|
||||||
|
|
||||||
@@ -251,6 +252,16 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
|||||||
}
|
}
|
||||||
} else if (data.type === 'entry') {
|
} else if (data.type === 'entry') {
|
||||||
const entry = data.entry as ChatMessage
|
const entry = data.entry as ChatMessage
|
||||||
|
const entryObj = entry as unknown as Record<string, unknown>
|
||||||
|
if (
|
||||||
|
entryObj.role === 'toolResult' &&
|
||||||
|
typeof entryObj.toolName === 'string' &&
|
||||||
|
['create_file', 'create_folder', 'create_version'].includes(entryObj.toolName) &&
|
||||||
|
!entryObj.isError
|
||||||
|
) {
|
||||||
|
onAssetMutation?.()
|
||||||
|
}
|
||||||
|
|
||||||
set((s) => {
|
set((s) => {
|
||||||
const isExisting = s.messages.some((m) => m.id === entry.id)
|
const isExisting = s.messages.some((m) => m.id === entry.id)
|
||||||
// Replace temp/optimistic message when the real counterpart streams back
|
// Replace temp/optimistic message when the real counterpart streams back
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ export const useUiStore = create<UiState>()(
|
|||||||
setFileViewLeftSidebarCollapsed: (collapsed) =>
|
setFileViewLeftSidebarCollapsed: (collapsed) =>
|
||||||
set({ fileViewLeftSidebarCollapsed: collapsed }),
|
set({ fileViewLeftSidebarCollapsed: collapsed }),
|
||||||
|
|
||||||
fileViewRightSidebarCollapsed: true,
|
fileViewRightSidebarCollapsed: false,
|
||||||
setFileViewRightSidebarCollapsed: (collapsed) =>
|
setFileViewRightSidebarCollapsed: (collapsed) =>
|
||||||
set({ fileViewRightSidebarCollapsed: collapsed }),
|
set({ fileViewRightSidebarCollapsed: collapsed }),
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
export const APP_VERSION = '0.2.2'
|
export const APP_VERSION = '0.3.0'
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shumai/workflow-core",
|
"name": "@shumai/workflow-core",
|
||||||
"version": "0.2.2",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
|
|||||||
Reference in New Issue
Block a user