Compare commits

...
66 Commits
Author SHA1 Message Date
yiling d0d29b34ed Release v0.3.0 2026-07-28 18:56:55 +08:00
Yiling-J 219961755c Merge pull request #233 from shumaiOne/feat/sandbox-weaker-nested-env
feat(agent): support ENABLE_WEAKER_NESTED_SANDBOX environment variable
2026-07-28 18:33:20 +08:00
yiling bca2d26e1d feat(agent): support ENABLE_WEAKER_NESTED_SANDBOX environment variable 2026-07-28 18:28:16 +08:00
yiling 4bd166d7b9 try fixing docker compose sandbox 2026-07-28 16:58:27 +08:00
yiling 51208d3ff0 chore(deps): update @anthropic-ai/sandbox-runtime to 0.0.66 2026-07-28 16:13:40 +08:00
yiling ae5c58d48c try fixing docker compose sandbox 2026-07-28 15:47:03 +08:00
Yiling-J eb73ba7d6a Merge pull request #232 from shumaiOne/fix/analyze-image-s3-mime-type
fix(agent): resolve S3 MIME type detection and prompt parameter in image analysis
2026-07-28 14:40:10 +08:00
yiling 3727879c19 fix(agent): resolve S3 MIME type detection and prompt parameter in image analysis 2026-07-28 14:28:41 +08:00
Yiling-J f46fa31262 Merge pull request #231 from shumaiOne/feat/ci-docker-compose-healthcheck
ci(workflow): add docker compose deployment verification job
2026-07-28 14:12:40 +08:00
yiling 08552c229d ci(workflow): add docker compose deployment verification job 2026-07-28 14:03:48 +08:00
Yiling-J 9dfda1d446 Merge pull request #230 from shumaiOne/fix/sharp-docker-external
fix sharp version mismatch bug
2026-07-28 13:59:43 +08:00
yiling e214036308 fix sharp version mismatch bug 2026-07-28 13:58:52 +08:00
Yiling-J 9da6818adc Merge pull request #229 from shumaiOne/feat/session-storage-refactor
feat(agent): refactor database session storage to normalized DAG entries and lazy thread sync
2026-07-28 13:18:16 +08:00
yiling ff113906d7 refactor(db): strictly type PiSessionEntryData in prisma-json-types and clean up casts 2026-07-28 12:55:38 +08:00
yiling 56421cd562 feat(agent): implement dynamic in-memory thread tagging for session context entries 2026-07-28 11:51:25 +08:00
yiling 4e2694e2d9 feat(agent): refactor database session storage to normalized DAG entries and lazy thread sync 2026-07-28 11:21:31 +08:00
yiling b876af464e feat(file-browser): rename menu item to Copy name and download link 2026-07-27 22:17:07 +08:00
Yiling-J 216538fcfa Merge pull request #227 from shumaiOne/refactor/remove-implicit-agent-mention
refactor(agent): remove implicit agent mention trigger in comment threads
2026-07-27 14:57:29 +08:00
yiling bb71e6bb2a refactor(agent): remove implicit agent mention trigger in comment threads 2026-07-27 14:49:41 +08:00
Yiling-J 9bfa174348 Merge pull request #226 from shumaiOne/feat/inject-user-name-role-chat
feat(agent): inject user name and role into chat context
2026-07-27 14:38:04 +08:00
yiling cd3c7f3641 feat(agent): inject user name and role into chat context 2026-07-27 11:24:48 +08:00
Yiling-J b8345f7c46 Merge pull request #225 from shumaiOne/feat/copy-name-and-path
feat(file-browser): add copy name and path option to context menu
2026-07-27 10:35:51 +08:00
yiling d364e13eb7 fix(file-browser): reuse download-link API url for copy name and path 2026-07-27 10:26:42 +08:00
yiling f429873362 feat(file-browser): add copy name and path option to context menu 2026-07-27 10:23:22 +08:00
Yiling-J d81fc09b35 Change demo video link in README_CN.md
Updated demo video link in README_CN.md.
2026-07-27 09:45:23 +08:00
Yiling-J 6dec8e9786 Update demo video link in README 2026-07-27 09:44:57 +08:00
Yiling-J e1ec56147e Change demo video link in README_CN.md
Updated demo video link in README_CN.md.
2026-07-26 20:51:25 +08:00
Yiling-J 972b1c7458 Update demo video link in README 2026-07-26 20:50:37 +08:00
Yiling-J 07396725aa Revise features and introduce AI Agent functionalities
Updated features section and added AI capabilities for Shumai.
2026-07-26 20:46:43 +08:00
Yiling-J 869bb873cf Update demo video link and media processing details
Updated demo video link and added media processing notes.
2026-07-26 20:35:00 +08:00
Yiling-J fd7b4ca331 Merge pull request #224 from shumaiOne/fix/database-session-storage-p1-bugs
fix(agent): ensure atomic appendEntry and persist leaf entries in DatabaseSessionStorage
2026-07-26 11:25:09 +08:00
yiling c4bba31f20 fix(agent): ensure atomic appendEntry and persist leaf entries in DatabaseSessionStorage 2026-07-26 11:17:59 +08:00
yiling 72654e84b2 Release v0.2.3 2026-07-25 11:49:11 +08:00
Yiling-J cec3821d00 Merge pull request #223 from shumaiOne/test/e2e-video-screenshot-annotation
fix(transcode): handle timestamp rounding tolerance for screenshot annotations
2026-07-25 11:30:18 +08:00
yiling dc3dbcb73e fix(transcode): remove debug logs, keep clean epsilon bugfix 2026-07-25 11:21:45 +08:00
yiling 6226090fd1 fix(e2e): add sharp dependency to packages/e2e 2026-07-25 11:17:32 +08:00
yiling d052c56d39 fix(transcode): handle timestamp rounding tolerance for screenshot annotations 2026-07-25 10:46:20 +08:00
Yiling-J bd13fa7774 Merge pull request #222 from shumaiOne/refactor/split-transcode-workflow-e2e-tests
refactor(e2e): split transcode workflow E2E tests into per-workflow test files
2026-07-25 09:57:36 +08:00
yiling 5e462cc7b1 refactor(e2e): split transcode workflow E2E tests into per-workflow test files 2026-07-25 09:47:20 +08:00
Yiling-J 73c11af9a3 Merge pull request #221 from shumaiOne/fix/file-list-selection-and-dnd-space
fix(webui): fix space key drag overlay and shift range selection for version stacks
2026-07-24 21:13:47 +08:00
yiling adb73b56a2 fix(webui): prevent white focus outline on folder and file cards during selection 2026-07-24 20:57:28 +08:00
yiling e5dcf02b26 fix(webui): fix space key drag overlay and shift range selection for version stacks 2026-07-24 20:47:45 +08:00
Yiling-J 684f88a406 Merge pull request #220 from shumaiOne/fix/refresh-asset-on-agent-tool
fix(webui): refresh file list and detail when agent executes asset creation tools
2026-07-24 20:26:05 +08:00
yiling 8ec970e2bf fix(webui): refresh file list and detail when agent executes asset creation tools 2026-07-24 20:16:58 +08:00
Yiling-J 3eb7894df9 Merge pull request #219 from shumaiOne/fix/default-file-view-right-sidebar-visible
fix(webui): show right sidebar by default on file detail page
2026-07-24 16:18:48 +08:00
yiling 464167ec83 fix(webui): show right sidebar by default on file detail page 2026-07-24 16:16:50 +08:00
yiling dc8c898dae Release v0.2.2 2026-07-23 20:35:22 +08:00
Yiling-J ecc382af61 Merge pull request #218 from shumaiOne/fix/upload-task-completion-status
fix(webui): invalidate upload tasks query when upload task starts and completes
2026-07-23 20:25:44 +08:00
yiling 78dec7626b fix(webui): invalidate upload tasks query when upload task starts and completes 2026-07-23 20:18:37 +08:00
Yiling-J f87033bd3d Merge pull request #217 from shumaiOne/feat/psd-imagemagick-support
feat(transcode): add PSD support via ImageMagick and enforce sRGB conversion
2026-07-23 17:02:11 +08:00
yiling d1b0f3b64f docs: update Windows system requirements in README to include ImageMagick 2026-07-23 16:48:34 +08:00
yiling 8cdbc403db test(e2e): add PSD transcode workflow E2E test 2026-07-23 16:44:56 +08:00
yiling 90adc496dd fix(transcode): update APT package name from imagemagick-7.q16 to imagemagick 2026-07-23 16:34:01 +08:00
yiling 8d1c51abca feat(transcode): add PSD support via ImageMagick and enforce sRGB conversion 2026-07-23 16:19:25 +08:00
Yiling-J 21de21902e Merge pull request #215 from shumaiOne/feat/ai-token-usage-tracking
feat(ai-usage): add team and member token usage tracking and APIs
2026-07-23 15:26:32 +08:00
Yiling-J 330a0b99a9 Merge pull request #216 from shumaiOne/feat/webui-ai-token-usage
feat(webui): integrate AI usage API into dashboard page
2026-07-23 15:10:58 +08:00
yiling df013aa4bb feat(webui): add AI usage dashboard for team and member token tracking 2026-07-23 15:03:09 +08:00
yiling 2c04c97a02 refactor(ai-usage): use Prisma.PrismaClientKnownRequestError for P2002 handling 2026-07-23 11:35:18 +08:00
yiling f6c0a41151 fix(ai-usage): resolve code review feedback for concurrency upsert and timeframe window 2026-07-23 11:29:11 +08:00
yiling f93c8ea524 refactor(agent): invoke harness.subscribe directly without typeof check 2026-07-23 11:11:48 +08:00
yiling 783daa6d3f fix(ai-usage): align since date with top-of-hour bucket boundaries 2026-07-23 11:08:35 +08:00
yiling 1c44e5aff7 feat(ai-usage): add team and member token usage tracking and APIs 2026-07-23 11:02:54 +08:00
Yiling-J 2552d68b98 Merge pull request #214 from shumaiOne/fix/search-result-row-overflow
fix(webui): prevent horizontal overflow in search dialog result rows
2026-07-22 21:18:06 +08:00
yiling 1f714af366 fix(webui): prevent horizontal overflow in search dialog result rows 2026-07-22 21:12:45 +08:00
Yiling-J f0ca7c180b Merge pull request #213 from shumaiOne/fix/sql-query-builder-bugs
fix(search): fix buildSqlCondition date range, numeric metadata, and string parsing bugs
2026-07-22 20:43:26 +08:00
yiling 8aadaa70bf fix(search): fix buildSqlCondition date range, numeric metadata, and string parsing bugs 2026-07-22 20:33:33 +08:00
151 changed files with 8310 additions and 1357 deletions
+43 -2
View File
@@ -32,7 +32,7 @@ jobs:
- name: Install system dependencies - name: Install system dependencies
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils imagemagick
- name: Lint - name: Lint
run: bun run lint run: bun run lint
@@ -157,7 +157,48 @@ jobs:
- name: Install system dependencies - name: Install system dependencies
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils imagemagick
- 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
+1 -1
View File
@@ -48,7 +48,7 @@ jobs:
- name: Install system dependencies - name: Install system dependencies
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev fd-find sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils imagemagick libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev fd-find
- name: Install dependencies - name: Install dependencies
run: bun install run: bun install
+1
View File
@@ -50,6 +50,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
bubblewrap \ bubblewrap \
gosu \ gosu \
poppler-utils \ poppler-utils \
imagemagick \
fonts-noto-cjk \ fonts-noto-cjk \
&& apt-get clean \ && apt-get clean \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
+33 -19
View File
@@ -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:
@@ -126,23 +137,24 @@ Shumai requires the following system packages on Linux:
- **`ffmpeg`** – Used for media transcoding and metadata extraction. - **`ffmpeg`** – Used for media transcoding and metadata extraction.
- **`poppler`** (`poppler-utils`) – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`). - **`poppler`** (`poppler-utils`) – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`).
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
- **`bubblewrap`**, **`socat`**, and **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`) for process isolation, networking, and workspace search. - **`bubblewrap`**, **`socat`**, and **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`) for process isolation, networking, and workspace search.
Install all required packages with one command: Install all required packages with one command:
> Ubuntu/Debian > Ubuntu/Debian
```bash ```bash
sudo apt install -y ffmpeg poppler-utils bubblewrap socat ripgrep sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep
``` ```
> Fedora > Fedora
```bash ```bash
sudo dnf install -y ffmpeg poppler-utils bubblewrap socat ripgrep sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep
``` ```
> Arch Linux > Arch Linux
```bash ```bash
sudo pacman -S --noconfirm ffmpeg poppler bubblewrap socat ripgrep sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep
``` ```
> [!NOTE] > [!NOTE]
@@ -164,12 +176,13 @@ Shumai requires:
- **`ffmpeg`** – Used for media transcoding and metadata extraction. - **`ffmpeg`** – Used for media transcoding and metadata extraction.
- **`poppler`** – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`). - **`poppler`** – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`).
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
- **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`). - **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`).
Install the required packages with Homebrew: Install the required packages with Homebrew:
```bash ```bash
brew install ffmpeg poppler ripgrep brew install ffmpeg poppler imagemagick ripgrep
``` ```
--- ---
@@ -190,17 +203,18 @@ brew install ffmpeg poppler ripgrep
Shumai requires: Shumai requires:
- **`ffmpeg`** – Used for media transcoding and metadata extraction. - **`ffmpeg`** – Used for media transcoding and metadata extraction.
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
Install `ffmpeg` using your preferred package manager: Install required packages using your preferred package manager:
**winget** **winget**
```powershell ```powershell
winget install Gyan.FFmpeg winget install Gyan.FFmpeg ImageMagick.ImageMagick
``` ```
**Chocolatey** **Chocolatey**
```powershell ```powershell
choco install ffmpeg choco install ffmpeg imagemagick
``` ```
#### Step 4: Install Shumai globally #### Step 4: Install Shumai globally
+30 -20
View File
@@ -15,22 +15,29 @@
![Shumai 应用截图](docs/screenshot.webp) ![Shumai 应用截图](docs/screenshot.webp)
## 功能特性 ## 功能
- **兼容 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 封面图,作为文件列表中的预览图。此外:
@@ -140,23 +147,24 @@ mkdir shumai && cd shumai
- **`ffmpeg`** —— 用于媒体转码和元数据提取。 - **`ffmpeg`** —— 用于媒体转码和元数据提取。
- **`poppler`** (`poppler-utils`) —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。 - **`poppler`** (`poppler-utils`) —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
- **`bubblewrap`**、**`socat`** 和 **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需,用于进程隔离、网络通信和工作区搜索。 - **`bubblewrap`**、**`socat`** 和 **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需,用于进程隔离、网络通信和工作区搜索。
可以使用以下命令一次性安装所有依赖: 可以使用以下命令一次性安装所有依赖:
> Ubuntu/Debian > Ubuntu/Debian
```bash ```bash
sudo apt install -y ffmpeg poppler-utils bubblewrap socat ripgrep sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep
``` ```
> Fedora > Fedora
```bash ```bash
sudo dnf install -y ffmpeg poppler-utils bubblewrap socat ripgrep sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep
``` ```
> Arch Linux > Arch Linux
```bash ```bash
sudo pacman -S --noconfirm ffmpeg poppler bubblewrap socat ripgrep sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep
``` ```
> [!NOTE] > [!NOTE]
@@ -178,12 +186,13 @@ sudo pacman -S --noconfirm ffmpeg poppler bubblewrap socat ripgrep
- **`ffmpeg`** —— 用于媒体转码和元数据提取。 - **`ffmpeg`** —— 用于媒体转码和元数据提取。
- **`poppler`** —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。 - **`poppler`** —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
- **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需。 - **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需。
使用 Homebrew 安装所需依赖: 使用 Homebrew 安装所需依赖:
```bash ```bash
brew install ffmpeg poppler ripgrep brew install ffmpeg poppler imagemagick ripgrep
``` ```
--- ---
@@ -204,17 +213,18 @@ brew install ffmpeg poppler ripgrep
在 Windows 上运行 Shumai 需要: 在 Windows 上运行 Shumai 需要:
- **`ffmpeg`** —— 用于媒体转码和元数据提取。 - **`ffmpeg`** —— 用于媒体转码和元数据提取。
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
使用你偏好的包管理器安装 `ffmpeg`: 使用你偏好的包管理器安装所需依赖:
**winget** **winget**
```powershell ```powershell
winget install Gyan.FFmpeg winget install Gyan.FFmpeg ImageMagick.ImageMagick
``` ```
**Chocolatey** **Chocolatey**
```powershell ```powershell
choco install ffmpeg choco install ffmpeg imagemagick
``` ```
#### 第四步:全局安装 Shumai #### 第四步:全局安装 Shumai
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/agent-app", "name": "@shumai/agent-app",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"bin": { "bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/cli", "name": "@shumai/cli",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"bin": { "bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/transcode-app", "name": "@shumai/transcode-app",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"bin": { "bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/web-app", "name": "@shumai/web-app",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"dependencies": { "dependencies": {
+19 -20
View File
@@ -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
+8
View File
@@ -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
+6
View File
@@ -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
View File
@@ -1,6 +1,6 @@
{ {
"name": "shumai", "name": "shumai",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"repository": { "repository": {
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "@shumai/agent", "name": "@shumai/agent",
"version": "0.2.1", "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",
+206 -4
View File
@@ -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'
@@ -56,6 +57,7 @@ describe('Agent Activities', () => {
it('should call agentChatActivity and prompt the harness', async () => { it('should call agentChatActivity and prompt the harness', async () => {
const mockHarness = { const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockResolvedValue({ prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: 'AI response' }], content: [{ type: 'text', text: 'AI response' }],
usage: { input: 10, output: 20 }, usage: { input: 10, output: 20 },
@@ -95,6 +97,84 @@ describe('Agent Activities', () => {
expect(piAgent.createAgentSession).toHaveBeenCalled() expect(piAgent.createAgentSession).toHaveBeenCalled()
}) })
it('should subscribe to harness events and record usage for assistant message_end events', async () => {
const { aiUsageService } = await import('@shumai/core/src/ai-usage/ai-usage')
const spyRecordUsage = vi.spyOn(aiUsageService, 'recordUsage').mockResolvedValue()
let subscribeListener!: (event: unknown) => Promise<void>
const mockHarness = {
subscribe: vi.fn().mockImplementation((listener) => {
subscribeListener = listener
}),
prompt: vi.fn().mockImplementation(async () => {
// Trigger assistant message end event during turn
if (subscribeListener) {
await subscribeListener({
type: 'message_end',
message: {
role: 'assistant',
usage: {
input: 150,
output: 75,
cacheRead: 25,
totalTokens: 225,
cost: { total: 0.0015 },
},
},
})
}
return {
content: [{ type: 'text', text: 'Subscribed response' }],
usage: { input: 150, output: 75 },
}
}),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
const context = {
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
const res = await agentChatActivity({
teamId: 'team123',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
userId: 'user123',
context,
})
expect(res.text).toBe('Subscribed response')
expect(res.usage.inputTokens).toBe(150)
expect(res.usage.outputTokens).toBe(75)
expect(res.usage.cacheReadTokens).toBe(25)
expect(res.usage.cost).toBe(0.0015)
expect(spyRecordUsage).toHaveBeenCalledWith({
teamId: 'team123',
userId: 'user123',
inputTokens: 150,
outputTokens: 75,
cacheReadTokens: 25,
totalTokens: 225,
cost: 0.0015,
})
})
it('should register local cancellation handler and call harness.abort when cancelled in local mode', async () => { it('should register local cancellation handler and call harness.abort when cancelled in local mode', async () => {
let resolvePrompt!: (value: { let resolvePrompt!: (value: {
content: Array<{ type: string; text: string } | { type: string }> content: Array<{ type: string; text: string } | { type: string }>
@@ -107,6 +187,7 @@ describe('Agent Activities', () => {
}) })
const mockHarness = { const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockReturnValue(promptPromise), prompt: vi.fn().mockReturnValue(promptPromise),
abort: vi.fn(), abort: vi.fn(),
} }
@@ -174,6 +255,7 @@ describe('Agent Activities', () => {
}) })
const mockHarness = { const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockReturnValue(promptPromise), prompt: vi.fn().mockReturnValue(promptPromise),
abort: vi.fn(), abort: vi.fn(),
} }
@@ -234,6 +316,7 @@ describe('Agent Activities', () => {
it('should include error message in text when stopReason is error', async () => { it('should include error message in text when stopReason is error', async () => {
const mockHarness = { const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockResolvedValue({ prompt: vi.fn().mockResolvedValue({
content: [], content: [],
usage: { input: 0, output: 0 }, usage: { input: 0, output: 0 },
@@ -274,6 +357,7 @@ describe('Agent Activities', () => {
it('should pass thinkingLevel from agent config to createAgentSession', async () => { it('should pass thinkingLevel from agent config to createAgentSession', async () => {
const mockHarness = { const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockResolvedValue({ prompt: vi.fn().mockResolvedValue({
content: [], content: [],
usage: { input: 0, output: 0 }, usage: { input: 0, output: 0 },
@@ -322,6 +406,7 @@ describe('Agent Activities', () => {
it('should call autofillAiActivity and run autofill tool', async () => { it('should call autofillAiActivity and run autofill tool', async () => {
const mockHarness = { const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockResolvedValue({ prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: 'Captured' }], content: [{ type: 'text', text: 'Captured' }],
usage: { input: 5, output: 5 }, usage: { input: 5, output: 5 },
@@ -461,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', () => {
@@ -962,6 +1163,7 @@ describe('Agent Database Activities Integration', () => {
}) })
const mockHarness = { const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockResolvedValue({ prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: ' "Summarized Chat Title" ' }], content: [{ type: 'text', text: ' "Summarized Chat Title" ' }],
}), }),
+275 -51
View File
@@ -25,11 +25,15 @@ import {
type DbProviderInfo, type DbProviderInfo,
} from '../index' } from '../index'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import { UpdateAssetMetadataRequest } from '@shumai/dtos' import { UpdateAssetMetadataRequest } from '@shumai/dtos'
export interface Usage { export interface Usage {
inputTokens: number inputTokens: number
outputTokens: number outputTokens: number
cacheReadTokens: number
totalTokens: number
cost: number
model: string model: string
} }
@@ -209,8 +213,56 @@ If you need to create files in the local filesystem (for example, a temporary fi
} as unknown as SessionTreeEntry) } as unknown as SessionTreeEntry)
} }
let totalInputTokens = 0
let totalOutputTokens = 0
let totalCacheReadTokens = 0
let grandTotalTokens = 0
let totalCost = 0
harness.subscribe(async (event) => {
if (event.type === 'message_end' && event.message.role === 'assistant') {
const assistantMsg = event.message
const u = assistantMsg.usage
if (u) {
const inputTokens = u.input || 0
const outputTokens = u.output || 0
const cacheReadTokens = u.cacheRead || 0
const totalTokens = u.totalTokens || inputTokens + outputTokens
const cost = u.cost?.total || 0
totalInputTokens += inputTokens
totalOutputTokens += outputTokens
totalCacheReadTokens += cacheReadTokens
grandTotalTokens += totalTokens
totalCost += cost
try {
await aiUsageService.recordUsage({
teamId: params.teamId,
userId: params.userId,
inputTokens,
outputTokens,
cacheReadTokens,
totalTokens,
cost,
})
} catch (err) {
logger.error({ err }, 'Failed to record AI usage')
}
}
}
})
const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass }) const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass })
if (totalInputTokens === 0 && totalOutputTokens === 0 && assistantMessage.usage) {
totalInputTokens = assistantMessage.usage.input || 0
totalOutputTokens = assistantMessage.usage.output || 0
totalCacheReadTokens = assistantMessage.usage.cacheRead || 0
grandTotalTokens = assistantMessage.usage.totalTokens || totalInputTokens + totalOutputTokens
totalCost = assistantMessage.usage.cost?.total || 0
}
const sessionEntries = await session.getEntries() const sessionEntries = await session.getEntries()
sessionEntries.forEach((entry) => { sessionEntries.forEach((entry) => {
if (entry.type === 'message') { if (entry.type === 'message') {
@@ -243,8 +295,11 @@ If you need to create files in the local filesystem (for example, a temporary fi
const usage: Usage = { const usage: Usage = {
model: modelId, model: modelId,
inputTokens: assistantMessage.usage?.input || 0, inputTokens: totalInputTokens,
outputTokens: assistantMessage.usage?.output || 0, outputTokens: totalOutputTokens,
cacheReadTokens: totalCacheReadTokens,
totalTokens: grandTotalTokens,
cost: totalCost,
} }
const storage = session.getStorage() const storage = session.getStorage()
@@ -278,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,
@@ -393,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
@@ -413,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>()
@@ -476,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 || ''
@@ -492,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()
})
})
}) })
+141 -48
View File
@@ -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)
+75
View File
@@ -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()
})
})
+28 -19
View File
@@ -7,21 +7,22 @@ import {
} from '@earendil-works/pi-agent-core' } from '@earendil-works/pi-agent-core'
import { NodeExecutionEnv } from '@earendil-works/pi-agent-core/node' import { NodeExecutionEnv } from '@earendil-works/pi-agent-core/node'
import { getModel } from '@earendil-works/pi-ai/compat' import { getModel } from '@earendil-works/pi-ai/compat'
import { agentService } from '@shumai/core/src/agent/agent'
import { prisma } from '@shumai/db'
import { Type, type TSchema } from '@sinclair/typebox' import { Type, type TSchema } from '@sinclair/typebox'
import * as fs from 'fs' import * as fs from 'fs'
import * as path from 'path' import * as path from 'path'
import { prisma } from '@shumai/db'
import { agentService } from '@shumai/core/src/agent/agent'
import { DatabaseSessionStorage } from './database-session-storage' import { DatabaseSessionStorage } from './database-session-storage'
import { createAnalyzeImageTool } from './tools/analyze-image' import { createAnalyzeImageTool } from './tools/analyze-image'
import { createScreenshotTool } from './tools/screenshot'
import { createReadPdfPagesTool } from './tools/read-pdf-pages'
import { createCreateFileTool } from './tools/create-file' import { createCreateFileTool } from './tools/create-file'
import { createCreateFolderTool } from './tools/create-folder' import { createCreateFolderTool } from './tools/create-folder'
import { createCreateVersionTool } from './tools/create-version' 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 { 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'
export interface DbModelInfo { export interface DbModelInfo {
modelId: string modelId: string
@@ -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({
@@ -380,15 +389,15 @@ export function formatSkillsForPrompt(
return lines.join('\n') return lines.join('\n')
} }
import { registerWorkflow, registerActivities } from '@shumai/workflow-core'
import { WorkflowTaskType } from '@shumai/db' import { WorkflowTaskType } from '@shumai/db'
import { agentEmbeddingMedia } from './workflows/agent-embedding' import { registerActivities, registerWorkflow } from '@shumai/workflow-core'
import { queryEmbeddingForSearch } from './workflows/query-embedding-for-search'
import { agentAutofillMedia } from './workflows/agent-autofill'
import { agentChat } from './workflows/agent-chat'
import { agentToolCall } from './workflows/agent-tool-call'
import * as agentActivities from './activities/agent' import * as agentActivities from './activities/agent'
import * as aiActivities from './activities/ai' import * as aiActivities from './activities/ai'
import { agentAutofillMedia } from './workflows/agent-autofill'
import { agentChat } from './workflows/agent-chat'
import { agentEmbeddingMedia } from './workflows/agent-embedding'
import { agentToolCall } from './workflows/agent-tool-call'
import { queryEmbeddingForSearch } from './workflows/query-embedding-for-search'
export function initAgentWorkflows() { export function initAgentWorkflows() {
registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia) registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia)
@@ -401,19 +410,19 @@ export function initAgentWorkflows() {
registerActivities(aiActivities) registerActivities(aiActivities)
} }
export * from './database-session-storage'
export * from './activities/agent' export * from './activities/agent'
export { export {
extractAiMetadataActivity,
generateEmbeddingActivity,
generateImageEmbeddingActivity,
generateTextEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
type ExtractAiMetadataParams,
type GeneratedEmbedding, type GeneratedEmbedding,
type GenerateEmbeddingParams, type GenerateEmbeddingParams,
generateEmbeddingActivity,
type GenerateTextEmbeddingParams, type GenerateTextEmbeddingParams,
generateTextEmbeddingActivity,
type ExtractAiMetadataParams,
extractAiMetadataActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
} from './activities/ai' } from './activities/ai'
export * from './database-session-storage'
export * from './workflows/agent-autofill' export * from './workflows/agent-autofill'
export * from './workflows/agent-chat' export * from './workflows/agent-chat'
export * from './workflows/agent-embedding' export * from './workflows/agent-embedding'
+4 -1
View File
@@ -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,
}, },
] ]
+3 -1
View File
@@ -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')
})
})
+53
View File
@@ -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 },
}
},
})
+3 -1
View File
@@ -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
+38 -54
View File
@@ -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'),
}),
)
})
}) })
+21 -14
View File
@@ -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 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/api", "name": "@shumai/api",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+68
View File
@@ -37,6 +37,13 @@ vi.mock('@shumai/core/src/user/api-token', () => ({
}, },
})) }))
vi.mock('@shumai/core/src/ai-usage/ai-usage', () => ({
aiUsageService: {
recordUsage: vi.fn(),
getTeamUsageStats: vi.fn(),
},
}))
describe('team api', () => { describe('team api', () => {
const app = new Hono().use('*', authMiddleware).route('/', teamRoute) const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -403,5 +410,66 @@ describe('team api', () => {
expect(data).toEqual({ success: true }) expect(data).toEqual({ success: true })
expect(apiTokenService.deleteToken).toHaveBeenCalledWith('user1', 'token1') expect(apiTokenService.deleteToken).toHaveBeenCalledWith('user1', 'token1')
}) })
it('GET /teams/:teamId/ai-usage returns team usage stats for owner', async () => {
const { aiUsageService } = await import('@shumai/core/src/ai-usage/ai-usage')
vi.mocked(aiUsageService.getTeamUsageStats).mockResolvedValue({
timeframe: '30d',
team: {
inputTokens: 1000,
outputTokens: 500,
cacheReadTokens: 200,
totalTokens: 1500,
cost: 0.005,
},
})
const res = await app.request('/teams/t1/ai-usage?timeframe=30d')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.team.totalTokens).toBe(1500)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
}),
)
expect(aiUsageService.getTeamUsageStats).toHaveBeenCalledWith({
teamId: 't1',
timeframe: '30d',
userId: undefined,
})
})
it('GET /teams/:teamId/ai-usage?userId=user1 returns specific member usage stats', async () => {
const { aiUsageService } = await import('@shumai/core/src/ai-usage/ai-usage')
vi.mocked(aiUsageService.getTeamUsageStats).mockResolvedValue({
timeframe: '7d',
member: {
userId: 'user1',
userName: 'Test User',
userEmail: 'user1@example.com',
role: 'owner',
inputTokens: 400,
outputTokens: 200,
cacheReadTokens: 50,
totalTokens: 600,
cost: 0.002,
},
})
const res = await app.request('/teams/t1/ai-usage?timeframe=7d&userId=user1')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.member.userId).toBe('user1')
expect(aiUsageService.getTeamUsageStats).toHaveBeenCalledWith({
teamId: 't1',
timeframe: '7d',
userId: 'user1',
})
})
}) })
}) })
+22 -1
View File
@@ -15,8 +15,9 @@ import {
updateTeamMemberRoleRequestSchema, updateTeamMemberRoleRequestSchema,
createApiTokenRequestSchema, createApiTokenRequestSchema,
} from '@shumai/dtos' } from '@shumai/dtos'
import { updateUserMetadataRequestSchema } from '@shumai/dtos' import { updateUserMetadataRequestSchema, getTeamAiUsageQuerySchema } from '@shumai/dtos'
import { apiTokenService } from '@shumai/core/src/user/api-token' import { apiTokenService } from '@shumai/core/src/user/api-token'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -313,5 +314,25 @@ const route = new Hono<{ Variables: { user: User } }>()
await apiTokenService.deleteToken(user.id, tokenId) await apiTokenService.deleteToken(user.id, tokenId)
return c.json({ success: true }) return c.json({ success: true })
}) })
.get('/teams/:teamId/ai-usage', zValidator('query', getTeamAiUsageQuerySchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const { timeframe, userId } = c.req.valid('query')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const stats = await aiUsageService.getTeamUsageStats({
teamId,
timeframe,
userId,
})
return c.json(stats)
})
export default route export default route
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/core", "name": "@shumai/core",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+52
View File
@@ -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)
})
}) })
}) })
+56 -3
View File
@@ -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,
}
}) })
} }
} }
+313
View File
@@ -0,0 +1,313 @@
import { describe, expect, it, vi } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { aiUsageService } from './ai-usage'
import { HTTPException } from 'hono/http-exception'
describe('AiUsageService', () => {
setupTestDbHooks()
async function createTestTeamAndUser() {
const user = await prisma.user.create({
data: {
name: 'Usage Test User',
email: `usage-test-${Date.now()}-${Math.random()}@example.com`,
},
})
const team = await prisma.team.create({
data: {
name: 'Usage Test Team',
},
})
const teamMember = await prisma.teamMember.create({
data: {
teamId: team.id,
userId: user.id,
role: 'owner',
},
})
return { user, team, teamMember }
}
it('records usage for both team total and specific member', async () => {
const { team, user } = await createTestTeamAndUser()
const now = new Date()
await aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 100,
outputTokens: 50,
cacheReadTokens: 20,
totalTokens: 150,
cost: 0.001,
timestamp: now,
})
// Verify database rows
const records = await prisma.aiUsage.findMany({
where: { teamId: team.id },
})
expect(records).toHaveLength(2)
const teamRecord = records.find((r) => r.userId === null)
expect(teamRecord).toBeDefined()
expect(teamRecord?.inputTokens).toBe(100)
expect(teamRecord?.outputTokens).toBe(50)
expect(teamRecord?.cacheReadTokens).toBe(20)
expect(teamRecord?.totalTokens).toBe(150)
expect(teamRecord?.cost).toBeCloseTo(0.001)
const memberRecord = records.find((r) => r.userId === user.id)
expect(memberRecord).toBeDefined()
expect(memberRecord?.inputTokens).toBe(100)
expect(memberRecord?.outputTokens).toBe(50)
expect(memberRecord?.cacheReadTokens).toBe(20)
expect(memberRecord?.totalTokens).toBe(150)
expect(memberRecord?.cost).toBeCloseTo(0.001)
})
it('increments existing hourly buckets for team and member', async () => {
const { team, user } = await createTestTeamAndUser()
const now = new Date()
await aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 100,
outputTokens: 50,
cacheReadTokens: 10,
totalTokens: 150,
cost: 0.001,
timestamp: now,
})
await aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 200,
outputTokens: 100,
cacheReadTokens: 30,
totalTokens: 300,
cost: 0.002,
timestamp: now,
})
const teamStats = await aiUsageService.getTeamUsageStats({
teamId: team.id,
timeframe: '1h',
})
expect(teamStats.team).toBeDefined()
expect(teamStats.team?.inputTokens).toBe(300)
expect(teamStats.team?.outputTokens).toBe(150)
expect(teamStats.team?.cacheReadTokens).toBe(40)
expect(teamStats.team?.totalTokens).toBe(450)
expect(teamStats.team?.cost).toBeCloseTo(0.003)
const memberStats = await aiUsageService.getTeamUsageStats({
teamId: team.id,
timeframe: '1h',
userId: user.id,
})
expect(memberStats.member).toBeDefined()
expect(memberStats.member?.userId).toBe(user.id)
expect(memberStats.member?.inputTokens).toBe(300)
expect(memberStats.member?.outputTokens).toBe(150)
expect(memberStats.member?.cacheReadTokens).toBe(40)
expect(memberStats.member?.totalTokens).toBe(450)
expect(memberStats.member?.cost).toBeCloseTo(0.003)
})
it('handles background system tasks with no userId', async () => {
const { team } = await createTestTeamAndUser()
await aiUsageService.recordUsage({
teamId: team.id,
userId: null,
inputTokens: 50,
outputTokens: 25,
cacheReadTokens: 5,
totalTokens: 75,
cost: 0.0005,
})
const records = await prisma.aiUsage.findMany({
where: { teamId: team.id },
})
expect(records).toHaveLength(1)
expect(records[0].userId).toBeNull()
expect(records[0].inputTokens).toBe(50)
})
it('filters statistics correctly by timeframe', async () => {
vi.useFakeTimers()
const now = new Date('2026-07-23T15:30:00Z')
vi.setSystemTime(now)
try {
const { team, user } = await createTestTeamAndUser()
// 5 minutes ago (within current 1h bucket)
const recent = new Date(now.getTime() - 5 * 60 * 1000)
// 2 hours ago (within 24h, outside 1h)
const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000)
// 3 days ago (within 7d, outside 24h)
const threeDaysAgo = new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000)
await aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 100,
outputTokens: 50,
cacheReadTokens: 10,
totalTokens: 150,
cost: 0.001,
timestamp: recent,
})
await aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 200,
outputTokens: 100,
cacheReadTokens: 20,
totalTokens: 300,
cost: 0.002,
timestamp: twoHoursAgo,
})
await aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 400,
outputTokens: 200,
cacheReadTokens: 40,
totalTokens: 600,
cost: 0.004,
timestamp: threeDaysAgo,
})
// 1h timeframe should only include recent
const stats1h = await aiUsageService.getTeamUsageStats({
teamId: team.id,
timeframe: '1h',
})
expect(stats1h.team?.inputTokens).toBe(100)
// 24h timeframe should include recent + 2 hours ago
const stats24h = await aiUsageService.getTeamUsageStats({
teamId: team.id,
timeframe: '24h',
})
expect(stats24h.team?.inputTokens).toBe(300)
// 7d timeframe should include all 3
const stats7d = await aiUsageService.getTeamUsageStats({
teamId: team.id,
timeframe: '7d',
})
expect(stats7d.team?.inputTokens).toBe(700)
} finally {
vi.useRealTimers()
}
})
it('throws 404 when querying non-existent team member', async () => {
const { team } = await createTestTeamAndUser()
await expect(
aiUsageService.getTeamUsageStats({
teamId: team.id,
timeframe: '30d',
userId: 'non-existent-user-id',
}),
).rejects.toThrow(HTTPException)
})
it('targets only current hour bucket for 1h timeframe instead of including previous hour bucket', async () => {
const { team, user } = await createTestTeamAndUser()
// 10:15 AM (previous hour)
const prevHour = new Date('2026-07-23T10:15:00Z')
// 11:10 AM (current hour)
const currHour = new Date('2026-07-23T11:10:00Z')
await aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 100,
outputTokens: 0,
cacheReadTokens: 0,
totalTokens: 100,
cost: 0.001,
timestamp: prevHour,
})
await aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 50,
outputTokens: 0,
cacheReadTokens: 0,
totalTokens: 50,
cost: 0.0005,
timestamp: currHour,
})
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-07-23T11:15:00Z'))
try {
const stats1h = await aiUsageService.getTeamUsageStats({
teamId: team.id,
timeframe: '1h',
})
expect(stats1h.team?.inputTokens).toBe(50)
} finally {
vi.useRealTimers()
}
})
it('handles concurrent recordUsage calls for the same team and user without duplication or race errors', async () => {
const { team, user } = await createTestTeamAndUser()
const now = new Date()
await Promise.all([
aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 100,
outputTokens: 50,
cacheReadTokens: 10,
totalTokens: 150,
cost: 0.001,
timestamp: now,
}),
aiUsageService.recordUsage({
teamId: team.id,
userId: user.id,
inputTokens: 200,
outputTokens: 100,
cacheReadTokens: 20,
totalTokens: 300,
cost: 0.002,
timestamp: now,
}),
])
const stats = await aiUsageService.getTeamUsageStats({
teamId: team.id,
timeframe: '1h',
})
expect(stats.team?.inputTokens).toBe(300)
expect(stats.team?.outputTokens).toBe(150)
})
})
+263
View File
@@ -0,0 +1,263 @@
import { prisma, Prisma } from '@shumai/db'
import type { TeamUsageStatsResponse, Timeframe } from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
export interface RecordUsageParams {
teamId: string
userId?: string | null
inputTokens: number
outputTokens: number
cacheReadTokens: number
totalTokens: number
cost: number
timestamp?: Date
}
export interface GetTeamUsageStatsParams {
teamId: string
timeframe: Timeframe
userId?: string
}
export class AiUsageService {
private async incrementBucket(params: {
teamId: string
userId: string | null
periodStart: Date
inputTokens: number
outputTokens: number
cacheReadTokens: number
totalTokens: number
cost: number
}): Promise<void> {
if (params.userId !== null) {
await prisma.aiUsage.upsert({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
teamId_userId_periodStart: {
teamId: params.teamId,
userId: params.userId,
periodStart: params.periodStart,
},
},
update: {
inputTokens: { increment: params.inputTokens },
outputTokens: { increment: params.outputTokens },
cacheReadTokens: { increment: params.cacheReadTokens },
totalTokens: { increment: params.totalTokens },
cost: { increment: params.cost },
},
create: {
teamId: params.teamId,
userId: params.userId,
periodStart: params.periodStart,
inputTokens: params.inputTokens,
outputTokens: params.outputTokens,
cacheReadTokens: params.cacheReadTokens,
totalTokens: params.totalTokens,
cost: params.cost,
},
})
} else {
const existing = await prisma.aiUsage.findFirst({
where: {
teamId: params.teamId,
userId: null,
periodStart: params.periodStart,
},
})
if (existing) {
await prisma.aiUsage.update({
where: { id: existing.id },
data: {
inputTokens: { increment: params.inputTokens },
outputTokens: { increment: params.outputTokens },
cacheReadTokens: { increment: params.cacheReadTokens },
totalTokens: { increment: params.totalTokens },
cost: { increment: params.cost },
},
})
} else {
try {
await prisma.aiUsage.create({
data: {
teamId: params.teamId,
userId: null,
periodStart: params.periodStart,
inputTokens: params.inputTokens,
outputTokens: params.outputTokens,
cacheReadTokens: params.cacheReadTokens,
totalTokens: params.totalTokens,
cost: params.cost,
},
})
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
await prisma.aiUsage.updateMany({
where: {
teamId: params.teamId,
userId: null,
periodStart: params.periodStart,
},
data: {
inputTokens: { increment: params.inputTokens },
outputTokens: { increment: params.outputTokens },
cacheReadTokens: { increment: params.cacheReadTokens },
totalTokens: { increment: params.totalTokens },
cost: { increment: params.cost },
},
})
} else {
throw err
}
}
}
}
}
async recordUsage(params: RecordUsageParams): Promise<void> {
const timestamp = params.timestamp ?? new Date()
const periodStart = new Date(timestamp)
periodStart.setMinutes(0, 0, 0)
// 1. Update/create Team Total record (userId = null)
await this.incrementBucket({
teamId: params.teamId,
userId: null,
periodStart,
inputTokens: params.inputTokens,
outputTokens: params.outputTokens,
cacheReadTokens: params.cacheReadTokens,
totalTokens: params.totalTokens,
cost: params.cost,
})
// 2. If triggered by a team member, update/create Member Usage record (userId = params.userId)
if (params.userId) {
await this.incrementBucket({
teamId: params.teamId,
userId: params.userId,
periodStart,
inputTokens: params.inputTokens,
outputTokens: params.outputTokens,
cacheReadTokens: params.cacheReadTokens,
totalTokens: params.totalTokens,
cost: params.cost,
})
}
}
async getTeamUsageStats(params: GetTeamUsageStatsParams): Promise<TeamUsageStatsResponse> {
const now = new Date()
const since = new Date(now)
switch (params.timeframe) {
case '1h':
// For 1h, target the current 1h bucket floored to start of current hour
since.setMinutes(0, 0, 0)
break
case '24h':
since.setDate(since.getDate() - 1)
since.setMinutes(0, 0, 0)
break
case '7d':
since.setDate(since.getDate() - 7)
since.setMinutes(0, 0, 0)
break
case '30d':
since.setDate(since.getDate() - 30)
since.setMinutes(0, 0, 0)
break
}
if (!params.userId) {
// Return Team-Level Usage (userId = null)
const teamRecords = await prisma.aiUsage.findMany({
where: {
teamId: params.teamId,
userId: null,
periodStart: { gte: since },
},
})
let inputTokens = 0
let outputTokens = 0
let cacheReadTokens = 0
let totalTokens = 0
let cost = 0
for (const r of teamRecords) {
inputTokens += r.inputTokens
outputTokens += r.outputTokens
cacheReadTokens += r.cacheReadTokens
totalTokens += r.totalTokens
cost += r.cost
}
return {
timeframe: params.timeframe,
team: {
inputTokens,
outputTokens,
cacheReadTokens,
totalTokens,
cost: Math.round((cost + Number.EPSILON) * 1000000) / 1000000,
},
}
} else {
// Return Specific Member Usage
const teamMember = await prisma.teamMember.findFirst({
where: {
teamId: params.teamId,
userId: params.userId,
},
include: { user: true },
})
if (!teamMember) {
throw new HTTPException(404, { message: 'Team member not found' })
}
const memberRecords = await prisma.aiUsage.findMany({
where: {
teamId: params.teamId,
userId: params.userId,
periodStart: { gte: since },
},
})
let inputTokens = 0
let outputTokens = 0
let cacheReadTokens = 0
let totalTokens = 0
let cost = 0
for (const r of memberRecords) {
inputTokens += r.inputTokens
outputTokens += r.outputTokens
cacheReadTokens += r.cacheReadTokens
totalTokens += r.totalTokens
cost += r.cost
}
return {
timeframe: params.timeframe,
member: {
userId: teamMember.user.id,
userName: teamMember.user.name,
userEmail: teamMember.user.email,
userImage: teamMember.user.image,
role: teamMember.role,
inputTokens,
outputTokens,
cacheReadTokens,
totalTokens,
cost: Math.round((cost + Number.EPSILON) * 1000000) / 1000000,
},
}
}
}
}
export const aiUsageService = new AiUsageService()
+2 -10
View File
@@ -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)
}) })
+1 -4
View File
@@ -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,
}, },
}, },
+38 -42
View File
@@ -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,
}, },
}) })
+31 -14
View File
@@ -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)
} }
+1
View File
@@ -21,3 +21,4 @@ export * from './versionStack/versionStack'
export * from './hyrumtoken' export * from './hyrumtoken'
export * from './pagination' export * from './pagination'
export * from './chat/chat' export * from './chat/chat'
export * from './ai-usage/ai-usage'
+16 -2
View File
@@ -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',
} }
} }
+54
View File
@@ -127,6 +127,7 @@ describe('SearchService', () => {
// String fields // String fields
await createWithMeta('str-apple', { text: 'apple' }) await createWithMeta('str-apple', { text: 'apple' })
await createWithMeta('str-banana', { text: 'banana' }) await createWithMeta('str-banana', { text: 'banana' })
await createWithMeta('sku-1-2', { sku: '1-2' })
// Number fields // Number fields
await createWithMeta('num-10', { num: 10 }) await createWithMeta('num-10', { num: 10 })
@@ -181,6 +182,7 @@ describe('SearchService', () => {
val: 'str-apple', val: 'str-apple',
expected: [ expected: [
'str-banana', 'str-banana',
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -200,6 +202,7 @@ describe('SearchService', () => {
val: 'apple', val: 'apple',
expected: [ expected: [
'str-banana', 'str-banana',
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -220,6 +223,7 @@ describe('SearchService', () => {
expected: [ expected: [
'str-apple', 'str-apple',
'str-banana', 'str-banana',
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -235,12 +239,14 @@ describe('SearchService', () => {
// String Metadata // String Metadata
{ field: 'text', op: 'eq', val: 'apple', expected: ['str-apple'] }, { field: 'text', op: 'eq', val: 'apple', expected: ['str-apple'] },
{ field: 'sku', op: 'eq', val: '1-2', expected: ['sku-1-2'] },
{ {
field: 'text', field: 'text',
op: 'neq', op: 'neq',
val: 'apple', val: 'apple',
expected: [ expected: [
'str-banana', 'str-banana',
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -258,6 +264,7 @@ describe('SearchService', () => {
op: 'isEmpty', op: 'isEmpty',
val: null, val: null,
expected: [ expected: [
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -281,6 +288,7 @@ describe('SearchService', () => {
expected: [ expected: [
'str-apple', 'str-apple',
'str-banana', 'str-banana',
'sku-1-2',
'num-20', 'num-20',
'bool-true', 'bool-true',
'bool-false', 'bool-false',
@@ -293,6 +301,7 @@ describe('SearchService', () => {
], ],
}, },
{ field: 'num', op: 'gt', val: 15, expected: ['num-20'] }, { field: 'num', op: 'gt', val: 15, expected: ['num-20'] },
{ field: 'num', op: 'gt', val: 100, expected: [] },
{ field: 'num', op: 'lt', val: 15, expected: ['num-10'] }, { field: 'num', op: 'lt', val: 15, expected: ['num-10'] },
{ field: 'num', op: 'gte', val: 20, expected: ['num-20'] }, { field: 'num', op: 'gte', val: 20, expected: ['num-20'] },
{ field: 'num', op: 'lte', val: 10, expected: ['num-10'] }, { field: 'num', op: 'lte', val: 10, expected: ['num-10'] },
@@ -314,6 +323,7 @@ describe('SearchService', () => {
expected: [ expected: [
'str-apple', 'str-apple',
'str-banana', 'str-banana',
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -332,6 +342,7 @@ describe('SearchService', () => {
expected: [ expected: [
'str-apple', 'str-apple',
'str-banana', 'str-banana',
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -346,6 +357,7 @@ describe('SearchService', () => {
// Date Metadata // Date Metadata
{ field: 'date', op: 'eq', val: 'today', expected: ['date-today'] }, { field: 'date', op: 'eq', val: 'today', expected: ['date-today'] },
{ field: 'date', op: 'lte', val: 'today', expected: ['date-today', 'date-yesterday'] },
{ field: 'date', op: 'isWithin', val: 'today', expected: ['date-today'] }, { field: 'date', op: 'isWithin', val: 'today', expected: ['date-today'] },
{ field: 'date', op: 'lt', val: 'today', expected: ['date-yesterday'] }, { field: 'date', op: 'lt', val: 'today', expected: ['date-yesterday'] },
{ field: 'date', op: 'gt', val: 'yesterday', expected: ['date-today'] }, { field: 'date', op: 'gt', val: 'yesterday', expected: ['date-today'] },
@@ -358,6 +370,7 @@ describe('SearchService', () => {
expected: [ expected: [
'str-apple', 'str-apple',
'str-banana', 'str-banana',
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -378,6 +391,47 @@ describe('SearchService', () => {
expected: [ expected: [
'str-apple', 'str-apple',
'str-banana', 'str-banana',
'sku-1-2',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{
field: 'createdAt',
op: 'eq',
val: 'today',
expected: [
'str-apple',
'str-banana',
'sku-1-2',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{
field: 'createdAt',
op: 'lte',
val: 'today',
expected: [
'str-apple',
'str-banana',
'sku-1-2',
'num-10', 'num-10',
'num-20', 'num-20',
'bool-true', 'bool-true',
@@ -35,4 +35,76 @@ describe('SqlQueryBuilder', () => {
const builder = new SqlQueryBuilder().select(Prisma.sql`id`) const builder = new SqlQueryBuilder().select(Prisma.sql`id`)
expect(() => builder.build()).toThrow('FROM clause is required') expect(() => builder.build()).toThrow('FROM clause is required')
}) })
describe('Bug Reproduction Tests for buildSqlCondition', () => {
it('Bug 1: createdAt eq date should match full day range (>= startOfDay AND <= endOfDay)', () => {
const builder = new SqlQueryBuilder()
.from(Prisma.sql`assets a`)
.addSearchConditions('AND', [{ field: 'createdAt', operator: 'eq', value: '2026-07-22' }])
const query = builder.build()
expect(query.text).toBe(
'SELECT * FROM assets a WHERE (a."created_at" >= $1 AND a."created_at" <= $2)',
)
const startVal = query.values[0] as Date
const endVal = query.values[1] as Date
expect(startVal.getHours()).toBe(0)
expect(startVal.getMinutes()).toBe(0)
expect(startVal.getSeconds()).toBe(0)
expect(endVal.getHours()).toBe(23)
expect(endVal.getMinutes()).toBe(59)
expect(endVal.getSeconds()).toBe(59)
})
it('Bug 2: createdAt lte date should use end-of-day timestamp (23:59:59.999)', () => {
const builder = new SqlQueryBuilder()
.from(Prisma.sql`assets a`)
.addSearchConditions('AND', [{ field: 'createdAt', operator: 'lte', value: '2026-07-22' }])
const query = builder.build()
expect(query.text).toBe('SELECT * FROM assets a WHERE (a."created_at" <= $1)')
const endVal = query.values[0] as Date
expect(endVal.getHours()).toBe(23)
expect(endVal.getMinutes()).toBe(59)
expect(endVal.getSeconds()).toBe(59)
})
it('Bug 3: custom metadata numeric query should ONLY query number_value', () => {
const builder = new SqlQueryBuilder()
.from(Prisma.sql`assets a`)
.addSearchConditions('AND', [{ field: 'rating', operator: 'gt', value: 100 }])
const query = builder.build()
expect(query.text).toBe(
'SELECT * FROM assets a WHERE (a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = $1 AND number_value > $2))',
)
expect(query.values).toEqual(['rating', 100])
})
it('Bug 4: isDate should not misclassify dash-separated non-date string values like "1-2"', () => {
const builder = new SqlQueryBuilder()
.from(Prisma.sql`assets a`)
.addSearchConditions('AND', [{ field: 'sku', operator: 'eq', value: '1-2' }])
const query = builder.build()
expect(query.text).toBe(
'SELECT * FROM assets a WHERE (a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = $1 AND string_value = $2))',
)
expect(query.values).toEqual(['sku', '1-2'])
})
it('Bug 5: custom field names with special characters are safely parameterized', () => {
const builder = new SqlQueryBuilder()
.from(Prisma.sql`assets a`)
.addSearchConditions('AND', [
{ field: 'custom_field"test', operator: 'eq', value: 'hello' },
])
const query = builder.build()
expect(query.text).toBe(
'SELECT * FROM assets a WHERE (a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = $1 AND string_value = $2))',
)
expect(query.values).toEqual(['custom_field"test', 'hello'])
})
})
}) })
+61 -33
View File
@@ -101,7 +101,7 @@ export class SqlQueryBuilder {
private isDate(value: unknown): boolean { private isDate(value: unknown): boolean {
if (value instanceof Date) return true if (value instanceof Date) return true
if (typeof value !== 'string') return false if (typeof value !== 'string') return false
const valStr = value.toLowerCase() const valStr = value.trim().toLowerCase()
const relativeKeywords = [ const relativeKeywords = [
'today', 'today',
'yesterday', 'yesterday',
@@ -111,11 +111,14 @@ export class SqlQueryBuilder {
'one month ago', 'one month ago',
'one month from now', 'one month from now',
] ]
if (relativeKeywords.includes(valStr) || valStr.match(/\d+\s+days?\s+(ago|from\s+now)/)) { if (relativeKeywords.includes(valStr) || valStr.match(/^\d+\s+days?\s+(ago|from\s+now)$/)) {
return true return true
} }
if (!valStr.match(/^\d{4}-\d{2}-\d{2}/)) {
return false
}
const d = new Date(value) const d = new Date(value)
return !isNaN(d.getTime()) && value.includes('-') return !isNaN(d.getTime())
} }
private toDate(value: unknown): Date { private toDate(value: unknown): Date {
@@ -123,12 +126,8 @@ export class SqlQueryBuilder {
} }
private toDateBound(value: unknown, bound: 'start' | 'end'): Date { private toDateBound(value: unknown, bound: 'start' | 'end'): Date {
const d = this.parseRelativeDate(value) const range = this.parseDateRange(value)
if (d instanceof Date) return d return bound === 'start' ? range.start : range.end
if (d && 'gte' in d && 'lte' in d) {
return bound === 'start' ? d.gte! : d.lte!
}
return new Date(value as string)
} }
private parseDateRange(value: unknown): { start: Date; end: Date } { private parseDateRange(value: unknown): { start: Date; end: Date } {
@@ -137,6 +136,11 @@ export class SqlQueryBuilder {
return { start: d.gte!, end: d.lte! } return { start: d.gte!, end: d.lte! }
} }
const date = d instanceof Date ? d : new Date(value as string) const date = d instanceof Date ? d : new Date(value as string)
const valStr = typeof value === 'string' ? value : ''
const hasTime = valStr.includes('T') || valStr.includes(':')
if (hasTime) {
return { start: date, end: date }
}
const start = new Date(date) const start = new Date(date)
start.setHours(0, 0, 0, 0) start.setHours(0, 0, 0, 0)
const end = new Date(date) const end = new Date(date)
@@ -239,18 +243,8 @@ export class SqlQueryBuilder {
} }
private buildSqlCondition(field: string, operator: string, value: unknown): Prisma.Sql | null { private buildSqlCondition(field: string, operator: string, value: unknown): Prisma.Sql | null {
const colName =
field === 'sizeByte' || field === 'size_byte'
? 'size_byte'
: field === 'createdAt' || field === 'created_at'
? 'created_at'
: field === 'updatedAt' || field === 'updated_at'
? 'updated_at'
: field
const dbCol = Prisma.raw(`a."${colName}"`)
if (field === 'name') { if (field === 'name') {
const dbCol = Prisma.raw(`a."name"`)
const valStr = String(value) const valStr = String(value)
switch (operator) { switch (operator) {
case 'eq': case 'eq':
@@ -271,6 +265,7 @@ export class SqlQueryBuilder {
} }
if (field === 'sizeByte' || field === 'size_byte') { if (field === 'sizeByte' || field === 'size_byte') {
const dbCol = Prisma.raw(`a."size_byte"`)
const valNum = Number(value) const valNum = Number(value)
switch (operator) { switch (operator) {
case 'eq': case 'eq':
@@ -296,12 +291,17 @@ export class SqlQueryBuilder {
field === 'created_at' || field === 'created_at' ||
field === 'updated_at' field === 'updated_at'
) { ) {
const valDate = this.toDate(value) const colName = field === 'createdAt' || field === 'created_at' ? 'created_at' : 'updated_at'
const dbCol = Prisma.raw(`a."${colName}"`)
switch (operator) { switch (operator) {
case 'eq': case 'eq': {
return Prisma.sql`${dbCol} = ${valDate}` const range = this.parseDateRange(value)
case 'neq': return Prisma.sql`${dbCol} >= ${range.start} AND ${dbCol} <= ${range.end}`
return Prisma.sql`${dbCol} != ${valDate}` }
case 'neq': {
const range = this.parseDateRange(value)
return Prisma.sql`(${dbCol} < ${range.start} OR ${dbCol} > ${range.end})`
}
case 'gt': case 'gt':
return Prisma.sql`${dbCol} > ${this.toDateBound(value, 'end')}` return Prisma.sql`${dbCol} > ${this.toDateBound(value, 'end')}`
case 'gte': case 'gte':
@@ -333,14 +333,42 @@ export class SqlQueryBuilder {
const matchSql = this.buildEavValueMatch(value) const matchSql = this.buildEavValueMatch(value)
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field}) OR a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND NOT (${matchSql}))` return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field}) OR a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND NOT (${matchSql}))`
} }
case 'gt': case 'gt': {
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value > ${Number(value)} OR date_value > ${this.toDateBound(value, 'end')}))` if (
case 'gte': typeof value === 'number' ||
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value >= ${Number(value)} OR date_value >= ${this.toDateBound(value, 'start')}))` (typeof value === 'string' && !isNaN(Number(value)) && !this.isDate(value))
case 'lt': ) {
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value < ${Number(value)} OR date_value < ${this.toDateBound(value, 'start')}))` return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND number_value > ${Number(value)})`
case 'lte': }
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value <= ${Number(value)} OR date_value <= ${this.toDateBound(value, 'end')}))` return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value > ${this.toDateBound(value, 'end')})`
}
case 'gte': {
if (
typeof value === 'number' ||
(typeof value === 'string' && !isNaN(Number(value)) && !this.isDate(value))
) {
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND number_value >= ${Number(value)})`
}
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value >= ${this.toDateBound(value, 'start')})`
}
case 'lt': {
if (
typeof value === 'number' ||
(typeof value === 'string' && !isNaN(Number(value)) && !this.isDate(value))
) {
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND number_value < ${Number(value)})`
}
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value < ${this.toDateBound(value, 'start')})`
}
case 'lte': {
if (
typeof value === 'number' ||
(typeof value === 'string' && !isNaN(Number(value)) && !this.isDate(value))
) {
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND number_value <= ${Number(value)})`
}
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value <= ${this.toDateBound(value, 'end')})`
}
case 'contains': case 'contains':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND string_value ILIKE ${'%' + String(value) + '%'})` return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND string_value ILIKE ${'%' + String(value) + '%'})`
case 'notContains': case 'notContains':
+140 -1
View File
@@ -3,6 +3,7 @@ import { transcodeService } from './transcode'
import { s3Service } from '@shumai/core/src/s3/s3' import { s3Service } from '@shumai/core/src/s3/s3'
import * as path from 'path' import * as path from 'path'
import * as child_process from 'child_process' import * as child_process from 'child_process'
import { execFile } from 'child_process'
import * as fs from 'fs' import * as fs from 'fs'
import { WorkflowTask } from '@shumai/db' import { WorkflowTask } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test' import { setupTestDbHooks } from '@shumai/db/test'
@@ -24,6 +25,7 @@ vi.mock('child_process', () => ({
vi.mock('sharp', () => { vi.mock('sharp', () => {
const mockSharp = { const mockSharp = {
resize: vi.fn().mockReturnThis(), resize: vi.fn().mockReturnThis(),
toColorspace: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(), webp: vi.fn().mockReturnThis(),
composite: vi.fn().mockReturnThis(), composite: vi.fn().mockReturnThis(),
toBuffer: vi.fn().mockResolvedValue(Buffer.from('fake-webp-buffer')), toBuffer: vi.fn().mockResolvedValue(Buffer.from('fake-webp-buffer')),
@@ -182,17 +184,62 @@ describe('TranscodeService', () => {
) )
}) })
it('should use sharp for image transcoding', async () => { it('should use sharp for image transcoding with sRGB conversion', async () => {
const outputFile = path.join(tempDir, 'output.webp') const outputFile = path.join(tempDir, 'output.webp')
await transcodeService.transcodeImage('input.png', outputFile, 480, 80) await transcodeService.transcodeImage('input.png', outputFile, 480, 80)
expect(sharp).toHaveBeenCalledWith('input.png', { limitInputPixels: false }) expect(sharp).toHaveBeenCalledWith('input.png', { limitInputPixels: false })
const mockSharp = vi.mocked(sharp).mock.results[0].value const mockSharp = vi.mocked(sharp).mock.results[0].value
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
expect(mockSharp.resize).toHaveBeenCalledWith(480, 7680, expect.any(Object)) expect(mockSharp.resize).toHaveBeenCalledWith(480, 7680, expect.any(Object))
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 }) expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 })
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile) expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
}) })
it('should use ImageMagick for PSD image transcoding', async () => {
const outputFile = path.join(tempDir, 'output_psd.webp')
const psdBuffer = Buffer.from('8BPS-fake-psd-content')
await transcodeService.transcodeImage(psdBuffer, outputFile, 480, 80)
expect(execFile).toHaveBeenCalledWith(
'magick',
expect.arrayContaining([
'-colorspace',
'sRGB',
expect.stringContaining('[0]'),
'-quality',
'80',
]),
expect.any(Function),
)
})
it('should get PSD image info using ImageMagick identify', async () => {
const mockExecFile = vi.mocked(execFile)
mockExecFile.mockImplementation((cmd: unknown, args: unknown, callback: unknown) => {
const cb = callback as (
err: Error | null,
result: { stdout: string; stderr: string },
extra: string,
) => void
const argsArr = args as string[] | undefined
if (cmd === 'magick' && argsArr && argsArr[0] === 'identify') {
cb(null, { stdout: '1920 1080\n', stderr: '' }, '')
} else if (typeof cb === 'function') {
cb(null, { stdout: '', stderr: '' }, '')
}
return {} as ReturnType<typeof execFile>
})
const psdPath = path.join(tempDir, 'sample.psd')
fs.writeFileSync(psdPath, '8BPS-sample')
const info = await transcodeService.getImageInfo(psdPath)
expect(info.originalWidth).toBe(1920)
expect(info.originalHeight).toBe(1080)
expect(info.mimeType).toBe('psd')
})
it('should fetch image if input is a URL', async () => { it('should fetch image if input is a URL', async () => {
const mockBuffer = Buffer.from('fake-image-data') const mockBuffer = Buffer.from('fake-image-data')
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -215,6 +262,7 @@ describe('TranscodeService', () => {
expect(sharp).toHaveBeenCalledWith(inputBuffer, { limitInputPixels: false }) expect(sharp).toHaveBeenCalledWith(inputBuffer, { limitInputPixels: false })
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
expect(mockSharp.resize).toHaveBeenCalledWith(480, 7680, expect.any(Object)) expect(mockSharp.resize).toHaveBeenCalledWith(480, 7680, expect.any(Object))
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 }) expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 })
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile) expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
@@ -598,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')
+145 -11
View File
@@ -120,9 +120,69 @@ export interface ExtractVideoFramesParams {
isImage: boolean isImage: boolean
} }
export function isPsdInput(input: string | Buffer): boolean {
if (typeof input === 'string') {
if (input.toLowerCase().endsWith('.psd')) return true
if (fs.existsSync(input)) {
try {
const fd = fs.openSync(input, 'r')
const buf = Buffer.alloc(4)
fs.readSync(fd, buf, 0, 4, 0)
fs.closeSync(fd)
return buf.toString('ascii') === '8BPS'
} catch {
return false
}
}
return false
}
return (
input.length >= 4 &&
input[0] === 0x38 &&
input[1] === 0x42 &&
input[2] === 0x50 &&
input[3] === 0x53
)
}
export class TranscodeService { export class TranscodeService {
constructor(private readonly prismaClient: typeof prisma = prisma) {} constructor(private readonly prismaClient: typeof prisma = prisma) {}
private async execImageMagick(args: string[]): Promise<{ stdout: string; stderr: string }> {
try {
return await execFileAsync('magick', args)
} catch (err: unknown) {
const code = (err as Record<string, unknown>)?.code
if (code === 'ENOENT') {
return await execFileAsync('convert', args)
}
throw err
}
}
private async execImageMagickIdentify(
filePath: string,
): Promise<{ width: number; height: number }> {
const fileArg = `${filePath}[0]`
let stdout: string
try {
const res = await execFileAsync('magick', ['identify', '-format', '%w %h', fileArg])
stdout = res.stdout
} catch (err: unknown) {
const code = (err as Record<string, unknown>)?.code
if (code === 'ENOENT') {
const res = await execFileAsync('identify', ['-format', '%w %h', fileArg])
stdout = res.stdout
} else {
throw err
}
}
const parts = stdout.trim().split(/\s+/)
const width = parseInt(parts[0], 10) || 0
const height = parseInt(parts[1], 10) || 0
return { width, height }
}
private resolveCodecName(stream: { private resolveCodecName(stream: {
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
codec_name?: string codec_name?: string
@@ -222,6 +282,8 @@ export class TranscodeService {
async getImageInfo(inputFile: string): Promise<MediaMetadata> { async getImageInfo(inputFile: string): Promise<MediaMetadata> {
let input: string | Buffer = inputFile let input: string | Buffer = inputFile
let tempDirToCleanup: string | null = null
if (inputFile.startsWith('http')) { if (inputFile.startsWith('http')) {
const resp = await fetch(inputFile) const resp = await fetch(inputFile)
if (!resp.ok) { if (!resp.ok) {
@@ -230,6 +292,38 @@ export class TranscodeService {
input = Buffer.from(await resp.arrayBuffer()) input = Buffer.from(await resp.arrayBuffer())
} }
if (isPsdInput(input)) {
let psdPath: string
if (typeof input === 'string') {
psdPath = input
} else {
tempDirToCleanup = this.createTempDir('psd-info-')
psdPath = path.join(tempDirToCleanup, 'input.psd')
fs.writeFileSync(psdPath, input)
}
try {
const { width, height } = await this.execImageMagickIdentify(psdPath)
return {
originalWidth: width,
originalHeight: height,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: 0,
startTimecode: undefined,
hasAudio: false,
mimeType: 'psd',
}
} catch (err) {
console.warn('ImageMagick identify failed for PSD, falling back to sharp:', err)
} finally {
if (tempDirToCleanup) {
this.removeDir(tempDirToCleanup)
}
}
}
const metadata = await sharp(input, { limitInputPixels: false }).metadata() const metadata = await sharp(input, { limitInputPixels: false }).metadata()
return { return {
originalWidth: metadata.width || 0, originalWidth: metadata.width || 0,
@@ -309,13 +403,48 @@ export class TranscodeService {
input = Buffer.from(await resp.arrayBuffer()) input = Buffer.from(await resp.arrayBuffer())
} }
const sharpInstance = sharp(input, { limitInputPixels: false })
const WEBP_MAX_DIMENSION = 7680 const WEBP_MAX_DIMENSION = 7680
const targetW = width > 0 ? Math.min(width, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION const targetW = width > 0 ? Math.min(width, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
const targetH = height && height > 0 ? Math.min(height, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION const targetH = height && height > 0 ? Math.min(height, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
sharpInstance.resize(targetW, targetH, { if (isPsdInput(input)) {
let psdPath: string
let tempDirToCleanup: string | null = null
if (typeof input === 'string') {
psdPath = input
} else {
tempDirToCleanup = this.createTempDir('psd-transcode-')
psdPath = path.join(tempDirToCleanup, 'input.psd')
fs.writeFileSync(psdPath, input)
}
try {
const resizeGeometry =
targetH < WEBP_MAX_DIMENSION
? `${targetW}x${targetH}>`
: `${targetW}x${WEBP_MAX_DIMENSION}>`
await this.execImageMagick([
`${psdPath}[0]`,
'-colorspace',
'sRGB',
'-resize',
resizeGeometry,
'-quality',
quality.toString(),
outputFile,
])
return
} finally {
if (tempDirToCleanup) {
this.removeDir(tempDirToCleanup)
}
}
}
const sharpInstance = sharp(input, { limitInputPixels: false })
sharpInstance.toColorspace('srgb').resize(targetW, targetH, {
withoutEnlargement: true, withoutEnlargement: true,
fit: 'inside', fit: 'inside',
}) })
@@ -430,6 +559,7 @@ export class TranscodeService {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...spriteArgs]) await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...spriteArgs])
await sharp(firstPagePath, { limitInputPixels: false }) await sharp(firstPagePath, { limitInputPixels: false })
.toColorspace('srgb')
.resize(480, null, { withoutEnlargement: true, fit: 'inside' }) .resize(480, null, { withoutEnlargement: true, fit: 'inside' })
.webp({ quality: 75 }) .webp({ quality: 75 })
.toFile(outputPoster) .toFile(outputPoster)
@@ -793,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++) {
@@ -834,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)
@@ -926,6 +1058,7 @@ export class TranscodeService {
const webpName = `${stem}-page-${pageNum}-${ulid()}.webp` const webpName = `${stem}-page-${pageNum}-${ulid()}.webp`
let webpBuffer = await sharp(localPngPath, { limitInputPixels: false }) let webpBuffer = await sharp(localPngPath, { limitInputPixels: false })
.toColorspace('srgb')
.resize(1920, 1080, { fit: 'inside', withoutEnlargement: false }) .resize(1920, 1080, { fit: 'inside', withoutEnlargement: false })
.webp({ quality: 85 }) .webp({ quality: 85 })
.toBuffer() .toBuffer()
@@ -973,6 +1106,7 @@ export class TranscodeService {
const svgStr = renderAnnotationsToSvg(width, height, annotations) const svgStr = renderAnnotationsToSvg(width, height, annotations)
return await sharp(imageBuffer, { limitInputPixels: false }) return await sharp(imageBuffer, { limitInputPixels: false })
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }]) .composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
.toColorspace('srgb')
.resize(16383, 16383, { fit: 'inside', withoutEnlargement: true }) .resize(16383, 16383, { fit: 'inside', withoutEnlargement: true })
.webp({ quality: 85 }) .webp({ quality: 85 })
.toBuffer() .toBuffer()
+7
View File
@@ -27,6 +27,11 @@ describe('detectSupportedMimeType', () => {
expect(detectSupportedMimeType(buffer)).toBe('image/webp') expect(detectSupportedMimeType(buffer)).toBe('image/webp')
}) })
it('should detect PSD', () => {
const buffer = new Uint8Array([0x38, 0x42, 0x50, 0x53, 0x00, 0x01])
expect(detectSupportedMimeType(buffer)).toBe('image/vnd.adobe.photoshop')
})
it('should detect MP4', () => { it('should detect MP4', () => {
const buffer = new Uint8Array([ const buffer = new Uint8Array([
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
@@ -44,6 +49,8 @@ describe('getProxyType', () => {
it('should detect image proxyType', () => { it('should detect image proxyType', () => {
expect(getProxyType('image/png', 'test.png')).toBe('image') expect(getProxyType('image/png', 'test.png')).toBe('image')
expect(getProxyType('image/jpeg', 'photo.jpg')).toBe('image') expect(getProxyType('image/jpeg', 'photo.jpg')).toBe('image')
expect(getProxyType('image/vnd.adobe.photoshop', 'design.psd')).toBe('image')
expect(getProxyType(null, 'design.psd')).toBe('image')
}) })
it('should detect video proxyType', () => { it('should detect video proxyType', () => {
+4 -1
View File
@@ -7,7 +7,7 @@ export function getProxyType(
const lowerMediaType = mediaType?.toLowerCase() || '' const lowerMediaType = mediaType?.toLowerCase() || ''
const lowerFilename = filename?.toLowerCase() || '' const lowerFilename = filename?.toLowerCase() || ''
if (lowerMediaType.startsWith('image/')) return 'image' if (lowerMediaType.startsWith('image/') || lowerFilename.endsWith('.psd')) return 'image'
if (lowerMediaType.startsWith('video/')) return 'video' if (lowerMediaType.startsWith('video/')) return 'video'
if (lowerMediaType.startsWith('audio/')) return 'audio' if (lowerMediaType.startsWith('audio/')) return 'audio'
@@ -32,6 +32,9 @@ export function getProxyType(
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
export function detectSupportedMimeType(buffer: Uint8Array): string | null { export function detectSupportedMimeType(buffer: Uint8Array): string | null {
if (startsWithAscii(buffer, 0, '8BPS')) {
return 'image/vnd.adobe.photoshop'
}
if (startsWith(buffer, [0xff, 0xd8, 0xff])) { if (startsWith(buffer, [0xff, 0xd8, 0xff])) {
return buffer[3] === 0xf7 ? null : 'image/jpeg' return buffer[3] === 0xf7 ? null : 'image/jpeg'
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/db", "name": "@shumai/db",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
@@ -0,0 +1,28 @@
-- CreateTable
CREATE TABLE "ai_usages" (
"id" TEXT NOT NULL,
"team_id" TEXT NOT NULL,
"user_id" TEXT,
"period_start" TIMESTAMP(3) NOT NULL,
"input_tokens" INTEGER NOT NULL DEFAULT 0,
"output_tokens" INTEGER NOT NULL DEFAULT 0,
"cache_read_tokens" INTEGER NOT NULL DEFAULT 0,
"total_tokens" INTEGER NOT NULL DEFAULT 0,
"cost" DOUBLE PRECISION NOT NULL DEFAULT 0,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ai_usages_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "ai_usages_team_id_period_start_idx" ON "ai_usages"("team_id", "period_start");
-- CreateIndex
CREATE INDEX "ai_usages_team_id_user_id_period_start_idx" ON "ai_usages"("team_id", "user_id", "period_start");
-- AddForeignKey
ALTER TABLE "ai_usages" ADD CONSTRAINT "ai_usages_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ai_usages" ADD CONSTRAINT "ai_usages_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,8 @@
/*
Warnings:
- A unique constraint covering the columns `[team_id,user_id,period_start]` on the table `ai_usages` will be added. If there are existing duplicate values, this will fail.
*/
-- CreateIndex
CREATE UNIQUE INDEX "ai_usages_team_id_user_id_period_start_key" ON "ai_usages"("team_id", "user_id", "period_start");
@@ -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");
@@ -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;
@@ -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";
+37 -6
View File
@@ -155,6 +155,7 @@ model User {
collections Collection[] @relation("UserToCollection") collections Collection[] @relation("UserToCollection")
shareLinks ShareLink[] @relation("UserToShareLink") shareLinks ShareLink[] @relation("UserToShareLink")
apiTokens ApiToken[] @relation("UserToApiToken") apiTokens ApiToken[] @relation("UserToApiToken")
aiUsages AiUsage[] @relation("UserToAiUsage")
@@map("users") @@map("users")
} }
@@ -237,6 +238,7 @@ model Team {
skills Skill[] @relation("TeamToSkill") skills Skill[] @relation("TeamToSkill")
sandbox Sandbox? @relation("TeamToSandbox") sandbox Sandbox? @relation("TeamToSandbox")
agents Agent[] @relation("TeamToAgent") agents Agent[] @relation("TeamToAgent")
aiUsages AiUsage[] @relation("TeamToAiUsage")
@@map("teams") @@map("teams")
} }
@@ -720,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 {
@@ -814,3 +822,26 @@ model ApiToken {
@@map("api_tokens") @@map("api_tokens")
} }
model AiUsage {
id String @id @default(ulid())
teamId String @map("team_id")
userId String? @map("user_id")
periodStart DateTime @map("period_start")
inputTokens Int @default(0) @map("input_tokens")
outputTokens Int @default(0) @map("output_tokens")
cacheReadTokens Int @default(0) @map("cache_read_tokens")
totalTokens Int @default(0) @map("total_tokens")
cost Float @default(0) @map("cost")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
team Team @relation("TeamToAiUsage", fields: [teamId], references: [id], onDelete: Cascade)
user User? @relation("UserToAiUsage", fields: [userId], references: [id], onDelete: SetNull)
@@map("ai_usages")
@@unique([teamId, userId, periodStart])
@@index([teamId, periodStart])
@@index([teamId, userId, periodStart])
}
+5
View File
@@ -182,3 +182,8 @@ export type Collection = Prisma.CollectionModel
* *
*/ */
export type ApiToken = Prisma.ApiTokenModel export type ApiToken = Prisma.ApiTokenModel
/**
* Model AiUsage
*
*/
export type AiUsage = Prisma.AiUsageModel
+5
View File
@@ -206,3 +206,8 @@ export type Collection = Prisma.CollectionModel
* *
*/ */
export type ApiToken = Prisma.ApiTokenModel export type ApiToken = Prisma.ApiTokenModel
/**
* Model AiUsage
*
*/
export type AiUsage = Prisma.AiUsageModel
+43
View File
@@ -643,6 +643,33 @@ export type EnumAgentSessionTypeWithAggregatesFilter<$PrismaModel = never> = {
_max?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel> _max?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel>
} }
export type FloatFilter<$PrismaModel = never> = {
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
not?: Prisma.NestedFloatFilter<$PrismaModel> | number
}
export type FloatWithAggregatesFilter<$PrismaModel = never> = {
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
not?: Prisma.NestedFloatWithAggregatesFilter<$PrismaModel> | number
_count?: Prisma.NestedIntFilter<$PrismaModel>
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
_sum?: Prisma.NestedFloatFilter<$PrismaModel>
_min?: Prisma.NestedFloatFilter<$PrismaModel>
_max?: Prisma.NestedFloatFilter<$PrismaModel>
}
export type NestedStringFilter<$PrismaModel = never> = { export type NestedStringFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel> equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
@@ -1218,4 +1245,20 @@ export type NestedEnumAgentSessionTypeWithAggregatesFilter<$PrismaModel = never>
_max?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel> _max?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel>
} }
export type NestedFloatWithAggregatesFilter<$PrismaModel = never> = {
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
not?: Prisma.NestedFloatWithAggregatesFilter<$PrismaModel> | number
_count?: Prisma.NestedIntFilter<$PrismaModel>
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
_sum?: Prisma.NestedFloatFilter<$PrismaModel>
_min?: Prisma.NestedFloatFilter<$PrismaModel>
_max?: Prisma.NestedFloatFilter<$PrismaModel>
}
File diff suppressed because one or more lines are too long
+100 -3
View File
@@ -416,7 +416,8 @@ export const ModelName = {
Model: 'Model', Model: 'Model',
Provider: 'Provider', Provider: 'Provider',
Collection: 'Collection', Collection: 'Collection',
ApiToken: 'ApiToken' ApiToken: 'ApiToken',
AiUsage: 'AiUsage'
} as const } as const
export type ModelName = (typeof ModelName)[keyof typeof ModelName] export type ModelName = (typeof ModelName)[keyof typeof ModelName]
@@ -432,7 +433,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
omit: GlobalOmitOptions omit: GlobalOmitOptions
} }
meta: { meta: {
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "sandbox" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "asset" | "storageKey" | "assetMetadataValue" | "assetComment" | "assetCommentAttachment" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "agentSession" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "sandbox" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "asset" | "storageKey" | "assetMetadataValue" | "assetComment" | "assetCommentAttachment" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "agentSession" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage"
txIsolationLevel: TransactionIsolationLevel txIsolationLevel: TransactionIsolationLevel
} }
model: { model: {
@@ -2878,6 +2879,80 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
} }
} }
} }
AiUsage: {
payload: Prisma.$AiUsagePayload<ExtArgs>
fields: Prisma.AiUsageFieldRefs
operations: {
findUnique: {
args: Prisma.AiUsageFindUniqueArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload> | null
}
findUniqueOrThrow: {
args: Prisma.AiUsageFindUniqueOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>
}
findFirst: {
args: Prisma.AiUsageFindFirstArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload> | null
}
findFirstOrThrow: {
args: Prisma.AiUsageFindFirstOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>
}
findMany: {
args: Prisma.AiUsageFindManyArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>[]
}
create: {
args: Prisma.AiUsageCreateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>
}
createMany: {
args: Prisma.AiUsageCreateManyArgs<ExtArgs>
result: BatchPayload
}
createManyAndReturn: {
args: Prisma.AiUsageCreateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>[]
}
delete: {
args: Prisma.AiUsageDeleteArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>
}
update: {
args: Prisma.AiUsageUpdateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>
}
deleteMany: {
args: Prisma.AiUsageDeleteManyArgs<ExtArgs>
result: BatchPayload
}
updateMany: {
args: Prisma.AiUsageUpdateManyArgs<ExtArgs>
result: BatchPayload
}
updateManyAndReturn: {
args: Prisma.AiUsageUpdateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>[]
}
upsert: {
args: Prisma.AiUsageUpsertArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AiUsagePayload>
}
aggregate: {
args: Prisma.AiUsageAggregateArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AggregateAiUsage>
}
groupBy: {
args: Prisma.AiUsageGroupByArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AiUsageGroupByOutputType>[]
}
count: {
args: Prisma.AiUsageCountArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AiUsageCountAggregateOutputType> | number
}
}
}
} }
} & { } & {
other: { other: {
@@ -3322,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]
@@ -3392,6 +3471,23 @@ export const ApiTokenScalarFieldEnum = {
export type ApiTokenScalarFieldEnum = (typeof ApiTokenScalarFieldEnum)[keyof typeof ApiTokenScalarFieldEnum] export type ApiTokenScalarFieldEnum = (typeof ApiTokenScalarFieldEnum)[keyof typeof ApiTokenScalarFieldEnum]
export const AiUsageScalarFieldEnum = {
id: 'id',
teamId: 'teamId',
userId: 'userId',
periodStart: 'periodStart',
inputTokens: 'inputTokens',
outputTokens: 'outputTokens',
cacheReadTokens: 'cacheReadTokens',
totalTokens: 'totalTokens',
cost: 'cost',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AiUsageScalarFieldEnum = (typeof AiUsageScalarFieldEnum)[keyof typeof AiUsageScalarFieldEnum]
export const SortOrder = { export const SortOrder = {
asc: 'asc', asc: 'asc',
desc: 'desc' desc: 'desc'
@@ -3889,6 +3985,7 @@ export type GlobalOmitConfig = {
provider?: Prisma.ProviderOmit provider?: Prisma.ProviderOmit
collection?: Prisma.CollectionOmit collection?: Prisma.CollectionOmit
apiToken?: Prisma.ApiTokenOmit apiToken?: Prisma.ApiTokenOmit
aiUsage?: Prisma.AiUsageOmit
} }
/* Types for Logging */ /* Types for Logging */
@@ -83,7 +83,8 @@ export const ModelName = {
Model: 'Model', Model: 'Model',
Provider: 'Provider', Provider: 'Provider',
Collection: 'Collection', Collection: 'Collection',
ApiToken: 'ApiToken' ApiToken: 'ApiToken',
AiUsage: 'AiUsage'
} as const } as const
export type ModelName = (typeof ModelName)[keyof typeof ModelName] export type ModelName = (typeof ModelName)[keyof typeof ModelName]
@@ -507,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]
@@ -577,6 +582,23 @@ export const ApiTokenScalarFieldEnum = {
export type ApiTokenScalarFieldEnum = (typeof ApiTokenScalarFieldEnum)[keyof typeof ApiTokenScalarFieldEnum] export type ApiTokenScalarFieldEnum = (typeof ApiTokenScalarFieldEnum)[keyof typeof ApiTokenScalarFieldEnum]
export const AiUsageScalarFieldEnum = {
id: 'id',
teamId: 'teamId',
userId: 'userId',
periodStart: 'periodStart',
inputTokens: 'inputTokens',
outputTokens: 'outputTokens',
cacheReadTokens: 'cacheReadTokens',
totalTokens: 'totalTokens',
cost: 'cost',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AiUsageScalarFieldEnum = (typeof AiUsageScalarFieldEnum)[keyof typeof AiUsageScalarFieldEnum]
export const SortOrder = { export const SortOrder = {
asc: 'asc', asc: 'asc',
desc: 'desc' desc: 'desc'
+1
View File
@@ -41,4 +41,5 @@ export type * from './models/Model.ts'
export type * from './models/Provider.ts' export type * from './models/Provider.ts'
export type * from './models/Collection.ts' export type * from './models/Collection.ts'
export type * from './models/ApiToken.ts' export type * from './models/ApiToken.ts'
export type * from './models/AiUsage.ts'
export type * from './commonInputTypes.ts' export type * from './commonInputTypes.ts'
+3 -6
View File
@@ -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
View File
@@ -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
*/ */
File diff suppressed because it is too large Load Diff
+194
View File
@@ -199,6 +199,7 @@ export type TeamWhereInput = {
skills?: Prisma.SkillListRelationFilter skills?: Prisma.SkillListRelationFilter
sandbox?: Prisma.XOR<Prisma.SandboxNullableScalarRelationFilter, Prisma.SandboxWhereInput> | null sandbox?: Prisma.XOR<Prisma.SandboxNullableScalarRelationFilter, Prisma.SandboxWhereInput> | null
agents?: Prisma.AgentListRelationFilter agents?: Prisma.AgentListRelationFilter
aiUsages?: Prisma.AiUsageListRelationFilter
} }
export type TeamOrderByWithRelationInput = { export type TeamOrderByWithRelationInput = {
@@ -219,6 +220,7 @@ export type TeamOrderByWithRelationInput = {
skills?: Prisma.SkillOrderByRelationAggregateInput skills?: Prisma.SkillOrderByRelationAggregateInput
sandbox?: Prisma.SandboxOrderByWithRelationInput sandbox?: Prisma.SandboxOrderByWithRelationInput
agents?: Prisma.AgentOrderByRelationAggregateInput agents?: Prisma.AgentOrderByRelationAggregateInput
aiUsages?: Prisma.AiUsageOrderByRelationAggregateInput
} }
export type TeamWhereUniqueInput = Prisma.AtLeast<{ export type TeamWhereUniqueInput = Prisma.AtLeast<{
@@ -242,6 +244,7 @@ export type TeamWhereUniqueInput = Prisma.AtLeast<{
skills?: Prisma.SkillListRelationFilter skills?: Prisma.SkillListRelationFilter
sandbox?: Prisma.XOR<Prisma.SandboxNullableScalarRelationFilter, Prisma.SandboxWhereInput> | null sandbox?: Prisma.XOR<Prisma.SandboxNullableScalarRelationFilter, Prisma.SandboxWhereInput> | null
agents?: Prisma.AgentListRelationFilter agents?: Prisma.AgentListRelationFilter
aiUsages?: Prisma.AiUsageListRelationFilter
}, "id" | "rootFolderId"> }, "id" | "rootFolderId">
export type TeamOrderByWithAggregationInput = { export type TeamOrderByWithAggregationInput = {
@@ -285,6 +288,7 @@ export type TeamCreateInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateInput = { export type TeamUncheckedCreateInput = {
@@ -304,6 +308,7 @@ export type TeamUncheckedCreateInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamUpdateInput = { export type TeamUpdateInput = {
@@ -323,6 +328,7 @@ export type TeamUpdateInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateInput = { export type TeamUncheckedUpdateInput = {
@@ -342,6 +348,7 @@ export type TeamUncheckedUpdateInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateManyInput = { export type TeamCreateManyInput = {
@@ -579,6 +586,20 @@ export type TeamUpdateOneRequiredWithoutProvidersNestedInput = {
update?: Prisma.XOR<Prisma.XOR<Prisma.TeamUpdateToOneWithWhereWithoutProvidersInput, Prisma.TeamUpdateWithoutProvidersInput>, Prisma.TeamUncheckedUpdateWithoutProvidersInput> update?: Prisma.XOR<Prisma.XOR<Prisma.TeamUpdateToOneWithWhereWithoutProvidersInput, Prisma.TeamUpdateWithoutProvidersInput>, Prisma.TeamUncheckedUpdateWithoutProvidersInput>
} }
export type TeamCreateNestedOneWithoutAiUsagesInput = {
create?: Prisma.XOR<Prisma.TeamCreateWithoutAiUsagesInput, Prisma.TeamUncheckedCreateWithoutAiUsagesInput>
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutAiUsagesInput
connect?: Prisma.TeamWhereUniqueInput
}
export type TeamUpdateOneRequiredWithoutAiUsagesNestedInput = {
create?: Prisma.XOR<Prisma.TeamCreateWithoutAiUsagesInput, Prisma.TeamUncheckedCreateWithoutAiUsagesInput>
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutAiUsagesInput
upsert?: Prisma.TeamUpsertWithoutAiUsagesInput
connect?: Prisma.TeamWhereUniqueInput
update?: Prisma.XOR<Prisma.XOR<Prisma.TeamUpdateToOneWithWhereWithoutAiUsagesInput, Prisma.TeamUpdateWithoutAiUsagesInput>, Prisma.TeamUncheckedUpdateWithoutAiUsagesInput>
}
export type TeamCreateWithoutSandboxInput = { export type TeamCreateWithoutSandboxInput = {
id?: string id?: string
name: string name: string
@@ -595,6 +616,7 @@ export type TeamCreateWithoutSandboxInput = {
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutSandboxInput = { export type TeamUncheckedCreateWithoutSandboxInput = {
@@ -613,6 +635,7 @@ export type TeamUncheckedCreateWithoutSandboxInput = {
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutSandboxInput = { export type TeamCreateOrConnectWithoutSandboxInput = {
@@ -647,6 +670,7 @@ export type TeamUpdateWithoutSandboxInput = {
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutSandboxInput = { export type TeamUncheckedUpdateWithoutSandboxInput = {
@@ -665,6 +689,7 @@ export type TeamUncheckedUpdateWithoutSandboxInput = {
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutSkillsInput = { export type TeamCreateWithoutSkillsInput = {
@@ -683,6 +708,7 @@ export type TeamCreateWithoutSkillsInput = {
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutSkillsInput = { export type TeamUncheckedCreateWithoutSkillsInput = {
@@ -701,6 +727,7 @@ export type TeamUncheckedCreateWithoutSkillsInput = {
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutSkillsInput = { export type TeamCreateOrConnectWithoutSkillsInput = {
@@ -735,6 +762,7 @@ export type TeamUpdateWithoutSkillsInput = {
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutSkillsInput = { export type TeamUncheckedUpdateWithoutSkillsInput = {
@@ -753,6 +781,7 @@ export type TeamUncheckedUpdateWithoutSkillsInput = {
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutMembersInput = { export type TeamCreateWithoutMembersInput = {
@@ -771,6 +800,7 @@ export type TeamCreateWithoutMembersInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutMembersInput = { export type TeamUncheckedCreateWithoutMembersInput = {
@@ -789,6 +819,7 @@ export type TeamUncheckedCreateWithoutMembersInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutMembersInput = { export type TeamCreateOrConnectWithoutMembersInput = {
@@ -823,6 +854,7 @@ export type TeamUpdateWithoutMembersInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutMembersInput = { export type TeamUncheckedUpdateWithoutMembersInput = {
@@ -841,6 +873,7 @@ export type TeamUncheckedUpdateWithoutMembersInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutProjectsInput = { export type TeamCreateWithoutProjectsInput = {
@@ -859,6 +892,7 @@ export type TeamCreateWithoutProjectsInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutProjectsInput = { export type TeamUncheckedCreateWithoutProjectsInput = {
@@ -877,6 +911,7 @@ export type TeamUncheckedCreateWithoutProjectsInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutProjectsInput = { export type TeamCreateOrConnectWithoutProjectsInput = {
@@ -911,6 +946,7 @@ export type TeamUpdateWithoutProjectsInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutProjectsInput = { export type TeamUncheckedUpdateWithoutProjectsInput = {
@@ -929,6 +965,7 @@ export type TeamUncheckedUpdateWithoutProjectsInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutRootFolderInput = { export type TeamCreateWithoutRootFolderInput = {
@@ -947,6 +984,7 @@ export type TeamCreateWithoutRootFolderInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutRootFolderInput = { export type TeamUncheckedCreateWithoutRootFolderInput = {
@@ -965,6 +1003,7 @@ export type TeamUncheckedCreateWithoutRootFolderInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutRootFolderInput = { export type TeamCreateOrConnectWithoutRootFolderInput = {
@@ -999,6 +1038,7 @@ export type TeamUpdateWithoutRootFolderInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutRootFolderInput = { export type TeamUncheckedUpdateWithoutRootFolderInput = {
@@ -1017,6 +1057,7 @@ export type TeamUncheckedUpdateWithoutRootFolderInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutInvitesInput = { export type TeamCreateWithoutInvitesInput = {
@@ -1035,6 +1076,7 @@ export type TeamCreateWithoutInvitesInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutInvitesInput = { export type TeamUncheckedCreateWithoutInvitesInput = {
@@ -1053,6 +1095,7 @@ export type TeamUncheckedCreateWithoutInvitesInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutInvitesInput = { export type TeamCreateOrConnectWithoutInvitesInput = {
@@ -1087,6 +1130,7 @@ export type TeamUpdateWithoutInvitesInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutInvitesInput = { export type TeamUncheckedUpdateWithoutInvitesInput = {
@@ -1105,6 +1149,7 @@ export type TeamUncheckedUpdateWithoutInvitesInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutMetadataFieldsInput = { export type TeamCreateWithoutMetadataFieldsInput = {
@@ -1123,6 +1168,7 @@ export type TeamCreateWithoutMetadataFieldsInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutMetadataFieldsInput = { export type TeamUncheckedCreateWithoutMetadataFieldsInput = {
@@ -1141,6 +1187,7 @@ export type TeamUncheckedCreateWithoutMetadataFieldsInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutMetadataFieldsInput = { export type TeamCreateOrConnectWithoutMetadataFieldsInput = {
@@ -1175,6 +1222,7 @@ export type TeamUpdateWithoutMetadataFieldsInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutMetadataFieldsInput = { export type TeamUncheckedUpdateWithoutMetadataFieldsInput = {
@@ -1193,6 +1241,7 @@ export type TeamUncheckedUpdateWithoutMetadataFieldsInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutNotificationsInput = { export type TeamCreateWithoutNotificationsInput = {
@@ -1211,6 +1260,7 @@ export type TeamCreateWithoutNotificationsInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutNotificationsInput = { export type TeamUncheckedCreateWithoutNotificationsInput = {
@@ -1229,6 +1279,7 @@ export type TeamUncheckedCreateWithoutNotificationsInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutNotificationsInput = { export type TeamCreateOrConnectWithoutNotificationsInput = {
@@ -1263,6 +1314,7 @@ export type TeamUpdateWithoutNotificationsInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutNotificationsInput = { export type TeamUncheckedUpdateWithoutNotificationsInput = {
@@ -1281,6 +1333,7 @@ export type TeamUncheckedUpdateWithoutNotificationsInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutAgentsInput = { export type TeamCreateWithoutAgentsInput = {
@@ -1299,6 +1352,7 @@ export type TeamCreateWithoutAgentsInput = {
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutAgentsInput = { export type TeamUncheckedCreateWithoutAgentsInput = {
@@ -1317,6 +1371,7 @@ export type TeamUncheckedCreateWithoutAgentsInput = {
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutAgentsInput = { export type TeamCreateOrConnectWithoutAgentsInput = {
@@ -1351,6 +1406,7 @@ export type TeamUpdateWithoutAgentsInput = {
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutAgentsInput = { export type TeamUncheckedUpdateWithoutAgentsInput = {
@@ -1369,6 +1425,7 @@ export type TeamUncheckedUpdateWithoutAgentsInput = {
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutUserMetadataInput = { export type TeamCreateWithoutUserMetadataInput = {
@@ -1387,6 +1444,7 @@ export type TeamCreateWithoutUserMetadataInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutUserMetadataInput = { export type TeamUncheckedCreateWithoutUserMetadataInput = {
@@ -1405,6 +1463,7 @@ export type TeamUncheckedCreateWithoutUserMetadataInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutUserMetadataInput = { export type TeamCreateOrConnectWithoutUserMetadataInput = {
@@ -1439,6 +1498,7 @@ export type TeamUpdateWithoutUserMetadataInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutUserMetadataInput = { export type TeamUncheckedUpdateWithoutUserMetadataInput = {
@@ -1457,6 +1517,7 @@ export type TeamUncheckedUpdateWithoutUserMetadataInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
} }
export type TeamCreateWithoutProvidersInput = { export type TeamCreateWithoutProvidersInput = {
@@ -1475,6 +1536,7 @@ export type TeamCreateWithoutProvidersInput = {
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
} }
export type TeamUncheckedCreateWithoutProvidersInput = { export type TeamUncheckedCreateWithoutProvidersInput = {
@@ -1493,6 +1555,7 @@ export type TeamUncheckedCreateWithoutProvidersInput = {
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
} }
export type TeamCreateOrConnectWithoutProvidersInput = { export type TeamCreateOrConnectWithoutProvidersInput = {
@@ -1527,6 +1590,7 @@ export type TeamUpdateWithoutProvidersInput = {
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
} }
export type TeamUncheckedUpdateWithoutProvidersInput = { export type TeamUncheckedUpdateWithoutProvidersInput = {
@@ -1545,6 +1609,99 @@ export type TeamUncheckedUpdateWithoutProvidersInput = {
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
}
export type TeamCreateWithoutAiUsagesInput = {
id?: string
name: string
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
createdAt?: Date | string
updatedAt?: Date | string
rootFolder?: Prisma.AssetCreateNestedOneWithoutTeamRootFolderInput
members?: Prisma.TeamMemberCreateNestedManyWithoutTeamInput
projects?: Prisma.ProjectCreateNestedManyWithoutTeamInput
metadataFields?: Prisma.MetadataFieldCreateNestedManyWithoutTeamInput
invites?: Prisma.InviteCreateNestedManyWithoutTeamInput
notifications?: Prisma.NotificationCreateNestedManyWithoutTeamInput
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
}
export type TeamUncheckedCreateWithoutAiUsagesInput = {
id?: string
name: string
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
createdAt?: Date | string
updatedAt?: Date | string
rootFolderId?: string | null
members?: Prisma.TeamMemberUncheckedCreateNestedManyWithoutTeamInput
projects?: Prisma.ProjectUncheckedCreateNestedManyWithoutTeamInput
metadataFields?: Prisma.MetadataFieldUncheckedCreateNestedManyWithoutTeamInput
invites?: Prisma.InviteUncheckedCreateNestedManyWithoutTeamInput
notifications?: Prisma.NotificationUncheckedCreateNestedManyWithoutTeamInput
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
}
export type TeamCreateOrConnectWithoutAiUsagesInput = {
where: Prisma.TeamWhereUniqueInput
create: Prisma.XOR<Prisma.TeamCreateWithoutAiUsagesInput, Prisma.TeamUncheckedCreateWithoutAiUsagesInput>
}
export type TeamUpsertWithoutAiUsagesInput = {
update: Prisma.XOR<Prisma.TeamUpdateWithoutAiUsagesInput, Prisma.TeamUncheckedUpdateWithoutAiUsagesInput>
create: Prisma.XOR<Prisma.TeamCreateWithoutAiUsagesInput, Prisma.TeamUncheckedCreateWithoutAiUsagesInput>
where?: Prisma.TeamWhereInput
}
export type TeamUpdateToOneWithWhereWithoutAiUsagesInput = {
where?: Prisma.TeamWhereInput
data: Prisma.XOR<Prisma.TeamUpdateWithoutAiUsagesInput, Prisma.TeamUncheckedUpdateWithoutAiUsagesInput>
}
export type TeamUpdateWithoutAiUsagesInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
rootFolder?: Prisma.AssetUpdateOneWithoutTeamRootFolderNestedInput
members?: Prisma.TeamMemberUpdateManyWithoutTeamNestedInput
projects?: Prisma.ProjectUpdateManyWithoutTeamNestedInput
metadataFields?: Prisma.MetadataFieldUpdateManyWithoutTeamNestedInput
invites?: Prisma.InviteUpdateManyWithoutTeamNestedInput
notifications?: Prisma.NotificationUpdateManyWithoutTeamNestedInput
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
}
export type TeamUncheckedUpdateWithoutAiUsagesInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
name?: Prisma.StringFieldUpdateOperationsInput | string
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
rootFolderId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
members?: Prisma.TeamMemberUncheckedUpdateManyWithoutTeamNestedInput
projects?: Prisma.ProjectUncheckedUpdateManyWithoutTeamNestedInput
metadataFields?: Prisma.MetadataFieldUncheckedUpdateManyWithoutTeamNestedInput
invites?: Prisma.InviteUncheckedUpdateManyWithoutTeamNestedInput
notifications?: Prisma.NotificationUncheckedUpdateManyWithoutTeamNestedInput
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
} }
@@ -1562,6 +1719,7 @@ export type TeamCountOutputType = {
providers: number providers: number
skills: number skills: number
agents: number agents: number
aiUsages: number
} }
export type TeamCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = { export type TeamCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
@@ -1574,6 +1732,7 @@ export type TeamCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.I
providers?: boolean | TeamCountOutputTypeCountProvidersArgs providers?: boolean | TeamCountOutputTypeCountProvidersArgs
skills?: boolean | TeamCountOutputTypeCountSkillsArgs skills?: boolean | TeamCountOutputTypeCountSkillsArgs
agents?: boolean | TeamCountOutputTypeCountAgentsArgs agents?: boolean | TeamCountOutputTypeCountAgentsArgs
aiUsages?: boolean | TeamCountOutputTypeCountAiUsagesArgs
} }
/** /**
@@ -1649,6 +1808,13 @@ export type TeamCountOutputTypeCountAgentsArgs<ExtArgs extends runtime.Types.Ext
where?: Prisma.AgentWhereInput where?: Prisma.AgentWhereInput
} }
/**
* TeamCountOutputType without action
*/
export type TeamCountOutputTypeCountAiUsagesArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
where?: Prisma.AiUsageWhereInput
}
export type TeamSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{ export type TeamSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
id?: boolean id?: boolean
@@ -1668,6 +1834,7 @@ export type TeamSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = r
skills?: boolean | Prisma.Team$skillsArgs<ExtArgs> skills?: boolean | Prisma.Team$skillsArgs<ExtArgs>
sandbox?: boolean | Prisma.Team$sandboxArgs<ExtArgs> sandbox?: boolean | Prisma.Team$sandboxArgs<ExtArgs>
agents?: boolean | Prisma.Team$agentsArgs<ExtArgs> agents?: boolean | Prisma.Team$agentsArgs<ExtArgs>
aiUsages?: boolean | Prisma.Team$aiUsagesArgs<ExtArgs>
_count?: boolean | Prisma.TeamCountOutputTypeDefaultArgs<ExtArgs> _count?: boolean | Prisma.TeamCountOutputTypeDefaultArgs<ExtArgs>
}, ExtArgs["result"]["team"]> }, ExtArgs["result"]["team"]>
@@ -1713,6 +1880,7 @@ export type TeamInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs =
skills?: boolean | Prisma.Team$skillsArgs<ExtArgs> skills?: boolean | Prisma.Team$skillsArgs<ExtArgs>
sandbox?: boolean | Prisma.Team$sandboxArgs<ExtArgs> sandbox?: boolean | Prisma.Team$sandboxArgs<ExtArgs>
agents?: boolean | Prisma.Team$agentsArgs<ExtArgs> agents?: boolean | Prisma.Team$agentsArgs<ExtArgs>
aiUsages?: boolean | Prisma.Team$aiUsagesArgs<ExtArgs>
_count?: boolean | Prisma.TeamCountOutputTypeDefaultArgs<ExtArgs> _count?: boolean | Prisma.TeamCountOutputTypeDefaultArgs<ExtArgs>
} }
export type TeamIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = { export type TeamIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
@@ -1736,6 +1904,7 @@ export type $TeamPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs =
skills: Prisma.$SkillPayload<ExtArgs>[] skills: Prisma.$SkillPayload<ExtArgs>[]
sandbox: Prisma.$SandboxPayload<ExtArgs> | null sandbox: Prisma.$SandboxPayload<ExtArgs> | null
agents: Prisma.$AgentPayload<ExtArgs>[] agents: Prisma.$AgentPayload<ExtArgs>[]
aiUsages: Prisma.$AiUsagePayload<ExtArgs>[]
} }
scalars: runtime.Types.Extensions.GetPayloadResult<{ scalars: runtime.Types.Extensions.GetPayloadResult<{
id: string id: string
@@ -2152,6 +2321,7 @@ export interface Prisma__TeamClient<T, Null = never, ExtArgs extends runtime.Typ
skills<T extends Prisma.Team$skillsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$skillsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$SkillPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null> skills<T extends Prisma.Team$skillsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$skillsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$SkillPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
sandbox<T extends Prisma.Team$sandboxArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$sandboxArgs<ExtArgs>>): Prisma.Prisma__SandboxClient<runtime.Types.Result.GetResult<Prisma.$SandboxPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions> sandbox<T extends Prisma.Team$sandboxArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$sandboxArgs<ExtArgs>>): Prisma.Prisma__SandboxClient<runtime.Types.Result.GetResult<Prisma.$SandboxPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
agents<T extends Prisma.Team$agentsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$agentsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null> agents<T extends Prisma.Team$agentsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$agentsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
aiUsages<T extends Prisma.Team$aiUsagesArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$aiUsagesArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AiUsagePayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
/** /**
* 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.
@@ -2841,6 +3011,30 @@ export type Team$agentsArgs<ExtArgs extends runtime.Types.Extensions.InternalArg
distinct?: Prisma.AgentScalarFieldEnum | Prisma.AgentScalarFieldEnum[] distinct?: Prisma.AgentScalarFieldEnum | Prisma.AgentScalarFieldEnum[]
} }
/**
* Team.aiUsages
*/
export type Team$aiUsagesArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
/**
* Select specific fields to fetch from the AiUsage
*/
select?: Prisma.AiUsageSelect<ExtArgs> | null
/**
* Omit specific fields from the AiUsage
*/
omit?: Prisma.AiUsageOmit<ExtArgs> | null
/**
* Choose, which related nodes to fetch as well
*/
include?: Prisma.AiUsageInclude<ExtArgs> | null
where?: Prisma.AiUsageWhereInput
orderBy?: Prisma.AiUsageOrderByWithRelationInput | Prisma.AiUsageOrderByWithRelationInput[]
cursor?: Prisma.AiUsageWhereUniqueInput
take?: number
skip?: number
distinct?: Prisma.AiUsageScalarFieldEnum | Prisma.AiUsageScalarFieldEnum[]
}
/** /**
* Team without action * Team without action
*/ */
+268
View File
@@ -245,6 +245,7 @@ export type UserWhereInput = {
collections?: Prisma.CollectionListRelationFilter collections?: Prisma.CollectionListRelationFilter
shareLinks?: Prisma.ShareLinkListRelationFilter shareLinks?: Prisma.ShareLinkListRelationFilter
apiTokens?: Prisma.ApiTokenListRelationFilter apiTokens?: Prisma.ApiTokenListRelationFilter
aiUsages?: Prisma.AiUsageListRelationFilter
} }
export type UserOrderByWithRelationInput = { export type UserOrderByWithRelationInput = {
@@ -276,6 +277,7 @@ export type UserOrderByWithRelationInput = {
collections?: Prisma.CollectionOrderByRelationAggregateInput collections?: Prisma.CollectionOrderByRelationAggregateInput
shareLinks?: Prisma.ShareLinkOrderByRelationAggregateInput shareLinks?: Prisma.ShareLinkOrderByRelationAggregateInput
apiTokens?: Prisma.ApiTokenOrderByRelationAggregateInput apiTokens?: Prisma.ApiTokenOrderByRelationAggregateInput
aiUsages?: Prisma.AiUsageOrderByRelationAggregateInput
} }
export type UserWhereUniqueInput = Prisma.AtLeast<{ export type UserWhereUniqueInput = Prisma.AtLeast<{
@@ -310,6 +312,7 @@ export type UserWhereUniqueInput = Prisma.AtLeast<{
collections?: Prisma.CollectionListRelationFilter collections?: Prisma.CollectionListRelationFilter
shareLinks?: Prisma.ShareLinkListRelationFilter shareLinks?: Prisma.ShareLinkListRelationFilter
apiTokens?: Prisma.ApiTokenListRelationFilter apiTokens?: Prisma.ApiTokenListRelationFilter
aiUsages?: Prisma.AiUsageListRelationFilter
}, "id" | "email"> }, "id" | "email">
export type UserOrderByWithAggregationInput = { export type UserOrderByWithAggregationInput = {
@@ -375,6 +378,7 @@ export type UserCreateInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateInput = { export type UserUncheckedCreateInput = {
@@ -406,6 +410,7 @@ export type UserUncheckedCreateInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserUpdateInput = { export type UserUpdateInput = {
@@ -437,6 +442,7 @@ export type UserUpdateInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateInput = { export type UserUncheckedUpdateInput = {
@@ -468,6 +474,7 @@ export type UserUncheckedUpdateInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateManyInput = { export type UserCreateManyInput = {
@@ -838,6 +845,22 @@ export type UserUpdateOneRequiredWithoutApiTokensNestedInput = {
update?: Prisma.XOR<Prisma.XOR<Prisma.UserUpdateToOneWithWhereWithoutApiTokensInput, Prisma.UserUpdateWithoutApiTokensInput>, Prisma.UserUncheckedUpdateWithoutApiTokensInput> update?: Prisma.XOR<Prisma.XOR<Prisma.UserUpdateToOneWithWhereWithoutApiTokensInput, Prisma.UserUpdateWithoutApiTokensInput>, Prisma.UserUncheckedUpdateWithoutApiTokensInput>
} }
export type UserCreateNestedOneWithoutAiUsagesInput = {
create?: Prisma.XOR<Prisma.UserCreateWithoutAiUsagesInput, Prisma.UserUncheckedCreateWithoutAiUsagesInput>
connectOrCreate?: Prisma.UserCreateOrConnectWithoutAiUsagesInput
connect?: Prisma.UserWhereUniqueInput
}
export type UserUpdateOneWithoutAiUsagesNestedInput = {
create?: Prisma.XOR<Prisma.UserCreateWithoutAiUsagesInput, Prisma.UserUncheckedCreateWithoutAiUsagesInput>
connectOrCreate?: Prisma.UserCreateOrConnectWithoutAiUsagesInput
upsert?: Prisma.UserUpsertWithoutAiUsagesInput
disconnect?: Prisma.UserWhereInput | boolean
delete?: Prisma.UserWhereInput | boolean
connect?: Prisma.UserWhereUniqueInput
update?: Prisma.XOR<Prisma.XOR<Prisma.UserUpdateToOneWithWhereWithoutAiUsagesInput, Prisma.UserUpdateWithoutAiUsagesInput>, Prisma.UserUncheckedUpdateWithoutAiUsagesInput>
}
export type UserCreateWithoutSessionsInput = { export type UserCreateWithoutSessionsInput = {
id?: string id?: string
type?: $Enums.UserType type?: $Enums.UserType
@@ -866,6 +889,7 @@ export type UserCreateWithoutSessionsInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutSessionsInput = { export type UserUncheckedCreateWithoutSessionsInput = {
@@ -896,6 +920,7 @@ export type UserUncheckedCreateWithoutSessionsInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutSessionsInput = { export type UserCreateOrConnectWithoutSessionsInput = {
@@ -942,6 +967,7 @@ export type UserUpdateWithoutSessionsInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutSessionsInput = { export type UserUncheckedUpdateWithoutSessionsInput = {
@@ -972,6 +998,7 @@ export type UserUncheckedUpdateWithoutSessionsInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutAccountsInput = { export type UserCreateWithoutAccountsInput = {
@@ -1002,6 +1029,7 @@ export type UserCreateWithoutAccountsInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutAccountsInput = { export type UserUncheckedCreateWithoutAccountsInput = {
@@ -1032,6 +1060,7 @@ export type UserUncheckedCreateWithoutAccountsInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutAccountsInput = { export type UserCreateOrConnectWithoutAccountsInput = {
@@ -1078,6 +1107,7 @@ export type UserUpdateWithoutAccountsInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutAccountsInput = { export type UserUncheckedUpdateWithoutAccountsInput = {
@@ -1108,6 +1138,7 @@ export type UserUncheckedUpdateWithoutAccountsInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutAuthTokensInput = { export type UserCreateWithoutAuthTokensInput = {
@@ -1138,6 +1169,7 @@ export type UserCreateWithoutAuthTokensInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutAuthTokensInput = { export type UserUncheckedCreateWithoutAuthTokensInput = {
@@ -1168,6 +1200,7 @@ export type UserUncheckedCreateWithoutAuthTokensInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutAuthTokensInput = { export type UserCreateOrConnectWithoutAuthTokensInput = {
@@ -1214,6 +1247,7 @@ export type UserUpdateWithoutAuthTokensInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutAuthTokensInput = { export type UserUncheckedUpdateWithoutAuthTokensInput = {
@@ -1244,6 +1278,7 @@ export type UserUncheckedUpdateWithoutAuthTokensInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutTeamMembersInput = { export type UserCreateWithoutTeamMembersInput = {
@@ -1274,6 +1309,7 @@ export type UserCreateWithoutTeamMembersInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutTeamMembersInput = { export type UserUncheckedCreateWithoutTeamMembersInput = {
@@ -1304,6 +1340,7 @@ export type UserUncheckedCreateWithoutTeamMembersInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutTeamMembersInput = { export type UserCreateOrConnectWithoutTeamMembersInput = {
@@ -1350,6 +1387,7 @@ export type UserUpdateWithoutTeamMembersInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutTeamMembersInput = { export type UserUncheckedUpdateWithoutTeamMembersInput = {
@@ -1380,6 +1418,7 @@ export type UserUncheckedUpdateWithoutTeamMembersInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutShareLinksInput = { export type UserCreateWithoutShareLinksInput = {
@@ -1410,6 +1449,7 @@ export type UserCreateWithoutShareLinksInput = {
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutUserInput userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutUserInput
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutShareLinksInput = { export type UserUncheckedCreateWithoutShareLinksInput = {
@@ -1440,6 +1480,7 @@ export type UserUncheckedCreateWithoutShareLinksInput = {
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutUserInput userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutUserInput
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutShareLinksInput = { export type UserCreateOrConnectWithoutShareLinksInput = {
@@ -1486,6 +1527,7 @@ export type UserUpdateWithoutShareLinksInput = {
userMetadata?: Prisma.UserMetadataUpdateManyWithoutUserNestedInput userMetadata?: Prisma.UserMetadataUpdateManyWithoutUserNestedInput
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutShareLinksInput = { export type UserUncheckedUpdateWithoutShareLinksInput = {
@@ -1516,6 +1558,7 @@ export type UserUncheckedUpdateWithoutShareLinksInput = {
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutUserNestedInput userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutUserNestedInput
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutAssetsInput = { export type UserCreateWithoutAssetsInput = {
@@ -1546,6 +1589,7 @@ export type UserCreateWithoutAssetsInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutAssetsInput = { export type UserUncheckedCreateWithoutAssetsInput = {
@@ -1576,6 +1620,7 @@ export type UserUncheckedCreateWithoutAssetsInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutAssetsInput = { export type UserCreateOrConnectWithoutAssetsInput = {
@@ -1622,6 +1667,7 @@ export type UserUpdateWithoutAssetsInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutAssetsInput = { export type UserUncheckedUpdateWithoutAssetsInput = {
@@ -1652,6 +1698,7 @@ export type UserUncheckedUpdateWithoutAssetsInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutCommentsInput = { export type UserCreateWithoutCommentsInput = {
@@ -1682,6 +1729,7 @@ export type UserCreateWithoutCommentsInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutCommentsInput = { export type UserUncheckedCreateWithoutCommentsInput = {
@@ -1712,6 +1760,7 @@ export type UserUncheckedCreateWithoutCommentsInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutCommentsInput = { export type UserCreateOrConnectWithoutCommentsInput = {
@@ -1747,6 +1796,7 @@ export type UserCreateWithoutCompletionChangedCommentsInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutCompletionChangedCommentsInput = { export type UserUncheckedCreateWithoutCompletionChangedCommentsInput = {
@@ -1777,6 +1827,7 @@ export type UserUncheckedCreateWithoutCompletionChangedCommentsInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutCompletionChangedCommentsInput = { export type UserCreateOrConnectWithoutCompletionChangedCommentsInput = {
@@ -1823,6 +1874,7 @@ export type UserUpdateWithoutCommentsInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutCommentsInput = { export type UserUncheckedUpdateWithoutCommentsInput = {
@@ -1853,6 +1905,7 @@ export type UserUncheckedUpdateWithoutCommentsInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserUpsertWithoutCompletionChangedCommentsInput = { export type UserUpsertWithoutCompletionChangedCommentsInput = {
@@ -1894,6 +1947,7 @@ export type UserUpdateWithoutCompletionChangedCommentsInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutCompletionChangedCommentsInput = { export type UserUncheckedUpdateWithoutCompletionChangedCommentsInput = {
@@ -1924,6 +1978,7 @@ export type UserUncheckedUpdateWithoutCompletionChangedCommentsInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutCreatedInvitesInput = { export type UserCreateWithoutCreatedInvitesInput = {
@@ -1954,6 +2009,7 @@ export type UserCreateWithoutCreatedInvitesInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutCreatedInvitesInput = { export type UserUncheckedCreateWithoutCreatedInvitesInput = {
@@ -1984,6 +2040,7 @@ export type UserUncheckedCreateWithoutCreatedInvitesInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutCreatedInvitesInput = { export type UserCreateOrConnectWithoutCreatedInvitesInput = {
@@ -2030,6 +2087,7 @@ export type UserUpdateWithoutCreatedInvitesInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutCreatedInvitesInput = { export type UserUncheckedUpdateWithoutCreatedInvitesInput = {
@@ -2060,6 +2118,7 @@ export type UserUncheckedUpdateWithoutCreatedInvitesInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutCreatedNotificationsInput = { export type UserCreateWithoutCreatedNotificationsInput = {
@@ -2090,6 +2149,7 @@ export type UserCreateWithoutCreatedNotificationsInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutCreatedNotificationsInput = { export type UserUncheckedCreateWithoutCreatedNotificationsInput = {
@@ -2120,6 +2180,7 @@ export type UserUncheckedCreateWithoutCreatedNotificationsInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutCreatedNotificationsInput = { export type UserCreateOrConnectWithoutCreatedNotificationsInput = {
@@ -2155,6 +2216,7 @@ export type UserCreateWithoutNotificationsInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutNotificationsInput = { export type UserUncheckedCreateWithoutNotificationsInput = {
@@ -2185,6 +2247,7 @@ export type UserUncheckedCreateWithoutNotificationsInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutNotificationsInput = { export type UserCreateOrConnectWithoutNotificationsInput = {
@@ -2231,6 +2294,7 @@ export type UserUpdateWithoutCreatedNotificationsInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutCreatedNotificationsInput = { export type UserUncheckedUpdateWithoutCreatedNotificationsInput = {
@@ -2261,6 +2325,7 @@ export type UserUncheckedUpdateWithoutCreatedNotificationsInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserUpsertWithoutNotificationsInput = { export type UserUpsertWithoutNotificationsInput = {
@@ -2302,6 +2367,7 @@ export type UserUpdateWithoutNotificationsInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutNotificationsInput = { export type UserUncheckedUpdateWithoutNotificationsInput = {
@@ -2332,6 +2398,7 @@ export type UserUncheckedUpdateWithoutNotificationsInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutTasksInput = { export type UserCreateWithoutTasksInput = {
@@ -2362,6 +2429,7 @@ export type UserCreateWithoutTasksInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutTasksInput = { export type UserUncheckedCreateWithoutTasksInput = {
@@ -2392,6 +2460,7 @@ export type UserUncheckedCreateWithoutTasksInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutTasksInput = { export type UserCreateOrConnectWithoutTasksInput = {
@@ -2438,6 +2507,7 @@ export type UserUpdateWithoutTasksInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutTasksInput = { export type UserUncheckedUpdateWithoutTasksInput = {
@@ -2468,6 +2538,7 @@ export type UserUncheckedUpdateWithoutTasksInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutAgentInput = { export type UserCreateWithoutAgentInput = {
@@ -2498,6 +2569,7 @@ export type UserCreateWithoutAgentInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutAgentInput = { export type UserUncheckedCreateWithoutAgentInput = {
@@ -2528,6 +2600,7 @@ export type UserUncheckedCreateWithoutAgentInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutAgentInput = { export type UserCreateOrConnectWithoutAgentInput = {
@@ -2574,6 +2647,7 @@ export type UserUpdateWithoutAgentInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutAgentInput = { export type UserUncheckedUpdateWithoutAgentInput = {
@@ -2604,6 +2678,7 @@ export type UserUncheckedUpdateWithoutAgentInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutAgentSessionsInput = { export type UserCreateWithoutAgentSessionsInput = {
@@ -2634,6 +2709,7 @@ export type UserCreateWithoutAgentSessionsInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutAgentSessionsInput = { export type UserUncheckedCreateWithoutAgentSessionsInput = {
@@ -2664,6 +2740,7 @@ export type UserUncheckedCreateWithoutAgentSessionsInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutAgentSessionsInput = { export type UserCreateOrConnectWithoutAgentSessionsInput = {
@@ -2710,6 +2787,7 @@ export type UserUpdateWithoutAgentSessionsInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutAgentSessionsInput = { export type UserUncheckedUpdateWithoutAgentSessionsInput = {
@@ -2740,6 +2818,7 @@ export type UserUncheckedUpdateWithoutAgentSessionsInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutUserMetadataInput = { export type UserCreateWithoutUserMetadataInput = {
@@ -2770,6 +2849,7 @@ export type UserCreateWithoutUserMetadataInput = {
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutUserMetadataInput = { export type UserUncheckedCreateWithoutUserMetadataInput = {
@@ -2800,6 +2880,7 @@ export type UserUncheckedCreateWithoutUserMetadataInput = {
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutUserMetadataInput = { export type UserCreateOrConnectWithoutUserMetadataInput = {
@@ -2846,6 +2927,7 @@ export type UserUpdateWithoutUserMetadataInput = {
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutUserMetadataInput = { export type UserUncheckedUpdateWithoutUserMetadataInput = {
@@ -2876,6 +2958,7 @@ export type UserUncheckedUpdateWithoutUserMetadataInput = {
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutCollectionsInput = { export type UserCreateWithoutCollectionsInput = {
@@ -2906,6 +2989,7 @@ export type UserCreateWithoutCollectionsInput = {
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutUserInput userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutUserInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutCollectionsInput = { export type UserUncheckedCreateWithoutCollectionsInput = {
@@ -2936,6 +3020,7 @@ export type UserUncheckedCreateWithoutCollectionsInput = {
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutUserInput userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutUserInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutCollectionsInput = { export type UserCreateOrConnectWithoutCollectionsInput = {
@@ -2982,6 +3067,7 @@ export type UserUpdateWithoutCollectionsInput = {
userMetadata?: Prisma.UserMetadataUpdateManyWithoutUserNestedInput userMetadata?: Prisma.UserMetadataUpdateManyWithoutUserNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutCollectionsInput = { export type UserUncheckedUpdateWithoutCollectionsInput = {
@@ -3012,6 +3098,7 @@ export type UserUncheckedUpdateWithoutCollectionsInput = {
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutUserNestedInput userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutUserNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
} }
export type UserCreateWithoutApiTokensInput = { export type UserCreateWithoutApiTokensInput = {
@@ -3042,6 +3129,7 @@ export type UserCreateWithoutApiTokensInput = {
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutUserInput userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutUserInput
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutUserInput
} }
export type UserUncheckedCreateWithoutApiTokensInput = { export type UserUncheckedCreateWithoutApiTokensInput = {
@@ -3072,6 +3160,7 @@ export type UserUncheckedCreateWithoutApiTokensInput = {
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutUserInput userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutUserInput
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutUserInput
} }
export type UserCreateOrConnectWithoutApiTokensInput = { export type UserCreateOrConnectWithoutApiTokensInput = {
@@ -3118,6 +3207,7 @@ export type UserUpdateWithoutApiTokensInput = {
userMetadata?: Prisma.UserMetadataUpdateManyWithoutUserNestedInput userMetadata?: Prisma.UserMetadataUpdateManyWithoutUserNestedInput
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
aiUsages?: Prisma.AiUsageUpdateManyWithoutUserNestedInput
} }
export type UserUncheckedUpdateWithoutApiTokensInput = { export type UserUncheckedUpdateWithoutApiTokensInput = {
@@ -3148,6 +3238,147 @@ export type UserUncheckedUpdateWithoutApiTokensInput = {
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutUserNestedInput userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutUserNestedInput
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutUserNestedInput
}
export type UserCreateWithoutAiUsagesInput = {
id?: string
type?: $Enums.UserType
name: string
email: string
emailVerified?: boolean
image?: string | null
password?: string | null
agentSettings?:PrismaJson.AgentSettings | Prisma.NullableJsonNullValueInput
guestEmail?: string | null
createdAt?: Date | string
updatedAt?: Date | string
assets?: Prisma.AssetCreateNestedManyWithoutCreatorInput
authTokens?: Prisma.AuthTokenCreateNestedManyWithoutUserInput
tasks?: Prisma.TaskCreateNestedManyWithoutCreatorInput
teamMembers?: Prisma.TeamMemberCreateNestedManyWithoutUserInput
comments?: Prisma.AssetCommentCreateNestedManyWithoutCreatorInput
completionChangedComments?: Prisma.AssetCommentCreateNestedManyWithoutCompletionLastChangedByInput
createdInvites?: Prisma.InviteCreateNestedManyWithoutInviterInput
createdNotifications?: Prisma.NotificationCreateNestedManyWithoutCreatorInput
notifications?: Prisma.NotificationCreateNestedManyWithoutUserInput
sessions?: Prisma.SessionCreateNestedManyWithoutUserInput
accounts?: Prisma.AccountCreateNestedManyWithoutUserInput
agent?: Prisma.AgentCreateNestedOneWithoutUserInput
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutUserInput
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutUserInput
collections?: Prisma.CollectionCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenCreateNestedManyWithoutUserInput
}
export type UserUncheckedCreateWithoutAiUsagesInput = {
id?: string
type?: $Enums.UserType
name: string
email: string
emailVerified?: boolean
image?: string | null
password?: string | null
agentSettings?:PrismaJson.AgentSettings | Prisma.NullableJsonNullValueInput
guestEmail?: string | null
createdAt?: Date | string
updatedAt?: Date | string
assets?: Prisma.AssetUncheckedCreateNestedManyWithoutCreatorInput
authTokens?: Prisma.AuthTokenUncheckedCreateNestedManyWithoutUserInput
tasks?: Prisma.TaskUncheckedCreateNestedManyWithoutCreatorInput
teamMembers?: Prisma.TeamMemberUncheckedCreateNestedManyWithoutUserInput
comments?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutCreatorInput
completionChangedComments?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutCompletionLastChangedByInput
createdInvites?: Prisma.InviteUncheckedCreateNestedManyWithoutInviterInput
createdNotifications?: Prisma.NotificationUncheckedCreateNestedManyWithoutCreatorInput
notifications?: Prisma.NotificationUncheckedCreateNestedManyWithoutUserInput
sessions?: Prisma.SessionUncheckedCreateNestedManyWithoutUserInput
accounts?: Prisma.AccountUncheckedCreateNestedManyWithoutUserInput
agent?: Prisma.AgentUncheckedCreateNestedOneWithoutUserInput
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutUserInput
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutUserInput
collections?: Prisma.CollectionUncheckedCreateNestedManyWithoutCreatorInput
shareLinks?: Prisma.ShareLinkUncheckedCreateNestedManyWithoutCreatorInput
apiTokens?: Prisma.ApiTokenUncheckedCreateNestedManyWithoutUserInput
}
export type UserCreateOrConnectWithoutAiUsagesInput = {
where: Prisma.UserWhereUniqueInput
create: Prisma.XOR<Prisma.UserCreateWithoutAiUsagesInput, Prisma.UserUncheckedCreateWithoutAiUsagesInput>
}
export type UserUpsertWithoutAiUsagesInput = {
update: Prisma.XOR<Prisma.UserUpdateWithoutAiUsagesInput, Prisma.UserUncheckedUpdateWithoutAiUsagesInput>
create: Prisma.XOR<Prisma.UserCreateWithoutAiUsagesInput, Prisma.UserUncheckedCreateWithoutAiUsagesInput>
where?: Prisma.UserWhereInput
}
export type UserUpdateToOneWithWhereWithoutAiUsagesInput = {
where?: Prisma.UserWhereInput
data: Prisma.XOR<Prisma.UserUpdateWithoutAiUsagesInput, Prisma.UserUncheckedUpdateWithoutAiUsagesInput>
}
export type UserUpdateWithoutAiUsagesInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
type?: Prisma.EnumUserTypeFieldUpdateOperationsInput | $Enums.UserType
name?: Prisma.StringFieldUpdateOperationsInput | string
email?: Prisma.StringFieldUpdateOperationsInput | string
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
agentSettings?:PrismaJson.AgentSettings | Prisma.NullableJsonNullValueInput
guestEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assets?: Prisma.AssetUpdateManyWithoutCreatorNestedInput
authTokens?: Prisma.AuthTokenUpdateManyWithoutUserNestedInput
tasks?: Prisma.TaskUpdateManyWithoutCreatorNestedInput
teamMembers?: Prisma.TeamMemberUpdateManyWithoutUserNestedInput
comments?: Prisma.AssetCommentUpdateManyWithoutCreatorNestedInput
completionChangedComments?: Prisma.AssetCommentUpdateManyWithoutCompletionLastChangedByNestedInput
createdInvites?: Prisma.InviteUpdateManyWithoutInviterNestedInput
createdNotifications?: Prisma.NotificationUpdateManyWithoutCreatorNestedInput
notifications?: Prisma.NotificationUpdateManyWithoutUserNestedInput
sessions?: Prisma.SessionUpdateManyWithoutUserNestedInput
accounts?: Prisma.AccountUpdateManyWithoutUserNestedInput
agent?: Prisma.AgentUpdateOneWithoutUserNestedInput
agentSessions?: Prisma.AgentSessionUpdateManyWithoutUserNestedInput
userMetadata?: Prisma.UserMetadataUpdateManyWithoutUserNestedInput
collections?: Prisma.CollectionUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUpdateManyWithoutUserNestedInput
}
export type UserUncheckedUpdateWithoutAiUsagesInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
type?: Prisma.EnumUserTypeFieldUpdateOperationsInput | $Enums.UserType
name?: Prisma.StringFieldUpdateOperationsInput | string
email?: Prisma.StringFieldUpdateOperationsInput | string
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
agentSettings?:PrismaJson.AgentSettings | Prisma.NullableJsonNullValueInput
guestEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assets?: Prisma.AssetUncheckedUpdateManyWithoutCreatorNestedInput
authTokens?: Prisma.AuthTokenUncheckedUpdateManyWithoutUserNestedInput
tasks?: Prisma.TaskUncheckedUpdateManyWithoutCreatorNestedInput
teamMembers?: Prisma.TeamMemberUncheckedUpdateManyWithoutUserNestedInput
comments?: Prisma.AssetCommentUncheckedUpdateManyWithoutCreatorNestedInput
completionChangedComments?: Prisma.AssetCommentUncheckedUpdateManyWithoutCompletionLastChangedByNestedInput
createdInvites?: Prisma.InviteUncheckedUpdateManyWithoutInviterNestedInput
createdNotifications?: Prisma.NotificationUncheckedUpdateManyWithoutCreatorNestedInput
notifications?: Prisma.NotificationUncheckedUpdateManyWithoutUserNestedInput
sessions?: Prisma.SessionUncheckedUpdateManyWithoutUserNestedInput
accounts?: Prisma.AccountUncheckedUpdateManyWithoutUserNestedInput
agent?: Prisma.AgentUncheckedUpdateOneWithoutUserNestedInput
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutUserNestedInput
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutUserNestedInput
collections?: Prisma.CollectionUncheckedUpdateManyWithoutCreatorNestedInput
shareLinks?: Prisma.ShareLinkUncheckedUpdateManyWithoutCreatorNestedInput
apiTokens?: Prisma.ApiTokenUncheckedUpdateManyWithoutUserNestedInput
} }
@@ -3172,6 +3403,7 @@ export type UserCountOutputType = {
collections: number collections: number
shareLinks: number shareLinks: number
apiTokens: number apiTokens: number
aiUsages: number
} }
export type UserCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = { export type UserCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
@@ -3191,6 +3423,7 @@ export type UserCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.I
collections?: boolean | UserCountOutputTypeCountCollectionsArgs collections?: boolean | UserCountOutputTypeCountCollectionsArgs
shareLinks?: boolean | UserCountOutputTypeCountShareLinksArgs shareLinks?: boolean | UserCountOutputTypeCountShareLinksArgs
apiTokens?: boolean | UserCountOutputTypeCountApiTokensArgs apiTokens?: boolean | UserCountOutputTypeCountApiTokensArgs
aiUsages?: boolean | UserCountOutputTypeCountAiUsagesArgs
} }
/** /**
@@ -3315,6 +3548,13 @@ export type UserCountOutputTypeCountApiTokensArgs<ExtArgs extends runtime.Types.
where?: Prisma.ApiTokenWhereInput where?: Prisma.ApiTokenWhereInput
} }
/**
* UserCountOutputType without action
*/
export type UserCountOutputTypeCountAiUsagesArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
where?: Prisma.AiUsageWhereInput
}
export type UserSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{ export type UserSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
id?: boolean id?: boolean
@@ -3345,6 +3585,7 @@ export type UserSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = r
collections?: boolean | Prisma.User$collectionsArgs<ExtArgs> collections?: boolean | Prisma.User$collectionsArgs<ExtArgs>
shareLinks?: boolean | Prisma.User$shareLinksArgs<ExtArgs> shareLinks?: boolean | Prisma.User$shareLinksArgs<ExtArgs>
apiTokens?: boolean | Prisma.User$apiTokensArgs<ExtArgs> apiTokens?: boolean | Prisma.User$apiTokensArgs<ExtArgs>
aiUsages?: boolean | Prisma.User$aiUsagesArgs<ExtArgs>
_count?: boolean | Prisma.UserCountOutputTypeDefaultArgs<ExtArgs> _count?: boolean | Prisma.UserCountOutputTypeDefaultArgs<ExtArgs>
}, ExtArgs["result"]["user"]> }, ExtArgs["result"]["user"]>
@@ -3409,6 +3650,7 @@ export type UserInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs =
collections?: boolean | Prisma.User$collectionsArgs<ExtArgs> collections?: boolean | Prisma.User$collectionsArgs<ExtArgs>
shareLinks?: boolean | Prisma.User$shareLinksArgs<ExtArgs> shareLinks?: boolean | Prisma.User$shareLinksArgs<ExtArgs>
apiTokens?: boolean | Prisma.User$apiTokensArgs<ExtArgs> apiTokens?: boolean | Prisma.User$apiTokensArgs<ExtArgs>
aiUsages?: boolean | Prisma.User$aiUsagesArgs<ExtArgs>
_count?: boolean | Prisma.UserCountOutputTypeDefaultArgs<ExtArgs> _count?: boolean | Prisma.UserCountOutputTypeDefaultArgs<ExtArgs>
} }
export type UserIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {} export type UserIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {}
@@ -3434,6 +3676,7 @@ export type $UserPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs =
collections: Prisma.$CollectionPayload<ExtArgs>[] collections: Prisma.$CollectionPayload<ExtArgs>[]
shareLinks: Prisma.$ShareLinkPayload<ExtArgs>[] shareLinks: Prisma.$ShareLinkPayload<ExtArgs>[]
apiTokens: Prisma.$ApiTokenPayload<ExtArgs>[] apiTokens: Prisma.$ApiTokenPayload<ExtArgs>[]
aiUsages: Prisma.$AiUsagePayload<ExtArgs>[]
} }
scalars: runtime.Types.Extensions.GetPayloadResult<{ scalars: runtime.Types.Extensions.GetPayloadResult<{
id: string id: string
@@ -3861,6 +4104,7 @@ export interface Prisma__UserClient<T, Null = never, ExtArgs extends runtime.Typ
collections<T extends Prisma.User$collectionsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.User$collectionsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$CollectionPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null> collections<T extends Prisma.User$collectionsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.User$collectionsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$CollectionPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
shareLinks<T extends Prisma.User$shareLinksArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.User$shareLinksArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ShareLinkPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null> shareLinks<T extends Prisma.User$shareLinksArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.User$shareLinksArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ShareLinkPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
apiTokens<T extends Prisma.User$apiTokensArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.User$apiTokensArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ApiTokenPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null> apiTokens<T extends Prisma.User$apiTokensArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.User$apiTokensArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ApiTokenPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
aiUsages<T extends Prisma.User$aiUsagesArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.User$aiUsagesArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AiUsagePayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
/** /**
* 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.
@@ -4696,6 +4940,30 @@ export type User$apiTokensArgs<ExtArgs extends runtime.Types.Extensions.Internal
distinct?: Prisma.ApiTokenScalarFieldEnum | Prisma.ApiTokenScalarFieldEnum[] distinct?: Prisma.ApiTokenScalarFieldEnum | Prisma.ApiTokenScalarFieldEnum[]
} }
/**
* User.aiUsages
*/
export type User$aiUsagesArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
/**
* Select specific fields to fetch from the AiUsage
*/
select?: Prisma.AiUsageSelect<ExtArgs> | null
/**
* Omit specific fields from the AiUsage
*/
omit?: Prisma.AiUsageOmit<ExtArgs> | null
/**
* Choose, which related nodes to fetch as well
*/
include?: Prisma.AiUsageInclude<ExtArgs> | null
where?: Prisma.AiUsageWhereInput
orderBy?: Prisma.AiUsageOrderByWithRelationInput | Prisma.AiUsageOrderByWithRelationInput[]
cursor?: Prisma.AiUsageWhereUniqueInput
take?: number
skip?: number
distinct?: Prisma.AiUsageScalarFieldEnum | Prisma.AiUsageScalarFieldEnum[]
}
/** /**
* User without action * User without action
*/ */
+4 -7
View File
@@ -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 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/dtos", "name": "@shumai/dtos",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+31
View File
@@ -14,3 +14,34 @@ export const aiProviderSettingsSchema = z.object({
}) })
export type AiProviderSettings = z.infer<typeof aiProviderSettingsSchema> export type AiProviderSettings = z.infer<typeof aiProviderSettingsSchema>
export const timeframeSchema = z.enum(['1h', '24h', '7d', '30d'])
export type Timeframe = z.infer<typeof timeframeSchema>
export const getTeamAiUsageQuerySchema = z.object({
timeframe: timeframeSchema.default('30d'),
userId: z.string().optional(),
})
export type GetTeamAiUsageQuery = z.infer<typeof getTeamAiUsageQuerySchema>
export interface AiUsageMetrics {
inputTokens: number
outputTokens: number
cacheReadTokens: number
totalTokens: number
cost: number
}
export interface MemberAiUsageMetrics extends AiUsageMetrics {
userId: string
userName: string
userEmail: string
userImage?: string | null
role: string
}
export interface TeamUsageStatsResponse {
timeframe: Timeframe
team?: AiUsageMetrics
member?: MemberAiUsageMetrics
}
Binary file not shown.
+9 -8
View File
@@ -1,16 +1,17 @@
{ {
"name": "@shumai/e2e", "name": "@shumai/e2e",
"version": "0.2.1", "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)
},
)
+317
View File
@@ -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)
},
)
-790
View File
@@ -1,790 +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 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 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/tableprinter", "name": "@shumai/tableprinter",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/transcode", "name": "@shumai/transcode",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
@@ -469,6 +469,21 @@ describe('Transcode Activities', () => {
).rejects.toThrowError(/Image transcoding failed/) ).rejects.toThrowError(/Image transcoding failed/)
}) })
it('should throw non-retryable ApplicationFailure when transcodeImageActivity fails with ImageMagick error', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
vi.mocked(transcodeService.transcodeImage).mockRejectedValue(
new Error('imagemagick convert failed'),
)
await expect(
transcodeImageActivity({
assetKey: 'i.psd',
filePath: '/tmp/i.psd',
imageSpec: { width: 800, height: 600, quality: 90, format: 'webp' },
}),
).rejects.toThrowError(/Image transcoding failed/)
})
it('should throw non-retryable ApplicationFailure when generateSpriteActivity fails with error', async () => { it('should throw non-retryable ApplicationFailure when generateSpriteActivity fails with error', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found')) vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
vi.mocked(transcodeService.generateSprite).mockRejectedValue(new Error('FFmpeg failed')) vi.mocked(transcodeService.generateSprite).mockRejectedValue(new Error('FFmpeg failed'))
@@ -389,6 +389,9 @@ export async function transcodeImageActivity(
code === 'ENOENT' || code === 'ENOENT' ||
lowerMsg.includes('enoent') || lowerMsg.includes('enoent') ||
lowerMsg.includes('sharp') || lowerMsg.includes('sharp') ||
lowerMsg.includes('imagemagick') ||
lowerMsg.includes('magick') ||
lowerMsg.includes('convert') ||
lowerMsg.includes('spawn') || lowerMsg.includes('spawn') ||
lowerMsg.includes('format') lowerMsg.includes('format')
) { ) {
+14 -3
View File
@@ -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('')
} }
@@ -0,0 +1,265 @@
import { useState } from 'react'
import { useQuery, useQueries } from '@tanstack/react-query'
import type { Timeframe } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { ToggleGroup, ToggleGroupItem } from '@/ui/components/ui/toggle-group'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/ui/components/ui/table'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { Loader2 } from 'lucide-react'
interface AiUsageDashboardProps {
teamId: string
}
export function AiUsageDashboard({ teamId }: AiUsageDashboardProps) {
const [viewMode, setViewMode] = useState<'team' | 'members'>('team')
const [timeframe, setTimeframe] = useState<Timeframe>('1h')
// Query team-level usage
const { data: teamUsageData, isLoading: isTeamLoading } = useQuery({
queryKey: ['teams', teamId, 'ai-usage', timeframe, 'team'],
queryFn: async () => {
const res = await client.api.teams[':teamId']['ai-usage'].$get({
param: { teamId },
query: { timeframe },
})
if (!res.ok) throw new Error('Failed to fetch team AI usage')
return await res.json()
},
enabled: !!teamId && viewMode === 'team',
})
// Query member list for members view
const { data: members, isLoading: isMembersListLoading } = useQuery({
queryKey: ['teams', teamId, 'members'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].members.$get({
param: { teamId },
query: {},
})
if (!res.ok) throw new Error('Failed to fetch team members')
return await res.json()
},
enabled: !!teamId && viewMode === 'members',
})
// Query each member's AI usage in parallel
const memberUsageQueries = useQueries({
queries: (members || []).map((member) => ({
queryKey: ['teams', teamId, 'ai-usage', timeframe, member.id],
queryFn: async () => {
const res = await client.api.teams[':teamId']['ai-usage'].$get({
param: { teamId },
query: { timeframe, userId: member.id },
})
if (!res.ok) throw new Error(`Failed to fetch AI usage for member ${member.id}`)
return await res.json()
},
enabled: !!teamId && viewMode === 'members',
})),
})
const isMembersLoading = isMembersListLoading || memberUsageQueries.some((q) => q.isLoading)
const getInitials = (name?: string) => {
if (!name) return 'U'
const names = name.split(' ')
if (names.length > 1) {
return `${names[0][0]}${names[names.length - 1][0]}`.toUpperCase()
}
return name.substring(0, 2).toUpperCase()
}
const localizeRole = (role?: string) => {
if (!role) return ''
switch (role.toLowerCase()) {
case 'owner':
return m.owner()
case 'editor':
return m.editor()
case 'reviewer':
return m.reviewer()
default:
return role
}
}
const formatTokens = (val?: number) => (val ?? 0).toLocaleString()
const formatCost = (val?: number) => `$${(val ?? 0).toFixed(6)}`
return (
<Card className="border-border/60 shadow-sm">
<CardHeader className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between pb-6">
<div>
<CardTitle className="text-xl font-semibold tracking-tight">{m.ai_usage()}</CardTitle>
<CardDescription className="text-sm text-muted-foreground mt-1">
{m.ai_usage_description()}
</CardDescription>
</div>
<div className="flex flex-wrap items-center gap-3">
<ToggleGroup
type="single"
value={viewMode}
onValueChange={(val) => {
if (val) setViewMode(val as 'team' | 'members')
}}
className="border rounded-lg p-1 bg-muted/30"
>
<ToggleGroupItem value="team" className="px-3 py-1.5 text-xs font-medium">
{m.team_view()}
</ToggleGroupItem>
<ToggleGroupItem value="members" className="px-3 py-1.5 text-xs font-medium">
{m.members_view()}
</ToggleGroupItem>
</ToggleGroup>
<ToggleGroup
type="single"
value={timeframe}
onValueChange={(val) => {
if (val) setTimeframe(val as Timeframe)
}}
className="border rounded-lg p-1 bg-muted/30"
>
<ToggleGroupItem value="1h" className="px-2.5 py-1.5 text-xs font-medium">
1h
</ToggleGroupItem>
<ToggleGroupItem value="24h" className="px-2.5 py-1.5 text-xs font-medium">
24h
</ToggleGroupItem>
<ToggleGroupItem value="7d" className="px-2.5 py-1.5 text-xs font-medium">
7d
</ToggleGroupItem>
<ToggleGroupItem value="30d" className="px-2.5 py-1.5 text-xs font-medium">
30d
</ToggleGroupItem>
</ToggleGroup>
</div>
</CardHeader>
<CardContent>
{viewMode === 'team' ? (
isTeamLoading ? (
<div className="flex h-48 items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>{m.team()}</TableHead>
<TableHead className="text-right">{m.input_tokens()}</TableHead>
<TableHead className="text-right">{m.output_tokens()}</TableHead>
<TableHead className="text-right">{m.cache_read_tokens()}</TableHead>
<TableHead className="text-right">{m.total_tokens()}</TableHead>
<TableHead className="text-right">{m.cost()}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell className="font-medium">{m.team()}</TableCell>
<TableCell className="text-right">
{formatTokens(teamUsageData?.team?.inputTokens)}
</TableCell>
<TableCell className="text-right">
{formatTokens(teamUsageData?.team?.outputTokens)}
</TableCell>
<TableCell className="text-right">
{formatTokens(teamUsageData?.team?.cacheReadTokens)}
</TableCell>
<TableCell className="text-right font-medium">
{formatTokens(teamUsageData?.team?.totalTokens)}
</TableCell>
<TableCell className="text-right font-medium">
{formatCost(teamUsageData?.team?.cost)}
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
)
) : isMembersLoading ? (
<div className="flex h-48 items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>{m.members()}</TableHead>
<TableHead>{m.role()}</TableHead>
<TableHead className="text-right">{m.input_tokens()}</TableHead>
<TableHead className="text-right">{m.output_tokens()}</TableHead>
<TableHead className="text-right">{m.cache_read_tokens()}</TableHead>
<TableHead className="text-right">{m.total_tokens()}</TableHead>
<TableHead className="text-right">{m.cost()}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{(members || []).map((member, idx) => {
const usageResult = memberUsageQueries[idx]?.data?.member
return (
<TableRow key={member.id}>
<TableCell>
<div className="flex items-center gap-3">
<Avatar className="h-8 w-8 rounded-full">
{member.image && (
<AvatarImage
src={member.image}
alt={member.name}
className="object-cover"
/>
)}
<AvatarFallback className="bg-primary/20 text-xs">
{getInitials(member.name)}
</AvatarFallback>
</Avatar>
<div className="flex flex-col">
<span className="text-sm font-medium leading-none">{member.name}</span>
<span className="text-xs text-muted-foreground mt-0.5">
{member.email}
</span>
</div>
</div>
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{localizeRole(member.role)}
</TableCell>
<TableCell className="text-right">
{formatTokens(usageResult?.inputTokens)}
</TableCell>
<TableCell className="text-right">
{formatTokens(usageResult?.outputTokens)}
</TableCell>
<TableCell className="text-right">
{formatTokens(usageResult?.cacheReadTokens)}
</TableCell>
<TableCell className="text-right font-medium">
{formatTokens(usageResult?.totalTokens)}
</TableCell>
<TableCell className="text-right font-medium">
{formatCost(usageResult?.cost)}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
)
}
@@ -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,
@@ -540,6 +541,9 @@ export function FileBrowser({
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId], queryKey: ['search', teamId, assetId],
}) })
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'upload', 'tasks'],
})
// The RPC client returns an object that we cast to the expected type // The RPC client returns an object that we cast to the expected type
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -547,6 +551,9 @@ export function FileBrowser({
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId], queryKey: ['search', teamId, assetId],
}) })
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'upload', 'tasks'],
})
}, },
}) })
@@ -1155,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}
+6 -3
View File
@@ -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())
}
} }
} }
@@ -380,8 +380,8 @@ export function SearchFilterDialog({
</div> </div>
{/* Results Body ported from Demo */} {/* Results Body ported from Demo */}
<ScrollArea className="flex-1 min-h-0 bg-background"> <ScrollArea className="flex-1 min-h-0 bg-background [&>div>div]:block!">
<div className="p-4 md:p-5"> <div className="p-4 md:p-5 min-w-0">
<div className="flex items-center justify-between mb-3 px-1"> <div className="flex items-center justify-between mb-3 px-1">
<span className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground/60 font-mono"> <span className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground/60 font-mono">
{m.search_results()} {m.search_results()}
@@ -394,7 +394,7 @@ export function SearchFilterDialog({
)} )}
</div> </div>
<div className="flex flex-col border border-border rounded-xl divide-y divide-border overflow-hidden"> <div className="flex flex-col border border-border rounded-xl divide-y divide-border overflow-hidden min-w-0">
{!hasActiveCriteria ? ( {!hasActiveCriteria ? (
<div className="py-20 text-center flex flex-col items-center justify-center bg-muted/20 px-4"> <div className="py-20 text-center flex flex-col items-center justify-center bg-muted/20 px-4">
<Search className="w-10 h-10 text-muted-foreground/30 mb-2" /> <Search className="w-10 h-10 text-muted-foreground/30 mb-2" />
@@ -449,7 +449,7 @@ export function SearchFilterDialog({
<div <div
key={record.id} key={record.id}
onClick={() => handleResultClick(record)} onClick={() => handleResultClick(record)}
className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer" className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer min-w-0"
> >
<div <div
className={cn( className={cn(
@@ -471,8 +471,8 @@ export function SearchFilterDialog({
</div> </div>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3 min-w-0">
<div className="truncate"> <div className="flex-1 min-w-0">
<span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate"> <span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate">
{record.name} {record.name}
</span> </span>
@@ -485,7 +485,7 @@ export function SearchFilterDialog({
record.startTime !== null && record.startTime !== null &&
record.endTime !== undefined && record.endTime !== undefined &&
record.endTime !== null && ( record.endTime !== null && (
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block"> <span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block max-w-full truncate">
{m.match_found_at()} {formatTimestamp(record.startTime)} -{' '} {m.match_found_at()} {formatTimestamp(record.startTime)} -{' '}
{formatTimestamp(record.endTime)} {formatTimestamp(record.endTime)}
</span> </span>
@@ -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)

Some files were not shown because too many files have changed in this diff Show More