mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-21 09:20:14 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5636a1b581 | ||
|
|
27af3a315e | ||
|
|
d3bbd42208 | ||
|
|
c3d88bb972 | ||
|
|
a80e9de6cc | ||
|
|
6b5c2d8b23 | ||
|
|
8d19b578e7 | ||
|
|
e20e147445 | ||
|
|
2116f2b1ab | ||
|
|
7889b08008 | ||
|
|
10279d74bc | ||
|
|
985bf0170c | ||
|
|
f04729b4bf | ||
|
|
55026af22e | ||
|
|
b8eddcd854 | ||
|
|
d326a4cab8 | ||
|
|
243a4ab2c5 | ||
|
|
e4c1830e02 | ||
|
|
7b6db5b56c | ||
|
|
63590d5329 | ||
|
|
ccf742e158 | ||
|
|
e55ee3a3f0 | ||
|
|
5e73fcf4aa | ||
|
|
ca5f54b385 |
@@ -197,10 +197,15 @@ The frontend is built with:
|
||||
|
||||
- **Prefer System Colors**: Always prefer using semantic system color design tokens (e.g., `bg-background`, `text-foreground`, `text-sidebar-primary`, `text-muted-foreground`, etc.) over hardcoded color utilities (e.g., `bg-blue-50`, `text-emerald-600`, `bg-emerald-500`). This ensures seamless compatibility with light and dark themes.
|
||||
|
||||
### Route Code-Splitting
|
||||
|
||||
To optimize initial bundle size, all routes must be code-split into `[route].tsx` (lightweight route definition and loaders) and `[route].lazy.tsx` (UI component and heavy imports).
|
||||
|
||||
### Development
|
||||
|
||||
- **Run Dev**: `bun run dev` (Runs on port 3000)
|
||||
|
||||
|
||||
## Testing
|
||||
|
||||
We use **Vitest** for testing (via `bun run test`). **Do not use `bun test`** as it uses Bun's native test runner which is not compatible with this project's test suite.
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
- **Semantic Search**: Find assets based on visual or conceptual search queries using vector embeddings(Gemini Embedding 2).
|
||||
|
||||
> [!NOTE]
|
||||
> **Media Processing & Storage:** When uploading media, Shumai always preserves and stores your original raw file. 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:
|
||||
> * **For Images:** Shumai generates a high-quality WebP proxy at the exact same resolution as your original file for optimized viewing.
|
||||
> * **For Videos:** It generates at least one proxy video (depending on your transcoding settings), alongside a sprite image and a small preview video (capped at 1600 frames) to enable fast timeline scrubbing and lightning-quick previews.
|
||||
|
||||
@@ -120,23 +120,85 @@ mkdir shumai && cd shumai
|
||||
|
||||
#### Step 3: Install Platform-Specific Dependencies
|
||||
|
||||
Make sure the following system dependencies are installed on your host machine before installing Shumai:
|
||||
#### Linux
|
||||
|
||||
| Package | Description | Ubuntu/Debian | Fedora | Arch | macOS |
|
||||
| :------------- | :------------------------------------------------------ | :------------------------------- | :------------------------------- | :-------------------------------------- | :--------------------- |
|
||||
| **ffmpeg** | Media transcoding and metadata extraction | `sudo apt install -y ffmpeg` | `sudo dnf install -y ffmpeg` | `sudo pacman -S --noconfirm ffmpeg` | `brew install ffmpeg` |
|
||||
| **bubblewrap** | Sandboxing environment for secure AI agent execution | `sudo apt install -y bubblewrap` | `sudo dnf install -y bubblewrap` | `sudo pacman -S --noconfirm bubblewrap` | _NOT REQUIRED_ |
|
||||
| **socat** | Bidirectional socket relay for sandbox network bridging | `sudo apt install -y socat` | `sudo dnf install -y socat` | `sudo pacman -S --noconfirm socat` | `brew install socat` |
|
||||
| **ripgrep** | Fast search tool for workspace security policies | `sudo apt install -y ripgrep` | `sudo dnf install -y ripgrep` | `sudo pacman -S --noconfirm ripgrep` | `brew install ripgrep` |
|
||||
Shumai requires the following system packages on Linux:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
- **`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:
|
||||
|
||||
> Ubuntu/Debian
|
||||
```bash
|
||||
sudo apt install -y ffmpeg bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> Fedora
|
||||
```bash
|
||||
sudo dnf install -y ffmpeg bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> Arch Linux
|
||||
```bash
|
||||
sudo pacman -S --noconfirm ffmpeg bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> **Ubuntu 24.04+ Note:** These releases restrict unprivileged user namespaces by default. To allow `bubblewrap` and the sandbox isolation layer to function, disable this restriction:
|
||||
> **Ubuntu 24.04+** restricts unprivileged user namespaces by default. This prevents `anthropic-experimental/sandbox-runtime` from using `bubblewrap` for sandbox isolation.
|
||||
>
|
||||
> To temporarily allow user namespaces:
|
||||
>
|
||||
> ```bash
|
||||
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
> ```
|
||||
>
|
||||
> Alternatively, configure an AppArmor profile that grants user namespace creation (`userns`) privileges to the relevant binaries.
|
||||
> Alternatively, configure an AppArmor profile that grants the required `userns` permission to the relevant binaries.
|
||||
|
||||
---
|
||||
|
||||
#### macOS
|
||||
|
||||
Shumai requires:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
- **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`).
|
||||
|
||||
Install the required packages with Homebrew:
|
||||
|
||||
```bash
|
||||
brew install ffmpeg ripgrep
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Windows (alpha)
|
||||
|
||||
> [!WARNING]
|
||||
> Windows support in anthropic-experimental/sandbox-runtime is **alpha and the design is in flux**.
|
||||
>
|
||||
> The current implementation provides:
|
||||
> - Network egress filtering via the **Windows Filtering Platform (WFP)**.
|
||||
> - File read/write denial via **ACL stamping**.
|
||||
>
|
||||
> However, it is **not a security boundary against a deliberately adversarial sandboxed process**.
|
||||
>
|
||||
> The sandbox implementation will be substantially revised in a future release, where sandboxed processes will run under a dedicated sandbox user account.
|
||||
|
||||
Shumai requires:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
|
||||
Install `ffmpeg` using your preferred package manager:
|
||||
|
||||
**winget**
|
||||
```powershell
|
||||
winget install Gyan.FFmpeg
|
||||
```
|
||||
|
||||
**Chocolatey**
|
||||
```powershell
|
||||
choco install ffmpeg
|
||||
|
||||
#### Step 4: Install Shumai globally
|
||||
|
||||
|
||||
+76
-14
@@ -33,7 +33,7 @@
|
||||
- **语义搜索**:基于向量进行搜索(Gemini Embedding 2),支持按视觉内容或语义概念搜索资产。
|
||||
|
||||
> [!NOTE]
|
||||
> **媒体处理与存储机制:** 上传媒体文件后,Shumai 始终会保留并存储原始文件。无论图片还是视频,都会额外生成一张 480p 的 WebP 封面图,作为文件列表中的预览图。此外:
|
||||
> **媒体处理与存储机制:** 上传媒体文件后,Shumai 始终会保留并存储原始文件。请注意,系统中显示的文件大小为原始文件的大小,不包含转码后生成的代理文件大小。无论图片还是视频,都会额外生成一张 480p 的 WebP 封面图,作为文件列表中的预览图。此外:
|
||||
>
|
||||
> * **图片:** 会生成一份与原图分辨率完全一致的高质量 WebP 转码版本,在保证画质的同时提升浏览性能。
|
||||
> * **视频:** 会根据转码配置生成至少一个代理视频,同时生成雪碧图(Sprite)和一段最长 1600 帧的低分辨率转码视频,用于实现快速拖动时间轴和即时视频预览。
|
||||
@@ -132,26 +132,88 @@ mkdir shumai && cd shumai
|
||||
|
||||
```
|
||||
|
||||
#### 第三步:安装平台特定系统依赖
|
||||
#### 步骤 3:安装平台依赖
|
||||
|
||||
在安装 Shumai 之前,请确保您的宿主机上已经安装了以下系统依赖项:
|
||||
#### Linux
|
||||
|
||||
| 依赖包 | 功能描述 | Ubuntu/Debian | Fedora | Arch | macOS |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| **ffmpeg** | 媒体转码及元数据提取 | `sudo apt install -y ffmpeg` | `sudo dnf install -y ffmpeg` | `sudo pacman -S --noconfirm ffmpeg` | `brew install ffmpeg` |
|
||||
| **bubblewrap** | 用于安全执行 AI 助手脚本的隔离沙箱环境 | `sudo apt install -y bubblewrap` | `sudo dnf install -y bubblewrap` | `sudo pacman -S --noconfirm bubblewrap` | *无需安装* |
|
||||
| **socat** | 用于沙箱网络桥接的双向套接字中继 | `sudo apt install -y socat` | `sudo dnf install -y socat` | `sudo pacman -S --noconfirm socat` | `brew install socat` |
|
||||
| **ripgrep** | 用于工作区安全策略的高效文本搜索工具 | `sudo apt install -y ripgrep` | `sudo dnf install -y ripgrep` | `sudo pacman -S --noconfirm ripgrep` | `brew install ripgrep` |
|
||||
在 Linux 上运行 Shumai 需要安装以下系统依赖:
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
- **`bubblewrap`**、**`socat`** 和 **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需,用于进程隔离、网络通信和工作区搜索。
|
||||
|
||||
可以使用以下命令一次性安装所有依赖:
|
||||
|
||||
> Ubuntu/Debian
|
||||
```bash
|
||||
sudo apt install -y ffmpeg bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> Fedora
|
||||
```bash
|
||||
sudo dnf install -y ffmpeg bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> Arch Linux
|
||||
```bash
|
||||
sudo pacman -S --noconfirm ffmpeg bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> **Ubuntu 24.04+ 用户请注意:** 这些系统版本默认限制了非特权用户命名空间(unprivileged user namespaces)。为了让 `bubblewrap` 和沙箱隔离层正常工作,需要关闭此限制:
|
||||
> **Ubuntu 24.04+** 默认限制非特权用户创建 User Namespace,这会导致 `anthropic-experimental/sandbox-runtime` 无法使用 `bubblewrap` 提供沙箱隔离。
|
||||
>
|
||||
> 如需临时启用 User Namespace,请执行:
|
||||
>
|
||||
> ```bash
|
||||
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
>
|
||||
> ```
|
||||
>
|
||||
>
|
||||
> 或者,您也可以专门配置一个 AppArmor 配置文件,为相关二进制文件授予用户命名空间创建(`userns`)权限。
|
||||
>
|
||||
> 或者,配置 AppArmor Profile,为相关可执行文件授予所需的 `userns` 权限。
|
||||
|
||||
---
|
||||
|
||||
#### macOS
|
||||
|
||||
在 macOS 上运行 Shumai 需要:
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
- **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需。
|
||||
|
||||
使用 Homebrew 安装所需依赖:
|
||||
|
||||
```bash
|
||||
brew install ffmpeg ripgrep
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Windows(Alpha)
|
||||
|
||||
> [!WARNING]
|
||||
> anthropic-experimental/sandbox-runtime 的 Windows 支持目前仍处于 **Alpha** 阶段,整体设计仍在持续调整中。
|
||||
>
|
||||
> 当前实现提供了以下能力:
|
||||
> - 通过 **Windows Filtering Platform (WFP)** 实现网络出口(egress)过滤。
|
||||
> - 通过 **ACL Stamping** 实现文件读写权限限制。
|
||||
>
|
||||
> **但这并不能作为针对恶意沙箱进程的安全边界(security boundary)**。
|
||||
>
|
||||
> 未来版本将对沙箱机制进行重大调整,届时沙箱进程将运行在独立的沙箱用户账户下。
|
||||
|
||||
在 Windows 上运行 Shumai 需要:
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
|
||||
使用你偏好的包管理器安装 `ffmpeg`:
|
||||
|
||||
**winget**
|
||||
```powershell
|
||||
winget install Gyan.FFmpeg
|
||||
```
|
||||
|
||||
**Chocolatey**
|
||||
```powershell
|
||||
choco install ffmpeg
|
||||
```
|
||||
|
||||
#### 第四步:全局安装 Shumai
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -89,7 +89,13 @@ async function run() {
|
||||
const mainHtmlHeaders = bundle.files.find((f) => f.path === bundle.index)?.headers || {
|
||||
'content-type': 'text/html;charset=utf-8',
|
||||
}
|
||||
const serveMainHtml = () => new Response(mainHtmlFile, { headers: mainHtmlHeaders })
|
||||
const raw = await mainHtmlFile.text()
|
||||
const mainHtmlText = raw
|
||||
.replaceAll('href="./', 'href="/')
|
||||
.replaceAll('src="./', 'src="/')
|
||||
.replaceAll('content="./', 'content="/')
|
||||
const serveMainHtml = () => new Response(mainHtmlText, { headers: mainHtmlHeaders })
|
||||
|
||||
|
||||
routes['/'] = serveMainHtml
|
||||
routes['/*'] = serveMainHtml
|
||||
|
||||
@@ -19,7 +19,8 @@ await Bun.build({
|
||||
root: '.',
|
||||
target: 'bun',
|
||||
outdir: outdir,
|
||||
minify: false,
|
||||
minify: true,
|
||||
splitting: true,
|
||||
naming: '[name].[ext]',
|
||||
plugins: [
|
||||
temporalWorkflow({
|
||||
@@ -44,5 +45,4 @@ await Bun.build({
|
||||
define: {
|
||||
'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
},
|
||||
publicPath: '/',
|
||||
})
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"bin": {
|
||||
"shumai-agent": "./src/index.ts",
|
||||
},
|
||||
@@ -49,7 +49,7 @@
|
||||
},
|
||||
"apps/cli": {
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"bin": {
|
||||
"shumai-cli": "./src/index.ts",
|
||||
},
|
||||
@@ -64,7 +64,7 @@
|
||||
},
|
||||
"apps/transcode": {
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"bin": {
|
||||
"shumai-transcode": "./src/index.ts",
|
||||
},
|
||||
@@ -76,7 +76,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/api": "workspace:*",
|
||||
@@ -91,7 +91,7 @@
|
||||
},
|
||||
"packages/agent": {
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.52",
|
||||
"@earendil-works/pi-agent-core": "0.78.0",
|
||||
@@ -115,7 +115,7 @@
|
||||
},
|
||||
"packages/api": {
|
||||
"name": "@shumai/api",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
"@shumai/core": "workspace:*",
|
||||
@@ -129,8 +129,9 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@shumai/core",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.78.0",
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.49",
|
||||
@@ -156,7 +157,7 @@
|
||||
},
|
||||
"packages/db": {
|
||||
"name": "@shumai/db",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.78.0",
|
||||
"@prisma/adapter-pg": "7.8.0",
|
||||
@@ -172,18 +173,19 @@
|
||||
},
|
||||
"packages/dtos": {
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.78.0",
|
||||
"zod": "4.4.3",
|
||||
},
|
||||
},
|
||||
"packages/tableprinter": {
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
},
|
||||
"packages/transcode": {
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -197,7 +199,7 @@
|
||||
},
|
||||
"packages/webui": {
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.5.0",
|
||||
"@dnd-kit/abstract": "0.4.0",
|
||||
@@ -294,7 +296,7 @@
|
||||
},
|
||||
"packages/workflow-core": {
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.7",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -88,9 +88,8 @@ If you need to create files in the local filesystem (for example, a temporary fi
|
||||
systemPrompt = `${systemPrompt}\n\nAgent Personality and Core Instructions:\n${agent.soul}`
|
||||
}
|
||||
|
||||
if (params.agentsInstruction) {
|
||||
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${params.agentsInstruction}`
|
||||
}
|
||||
// Note: params.agentsInstruction is no longer appended to systemPrompt here.
|
||||
// Instead, it is persisted as a custom message session entry in the conversation history below.
|
||||
|
||||
const modelConfig = agent.modelRef?.config
|
||||
if (modelConfig?.input) {
|
||||
@@ -145,6 +144,19 @@ If you need to create files in the local filesystem (for example, a temporary fi
|
||||
}
|
||||
|
||||
try {
|
||||
if (params.agentsInstruction && params.agentsInstruction.trim()) {
|
||||
const storage = session.getStorage()
|
||||
const parentId = await storage.getLeafId()
|
||||
await storage.appendEntry({
|
||||
id: ulid(),
|
||||
type: 'custom_message',
|
||||
parentId,
|
||||
timestamp: new Date().toISOString(),
|
||||
customType: 'context',
|
||||
content: params.agentsInstruction.trim(),
|
||||
} as unknown as SessionTreeEntry)
|
||||
}
|
||||
|
||||
const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass })
|
||||
|
||||
const sessionEntries = await session.getEntries()
|
||||
|
||||
@@ -73,4 +73,34 @@ describe('AgentChatPromptBuilder', () => {
|
||||
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', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
.withAttachedFiles(['- file1.txt', '- file2.png'])
|
||||
.withReferencedAssets(['- folder1', '- file3.mp4'])
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('[Context: Attached Files & Referenced Assets]')
|
||||
expect(result).toContain('Attached Files:\n- file1.txt\n- file2.png')
|
||||
expect(result).toContain('Referenced Workspace Assets:\n- folder1\n- file3.mp4')
|
||||
})
|
||||
|
||||
it('should build prompt for continuation mode returning only turn-specific modifications', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
.withContinuation(true)
|
||||
.withAssetDetails('movie.mp4', 'video/mp4', 12.34)
|
||||
.withPathContext('src/main.ts')
|
||||
.withCommentTimestamp(8.2)
|
||||
.withAttachedFiles(['- file1.txt'])
|
||||
.withReferencedAssets(['- folder1'])
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).not.toContain('The user is discussing an asset with ID:')
|
||||
expect(result).not.toContain('File Name: movie.mp4')
|
||||
expect(result).not.toContain('Asset Path Context:')
|
||||
expect(result).toContain('Comment Timestamp: 8.20 seconds')
|
||||
expect(result).toContain('[Context: New Attached Files & Referenced Assets]')
|
||||
expect(result).toContain('Attached Files:\n- file1.txt')
|
||||
expect(result).toContain('Referenced Workspace Assets:\n- folder1')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -22,11 +22,34 @@ export class AgentChatPromptBuilder {
|
||||
private commentTimestamp?: number
|
||||
private pathContext?: string
|
||||
private explicitMention = false
|
||||
private attachedFiles: string[] = []
|
||||
private referencedAssets: string[] = []
|
||||
|
||||
private isContinuation = false
|
||||
|
||||
constructor(assetId: string) {
|
||||
this.assetId = assetId
|
||||
}
|
||||
|
||||
withContinuation(isContinuation: boolean): this {
|
||||
this.isContinuation = isContinuation
|
||||
return this
|
||||
}
|
||||
|
||||
withAttachedFiles(files?: string[]): this {
|
||||
if (files) {
|
||||
this.attachedFiles = files
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
withReferencedAssets(assets?: string[]): this {
|
||||
if (assets) {
|
||||
this.referencedAssets = assets
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
withPathContext(pathContext?: string): this {
|
||||
this.pathContext = pathContext
|
||||
return this
|
||||
@@ -52,6 +75,23 @@ export class AgentChatPromptBuilder {
|
||||
}
|
||||
|
||||
build(): string {
|
||||
if (this.isContinuation) {
|
||||
let instruction = ''
|
||||
if (this.commentTimestamp !== undefined) {
|
||||
instruction += `Comment Timestamp: ${this.commentTimestamp.toFixed(2)} seconds`
|
||||
}
|
||||
if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) {
|
||||
instruction += `\n\n[Context: New Attached Files & Referenced Assets]`
|
||||
if (this.attachedFiles.length > 0) {
|
||||
instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}`
|
||||
}
|
||||
if (this.referencedAssets.length > 0) {
|
||||
instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}`
|
||||
}
|
||||
}
|
||||
return instruction.trim()
|
||||
}
|
||||
|
||||
let instruction = `The user is discussing an asset with ID: ${this.assetId}.`
|
||||
if (this.assetName) {
|
||||
instruction += `\nFile Name: ${this.assetName}`
|
||||
@@ -70,6 +110,16 @@ export class AgentChatPromptBuilder {
|
||||
instruction += `\n\nAsset Path Context:\n${this.pathContext}`
|
||||
}
|
||||
|
||||
if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) {
|
||||
instruction += `\n\n[Context: Attached Files & Referenced Assets]`
|
||||
if (this.attachedFiles.length > 0) {
|
||||
instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}`
|
||||
}
|
||||
if (this.referencedAssets.length > 0) {
|
||||
instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}`
|
||||
}
|
||||
}
|
||||
|
||||
if (this.mediaType) {
|
||||
const type = getSimpleMediaType(this.mediaType)
|
||||
if (type === 'image') {
|
||||
|
||||
@@ -185,6 +185,7 @@ describe('Agent Chat Workflow', () => {
|
||||
|
||||
expect(mockActivities.initializeAgentSessionActivity).not.toHaveBeenCalled()
|
||||
const expectedInstruction2 = new AgentChatPromptBuilder('a1')
|
||||
.withContinuation(true)
|
||||
.withPathContext('Path: folder/subfolder/file.png')
|
||||
.withAssetDetails('test-file.png', 'image/png', undefined)
|
||||
.withCommentTimestamp(null)
|
||||
@@ -397,4 +398,96 @@ describe('Agent Chat Workflow', () => {
|
||||
message: 'Sorry, I encountered an error while processing your request.',
|
||||
})
|
||||
})
|
||||
|
||||
it('should execute direct-context chatbot flow resolving file metadata and skipping comment placeholder', async () => {
|
||||
mockActivities.getAssetActivity.mockImplementation(async (id: string) => {
|
||||
if (id === 'file-attachment-1') {
|
||||
return {
|
||||
id: 'file-attachment-1',
|
||||
name: 'attachment.png',
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
projectId: 'p1',
|
||||
}
|
||||
}
|
||||
if (id === 'referenced-asset-1') {
|
||||
return {
|
||||
id: 'referenced-asset-1',
|
||||
name: 'ref-folder',
|
||||
type: 'folder',
|
||||
mediaType: null,
|
||||
projectId: 'p1',
|
||||
}
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name: 'test-file.png',
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
projectId: 'p1',
|
||||
project: { teamId: 't1' },
|
||||
}
|
||||
})
|
||||
|
||||
mockActivities.getAssetPathContextActivity.mockImplementation(async (id: string) => {
|
||||
if (id === 'file-attachment-1') return 'attachment.png'
|
||||
if (id === 'referenced-asset-1') return 'ref-folder'
|
||||
return 'folder/subfolder/file.png'
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: {
|
||||
agentId: 'b1',
|
||||
sessionId: 'session-direct-123',
|
||||
prompt: 'chatbot prompt',
|
||||
attachedFiles: ['file-attachment-1'],
|
||||
assetIds: ['referenced-asset-1'],
|
||||
explicitMention: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
// Verify placeholder comment is NOT created
|
||||
expect(mockActivities.createCommentActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
|
||||
|
||||
// Verify prompt builder is populated and workflow runs agentChatActivity with context instruction
|
||||
const expectedInstruction = new AgentChatPromptBuilder('a1')
|
||||
.withContinuation(true)
|
||||
.withPathContext('folder/subfolder/file.png')
|
||||
.withAssetDetails('test-file.png', 'image/png', undefined)
|
||||
.withCommentTimestamp(undefined)
|
||||
.withExplicitMention(true)
|
||||
.withAttachedFiles([
|
||||
'- Name: attachment.png (ID: file-attachment-1, Type: file, Media Type: image/png, Project ID: p1, Path: attachment.png)',
|
||||
])
|
||||
.withReferencedAssets([
|
||||
'- Name: ref-folder (ID: referenced-asset-1, Type: folder, Media Type: unknown, Project ID: p1, Path: ref-folder)',
|
||||
])
|
||||
.build()
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
message: 'chatbot prompt',
|
||||
imageUrls: [],
|
||||
projectId: 'p1',
|
||||
folderId: '',
|
||||
agentsInstruction: expectedInstruction,
|
||||
sessionId: 'session-direct-123',
|
||||
userId: undefined,
|
||||
userCommentId: undefined,
|
||||
explicitMention: true,
|
||||
context: { agent: { id: 'b1' } },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -46,26 +46,42 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 1. Get User Comment
|
||||
const userCommentId = payload.agent?.userCommentId
|
||||
if (!userCommentId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'userCommentId missing in payload',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
|
||||
if (!userComment) {
|
||||
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
||||
}
|
||||
let prompt = ''
|
||||
let attachmentImageUrls: string[] = []
|
||||
let commentTimestamp: number | undefined
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__CHAT__',
|
||||
sessionId: sessionId || 'pending',
|
||||
agentId: agentId,
|
||||
replyToId: userComment.replyToId ?? userComment.id,
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
if (userCommentId) {
|
||||
const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
|
||||
if (!userComment) {
|
||||
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
||||
}
|
||||
prompt = userComment.message || ''
|
||||
if (userComment.second !== null && userComment.second !== undefined) {
|
||||
commentTimestamp = userComment.second
|
||||
}
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__CHAT__',
|
||||
sessionId: sessionId || 'pending',
|
||||
agentId: agentId,
|
||||
replyToId: userComment.replyToId ?? userComment.id,
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 5. Prepare Images (Attachments only)
|
||||
if (userComment.attachments) {
|
||||
for (const att of userComment.attachments) {
|
||||
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) {
|
||||
attachmentImageUrls.push(att.asset.storageKey.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
prompt = payload.agent?.prompt || ''
|
||||
attachmentImageUrls = payload.agent?.imageUrls || []
|
||||
}
|
||||
|
||||
// 3. Get Asset
|
||||
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
||||
@@ -75,13 +91,21 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const teamId = asset.project.teamId
|
||||
|
||||
// 4. Initialize Session if missing
|
||||
let isNewChat = !payload.agent?.sessionId
|
||||
if (!sessionId) {
|
||||
if (!userCommentId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'sessionId is required when userCommentId is missing',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
sessionId = await executeActivity(agentWorkerQueue, initializeAgentSessionActivity, {
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
userCommentId,
|
||||
userId: payload.agent?.userId,
|
||||
})
|
||||
isNewChat = true
|
||||
}
|
||||
|
||||
// 4b. Fetch Agent Context
|
||||
@@ -90,16 +114,6 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
agentId: agentId,
|
||||
})
|
||||
|
||||
// 5. Prepare Images (Attachments only)
|
||||
const attachmentImageUrls: string[] = []
|
||||
if (userComment?.attachments) {
|
||||
for (const att of userComment.attachments) {
|
||||
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) {
|
||||
attachmentImageUrls.push(att.asset.storageKey.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const pathContext = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
@@ -110,11 +124,42 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const mediaInfo = asset.media as any
|
||||
const duration = mediaInfo?.duration
|
||||
|
||||
// Resolve Attached Files Details
|
||||
const attachedFileDetailsList: string[] = []
|
||||
if (payload.agent?.attachedFiles) {
|
||||
for (const fileId of payload.agent.attachedFiles) {
|
||||
const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId)
|
||||
if (file) {
|
||||
const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, fileId)
|
||||
attachedFileDetailsList.push(
|
||||
`- Name: ${file.name} (ID: ${file.id}, Type: ${file.type}, Media Type: ${file.mediaType || 'unknown'}, Project ID: ${file.projectId || 'unknown'}, Path: ${path})`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve Referenced Workspace Assets Details
|
||||
const referencedAssetDetailsList: string[] = []
|
||||
if (payload.agent?.assetIds) {
|
||||
for (const assetId of payload.agent.assetIds) {
|
||||
const referencedAsset = await executeActivity(agentWorkerQueue, getAssetActivity, assetId)
|
||||
if (referencedAsset) {
|
||||
const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, assetId)
|
||||
referencedAssetDetailsList.push(
|
||||
`- Name: ${referencedAsset.name} (ID: ${referencedAsset.id}, Type: ${referencedAsset.type}, Media Type: ${referencedAsset.mediaType || 'unknown'}, Project ID: ${referencedAsset.projectId || 'unknown'}, Path: ${path})`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const instruction = new AgentChatPromptBuilder(asset.id)
|
||||
.withContinuation(!isNewChat)
|
||||
.withPathContext(pathContext)
|
||||
.withAssetDetails(asset.name, asset.mediaType, duration)
|
||||
.withCommentTimestamp(userComment.second)
|
||||
.withCommentTimestamp(commentTimestamp)
|
||||
.withExplicitMention(payload.agent?.explicitMention)
|
||||
.withAttachedFiles(attachedFileDetailsList)
|
||||
.withReferencedAssets(referencedAssetDetailsList)
|
||||
.build()
|
||||
|
||||
// 6. Call AI Chat
|
||||
@@ -128,14 +173,14 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
message: userComment.message || '',
|
||||
message: prompt,
|
||||
imageUrls: attachmentImageUrls,
|
||||
projectId: payload.projectId,
|
||||
folderId,
|
||||
agentsInstruction: instruction,
|
||||
sessionId,
|
||||
userId: payload.agent?.userId,
|
||||
userCommentId,
|
||||
userCommentId: userCommentId || undefined,
|
||||
explicitMention: payload.agent?.explicitMention,
|
||||
context,
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import chatRoute from './chat'
|
||||
import { chatService } from '@shumai/core/src/chat/chat'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/chat/chat', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('@shumai/core/src/chat/chat')>()
|
||||
return {
|
||||
...original,
|
||||
chatService: {
|
||||
listSessions: vi.fn(),
|
||||
listMessages: vi.fn(),
|
||||
deleteSession: vi.fn(),
|
||||
startOrContinueChat: vi.fn(),
|
||||
},
|
||||
}
|
||||
})
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/db', () => ({
|
||||
prisma: {
|
||||
agentSessionEntry: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
workflowTask: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
import { prisma } from '@shumai/db'
|
||||
|
||||
describe('Chat API', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', chatRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /chat/sessions', () => {
|
||||
it('returns list of sessions', async () => {
|
||||
const mockSessions = {
|
||||
data: [
|
||||
{
|
||||
id: 'session1',
|
||||
agentId: 'default',
|
||||
userId: 'user1',
|
||||
assetId: 'asset1',
|
||||
userCommentId: 'comment1',
|
||||
createdAt: '2026-07-07T10:00:00Z',
|
||||
updatedAt: '2026-07-07T10:00:00Z',
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1 },
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(chatService.listSessions).mockResolvedValue(mockSessions as any)
|
||||
|
||||
const res = await app.request('/chat/sessions?first=10')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.data).toHaveLength(1)
|
||||
expect(data.data[0].id).toBe('session1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /chat/sessions/:sessionId/messages', () => {
|
||||
it('returns list of messages', async () => {
|
||||
const mockMessages = [
|
||||
{
|
||||
id: 'msg1',
|
||||
role: 'user',
|
||||
content: 'hello',
|
||||
timestamp: '2026-07-07T10:00:00Z',
|
||||
entry: {},
|
||||
},
|
||||
]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(chatService.listMessages).mockResolvedValue(mockMessages as any)
|
||||
|
||||
const res = await app.request('/chat/sessions/session1/messages')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].content).toBe('hello')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /chat/sessions/:sessionId', () => {
|
||||
it('deletes a session', async () => {
|
||||
vi.mocked(chatService.deleteSession).mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/chat/sessions/session1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
expect(res.status).toBe(204)
|
||||
expect(chatService.deleteSession).toHaveBeenCalledWith('user1', 'session1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /chat', () => {
|
||||
it('starts or continues chat and returns stream', async () => {
|
||||
vi.mocked(chatService.startOrContinueChat).mockResolvedValue({
|
||||
sessionId: 'session1',
|
||||
taskId: 'task1',
|
||||
})
|
||||
|
||||
const mockEntries = [
|
||||
{
|
||||
id: 'entry1',
|
||||
sessionId: 'session1',
|
||||
entry: {
|
||||
type: 'message',
|
||||
message: {
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: 'hi' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.agentSessionEntry.findMany).mockResolvedValue(mockEntries as any)
|
||||
|
||||
const mockTask = {
|
||||
id: 'task1',
|
||||
status: 'completed',
|
||||
output: {},
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.workflowTask.findUnique).mockResolvedValue(mockTask as any)
|
||||
|
||||
const res = await app.request('/chat', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
agentId: 'agent1',
|
||||
textPrompt: 'hi',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toContain('text/event-stream')
|
||||
|
||||
const text = await res.text()
|
||||
expect(text).toContain('data:')
|
||||
expect(text).toContain('entry1')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,126 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { streamSSE } from 'hono/streaming'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { chatService, mapEntryToMessage } from '@shumai/core/src/chat/chat'
|
||||
import { chatRequestSchema, paginationParamsSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/chat/sessions', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const query = c.req.valid('query')
|
||||
|
||||
const res = await chatService.listSessions(user.id, query)
|
||||
return c.json(res, 200)
|
||||
})
|
||||
.get('/chat/sessions/:sessionId/messages', async (c) => {
|
||||
const user = c.get('user')
|
||||
const sessionId = c.req.param('sessionId')
|
||||
|
||||
const res = await chatService.listMessages(user.id, sessionId)
|
||||
return c.json(res, 200)
|
||||
})
|
||||
.delete('/chat/sessions/:sessionId', async (c) => {
|
||||
const user = c.get('user')
|
||||
const sessionId = c.req.param('sessionId')
|
||||
|
||||
await chatService.deleteSession(user.id, sessionId)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/chat', zValidator('json', chatRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const { sessionId, taskId } = await chatService.startOrContinueChat(user, req)
|
||||
|
||||
return streamSSE(c, async (stream) => {
|
||||
let lastEntryId = ''
|
||||
const timeoutMs = 5 * 60 * 1000 // 5 minutes timeout
|
||||
const startTime = Date.now()
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (stream.aborted) {
|
||||
break
|
||||
}
|
||||
// Query new entries from the DB
|
||||
const newEntries = await prisma.agentSessionEntry.findMany({
|
||||
where: {
|
||||
sessionId,
|
||||
...(lastEntryId ? { id: { gt: lastEntryId } } : {}),
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
if (newEntries.length > 0) {
|
||||
for (const record of newEntries) {
|
||||
const message = mapEntryToMessage(record)
|
||||
await stream.writeSSE({
|
||||
data: JSON.stringify({
|
||||
type: 'entry',
|
||||
entry: message,
|
||||
}),
|
||||
})
|
||||
}
|
||||
lastEntryId = newEntries[newEntries.length - 1].id
|
||||
}
|
||||
|
||||
// Check if workflow has finished
|
||||
const task = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: { status: true, output: true },
|
||||
})
|
||||
|
||||
if (task && (task.status === 'completed' || task.status === 'failed')) {
|
||||
// Fetch any remaining entries one last time
|
||||
const finalEntries = await prisma.agentSessionEntry.findMany({
|
||||
where: {
|
||||
sessionId,
|
||||
...(lastEntryId ? { id: { gt: lastEntryId } } : {}),
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
for (const record of finalEntries) {
|
||||
const message = mapEntryToMessage(record)
|
||||
await stream.writeSSE({
|
||||
data: JSON.stringify({
|
||||
type: 'entry',
|
||||
entry: message,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
// Send done status
|
||||
const output = task.output as Record<string, unknown> | null
|
||||
await stream.writeSSE({
|
||||
data: JSON.stringify({
|
||||
type: 'done',
|
||||
status: task.status,
|
||||
error:
|
||||
task.status === 'failed'
|
||||
? (output?.error as string) || 'Workflow failed'
|
||||
: undefined,
|
||||
}),
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
// Wait before polling again
|
||||
await stream.sleep(1000)
|
||||
}
|
||||
|
||||
if (Date.now() - startTime >= timeoutMs) {
|
||||
await stream.writeSSE({
|
||||
data: JSON.stringify({
|
||||
type: 'done',
|
||||
status: 'failed',
|
||||
error: 'Request timed out',
|
||||
}),
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { Hono } from 'hono'
|
||||
import agentRoute from './agent'
|
||||
import chatRoute from './chat'
|
||||
import attachmentRoute from './attachment'
|
||||
import authnRoute from './authn'
|
||||
import collectionRoute from './collection'
|
||||
@@ -54,6 +55,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
.route('/', fileRoute)
|
||||
.route('/', folderRoute)
|
||||
.route('/', agentRoute)
|
||||
.route('/', chatRoute)
|
||||
.route('/', attachmentRoute)
|
||||
.route('/', uploadRoute)
|
||||
.route('/', shareRoute)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
@@ -8,6 +8,7 @@
|
||||
"dependencies": {
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@earendil-works/pi-agent-core": "0.78.0",
|
||||
"@sinclair/typebox": "0.34.49",
|
||||
"adm-zip": "0.5.17",
|
||||
"better-auth": "1.6.11",
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { chatService, buildSessionMessages, type PathEntry } from './chat'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
describe('ChatService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
async function setupBasicData() {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User', email: `test-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: { transcode: { videoStrategy: 'best_match' } },
|
||||
sandbox: { create: {} },
|
||||
},
|
||||
})
|
||||
|
||||
const teamMember = await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'Test Project',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: 'root',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.project.update({
|
||||
where: { id: project.id },
|
||||
data: { rootFolderId: rootFolder.id },
|
||||
})
|
||||
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
id: 'test-agent-id',
|
||||
name: 'Test Agent',
|
||||
email: 'test-agent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: 'test-agent-id',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return { user, team, teamMember, project, rootFolder, agent, agentUser }
|
||||
}
|
||||
|
||||
it('should start a new chat session and trigger workflow', async () => {
|
||||
const { user, project, rootFolder, agent } = await setupBasicData()
|
||||
|
||||
const { sessionId, taskId } = await chatService.startOrContinueChat(user, {
|
||||
agentId: agent.id,
|
||||
textPrompt: 'hello world',
|
||||
projectId: project.id,
|
||||
})
|
||||
|
||||
expect(sessionId).toBeDefined()
|
||||
expect(taskId).toBeDefined()
|
||||
|
||||
// Verify AgentSession is created
|
||||
const session = await prisma.agentSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
})
|
||||
expect(session).toBeDefined()
|
||||
expect(session?.userId).toBe(user.id)
|
||||
expect(session?.assetId).toBe(rootFolder.id)
|
||||
|
||||
// Verify no comment is created
|
||||
const comment = await prisma.assetComment.findFirst({
|
||||
where: { sessionId },
|
||||
})
|
||||
expect(comment).toBeNull()
|
||||
|
||||
// Verify no session entry is created yet (it is created automatically when the workflow runs)
|
||||
const entry = await prisma.agentSessionEntry.findFirst({
|
||||
where: { sessionId },
|
||||
})
|
||||
expect(entry).toBeNull()
|
||||
|
||||
// Verify WorkflowTask is created with correct payload
|
||||
const task = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskId },
|
||||
})
|
||||
expect(task).toBeDefined()
|
||||
expect(task?.type).toBe('chat')
|
||||
expect(task?.status).toBe('pending')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const taskPayload = task?.payload as any
|
||||
expect(taskPayload?.agent?.prompt).toBe('hello world')
|
||||
})
|
||||
|
||||
it('should continue an existing chat session', async () => {
|
||||
const { user, project, agent } = await setupBasicData()
|
||||
|
||||
// Start
|
||||
const { sessionId } = await chatService.startOrContinueChat(user, {
|
||||
agentId: agent.id,
|
||||
textPrompt: 'first message',
|
||||
projectId: project.id,
|
||||
})
|
||||
|
||||
// Continue
|
||||
const { sessionId: nextSessionId, taskId: nextTaskId } = await chatService.startOrContinueChat(
|
||||
user,
|
||||
{
|
||||
agentId: agent.id,
|
||||
textPrompt: 'second message',
|
||||
sessionId,
|
||||
},
|
||||
)
|
||||
|
||||
expect(nextSessionId).toBe(sessionId)
|
||||
expect(nextTaskId).toBeDefined()
|
||||
|
||||
// Verify no entries are created yet (they are created automatically when the workflow runs)
|
||||
const entries = await prisma.agentSessionEntry.findMany({
|
||||
where: { sessionId },
|
||||
})
|
||||
expect(entries).toHaveLength(0)
|
||||
|
||||
// Verify WorkflowTask is created with correct payload
|
||||
const task = await prisma.workflowTask.findUnique({
|
||||
where: { id: nextTaskId },
|
||||
})
|
||||
expect(task).toBeDefined()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const taskPayload = task?.payload as any
|
||||
expect(taskPayload?.agent?.prompt).toBe('second message')
|
||||
})
|
||||
|
||||
it('should inject context of referenced assets and attached files', async () => {
|
||||
const { user, project, rootFolder, agent } = await setupBasicData()
|
||||
|
||||
const childFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'child_folder',
|
||||
type: 'folder',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'doc_s3_key',
|
||||
},
|
||||
})
|
||||
|
||||
const textFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'doc.jpg',
|
||||
type: 'file',
|
||||
mediaType: 'image/jpeg',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: childFolder.id,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
const { taskId } = await chatService.startOrContinueChat(user, {
|
||||
agentId: agent.id,
|
||||
textPrompt: 'process file',
|
||||
projectId: project.id,
|
||||
assetIds: [childFolder.id],
|
||||
attachedFiles: [textFile.id],
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskId },
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const taskPayload = task?.payload as any
|
||||
|
||||
expect(taskPayload?.agent?.prompt).toBe('process file')
|
||||
expect(taskPayload?.agent?.attachedFiles).toContain(textFile.id)
|
||||
expect(taskPayload?.agent?.assetIds).toContain(childFolder.id)
|
||||
expect(taskPayload?.agent?.imageUrls).toContain('doc_s3_key')
|
||||
})
|
||||
|
||||
it('should list sessions of a user', async () => {
|
||||
const { user, project, agent } = await setupBasicData()
|
||||
|
||||
await chatService.startOrContinueChat(user, {
|
||||
agentId: agent.id,
|
||||
textPrompt: 'chat 1',
|
||||
projectId: project.id,
|
||||
})
|
||||
|
||||
await chatService.startOrContinueChat(user, {
|
||||
agentId: agent.id,
|
||||
textPrompt: 'chat 2',
|
||||
projectId: project.id,
|
||||
})
|
||||
|
||||
const list = await chatService.listSessions(user.id, { first: 10 })
|
||||
expect(list.data).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('should list messages mapped correctly', async () => {
|
||||
const { user, project, agent } = await setupBasicData()
|
||||
|
||||
const { sessionId } = await chatService.startOrContinueChat(user, {
|
||||
agentId: agent.id,
|
||||
textPrompt: 'hello',
|
||||
projectId: project.id,
|
||||
})
|
||||
|
||||
// Manually insert a test entry representing user message
|
||||
await prisma.agentSessionEntry.create({
|
||||
data: {
|
||||
id: 'test-entry-id',
|
||||
sessionId,
|
||||
entry: {
|
||||
type: 'message',
|
||||
id: 'test-entry-id',
|
||||
parentId: null,
|
||||
timestamp: new Date().toISOString(),
|
||||
message: {
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: 'hello' }],
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const messages = await chatService.listMessages(user.id, sessionId)
|
||||
expect(messages).toHaveLength(1)
|
||||
// Casting to any to access properties of union in test assertions
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const msg = messages[0] as any
|
||||
expect(msg.role).toBe('user')
|
||||
expect(msg.content).toEqual([{ type: 'text', text: 'hello' }])
|
||||
})
|
||||
|
||||
it('should delete session and cascade', async () => {
|
||||
const { user, project, agent } = await setupBasicData()
|
||||
|
||||
const { sessionId } = await chatService.startOrContinueChat(user, {
|
||||
agentId: agent.id,
|
||||
textPrompt: 'to delete',
|
||||
projectId: project.id,
|
||||
})
|
||||
|
||||
await chatService.deleteSession(user.id, sessionId)
|
||||
|
||||
const session = await prisma.agentSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
})
|
||||
expect(session).toBeNull()
|
||||
|
||||
const entries = await prisma.agentSessionEntry.findMany({
|
||||
where: { sessionId },
|
||||
})
|
||||
expect(entries).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('should build session messages correctly handling compaction and custom messages', () => {
|
||||
const pathEntries = [
|
||||
{
|
||||
id: 'entry-1',
|
||||
type: 'message',
|
||||
timestamp: '2026-07-07T00:00:00.000Z',
|
||||
message: {
|
||||
role: 'user',
|
||||
content: 'first message',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'entry-compaction',
|
||||
type: 'compaction',
|
||||
timestamp: '2026-07-07T00:01:00.000Z',
|
||||
summary: 'Compacted conversation history',
|
||||
tokensBefore: 200,
|
||||
firstKeptEntryId: 'entry-2',
|
||||
},
|
||||
{
|
||||
id: 'entry-2',
|
||||
type: 'message',
|
||||
timestamp: '2026-07-07T00:02:00.000Z',
|
||||
message: {
|
||||
role: 'assistant',
|
||||
content: 'kept message',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'entry-3',
|
||||
type: 'thinking_level_change',
|
||||
timestamp: '2026-07-07T00:03:00.000Z',
|
||||
thinkingLevel: 'high',
|
||||
},
|
||||
{
|
||||
id: 'entry-4',
|
||||
type: 'branch_summary',
|
||||
timestamp: '2026-07-07T00:04:00.000Z',
|
||||
summary: 'Branch summary details',
|
||||
fromId: 'entry-old',
|
||||
},
|
||||
]
|
||||
|
||||
const messages = buildSessionMessages(pathEntries as unknown as PathEntry[])
|
||||
|
||||
expect(messages).toHaveLength(4)
|
||||
|
||||
// 1. Compaction summary message
|
||||
// Casting to any to access properties of union in test assertions
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const msg0 = messages[0] as any
|
||||
expect(msg0.role).toBe('custom')
|
||||
expect(msg0.customType).toBe('compaction-summary')
|
||||
expect(msg0.content).toBe('Compacted conversation history')
|
||||
expect((msg0.details as Record<string, unknown>).tokensBefore).toBe(200)
|
||||
|
||||
// 2. Kept entry (entry-2)
|
||||
// Casting to any to access properties of union in test assertions
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const msg1 = messages[1] as any
|
||||
expect(msg1.id).toBe('entry-2')
|
||||
expect(msg1.role).toBe('assistant')
|
||||
expect(msg1.content).toBe('kept message')
|
||||
|
||||
// 3. Thinking level change (entry-3)
|
||||
// Casting to any to access properties of union in test assertions
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const msg2 = messages[2] as any
|
||||
expect(msg2.role).toBe('thinking_level_change')
|
||||
expect(msg2.content).toContain('Thinking level changed to high')
|
||||
|
||||
// 4. Branch summary (entry-4)
|
||||
// Casting to any to access properties of union in test assertions
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const msg3 = messages[3] as any
|
||||
expect(msg3.role).toBe('custom')
|
||||
expect(msg3.customType).toBe('branch-summary')
|
||||
expect(msg3.content).toBe('Branch summary details')
|
||||
expect((msg3.details as Record<string, unknown>).fromId).toBe('entry-old')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,365 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { paginateQuery, type PaginatedData } from '@shumai/core/src/pagination'
|
||||
import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos'
|
||||
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
export type PathEntry = SessionTreeEntry & { id: string }
|
||||
|
||||
export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] {
|
||||
let compaction: (SessionTreeEntry & { type: 'compaction' } & { id: string }) | null = null
|
||||
|
||||
for (const entry of pathEntries) {
|
||||
if (entry.type === 'compaction') {
|
||||
compaction = entry as SessionTreeEntry & { type: 'compaction' } & { id: string }
|
||||
}
|
||||
}
|
||||
|
||||
const messages: ChatMessage[] = []
|
||||
const appendMessage = (entry: PathEntry) => {
|
||||
const timestampMs = new Date(entry.timestamp).getTime()
|
||||
if (entry.type === 'message') {
|
||||
messages.push({
|
||||
...entry.message,
|
||||
id: entry.id,
|
||||
timestamp: entry.message.timestamp || timestampMs,
|
||||
} as unknown as ChatMessage)
|
||||
} else if (entry.type === 'custom_message') {
|
||||
messages.push({
|
||||
id: entry.id,
|
||||
role: 'custom',
|
||||
customType: entry.customType,
|
||||
content: entry.content,
|
||||
display: entry.display,
|
||||
details: entry.details as Record<string, unknown> | undefined,
|
||||
timestamp: timestampMs,
|
||||
} as unknown as ChatMessage)
|
||||
} else if (entry.type === 'branch_summary') {
|
||||
messages.push({
|
||||
id: entry.id,
|
||||
role: 'custom',
|
||||
customType: 'branch-summary',
|
||||
content: entry.summary,
|
||||
details: { fromId: entry.fromId },
|
||||
timestamp: timestampMs,
|
||||
} as unknown as ChatMessage)
|
||||
} else if (entry.type === 'thinking_level_change') {
|
||||
messages.push({
|
||||
id: entry.id,
|
||||
role: 'thinking_level_change',
|
||||
content: `Thinking level changed to ${entry.thinkingLevel}`,
|
||||
timestamp: timestampMs,
|
||||
} as unknown as ChatMessage)
|
||||
}
|
||||
}
|
||||
|
||||
if (compaction) {
|
||||
const compactionTimestamp = new Date(compaction.timestamp).getTime()
|
||||
messages.push({
|
||||
id: compaction.id,
|
||||
role: 'custom',
|
||||
customType: 'compaction-summary',
|
||||
content: compaction.summary,
|
||||
details: { tokensBefore: compaction.tokensBefore },
|
||||
timestamp: compactionTimestamp,
|
||||
} as unknown as ChatMessage)
|
||||
const compactionIdx = pathEntries.findIndex(
|
||||
(e) => e.type === 'compaction' && e.id === compaction?.id,
|
||||
)
|
||||
let foundFirstKept = false
|
||||
for (let i = 0; i < compactionIdx; i++) {
|
||||
const entry = pathEntries[i]
|
||||
if (entry.id === compaction.firstKeptEntryId) foundFirstKept = true
|
||||
if (foundFirstKept) appendMessage(entry)
|
||||
}
|
||||
for (let i = compactionIdx + 1; i < pathEntries.length; i++) {
|
||||
appendMessage(pathEntries[i])
|
||||
}
|
||||
} else {
|
||||
for (const entry of pathEntries) {
|
||||
appendMessage(entry)
|
||||
}
|
||||
}
|
||||
|
||||
return messages
|
||||
}
|
||||
|
||||
export function mapEntryToMessage(
|
||||
entryRecord: Prisma.AgentSessionEntryGetPayload<Record<string, never>>,
|
||||
): ChatMessage {
|
||||
const entryObj = entryRecord.entry as unknown as SessionTreeEntry
|
||||
const pathEntries = [{ ...entryObj, id: entryRecord.id }]
|
||||
const messages = buildSessionMessages(pathEntries)
|
||||
if (messages.length > 0) {
|
||||
return messages[0]
|
||||
}
|
||||
return {
|
||||
id: entryRecord.id,
|
||||
role: 'user',
|
||||
content: '',
|
||||
} as unknown as ChatMessage
|
||||
}
|
||||
|
||||
export class ChatService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private async getAssetPath(assetId: string): Promise<string> {
|
||||
const parts: string[] = []
|
||||
let currentId: string | null = assetId
|
||||
while (currentId) {
|
||||
const dbAssetNode = (await prisma.asset.findUnique({
|
||||
where: { id: currentId },
|
||||
select: { id: true, name: true, parentId: true, type: true },
|
||||
})) as { id: string; name: string; parentId: string | null; type: unknown } | null
|
||||
if (!dbAssetNode) break
|
||||
if (dbAssetNode.type === 'root' || dbAssetNode.type === 'share_root') {
|
||||
break
|
||||
}
|
||||
parts.unshift(dbAssetNode.name)
|
||||
currentId = dbAssetNode.parentId
|
||||
}
|
||||
return parts.join('/')
|
||||
}
|
||||
|
||||
async startOrContinueChat(
|
||||
user: User,
|
||||
req: ChatRequest,
|
||||
): Promise<{ sessionId: string; taskId: string }> {
|
||||
const {
|
||||
agentId,
|
||||
textPrompt,
|
||||
attachedFiles = [],
|
||||
assetIds = [],
|
||||
sessionId: passedSessionId,
|
||||
contextAssetId,
|
||||
projectId: passedProjectId,
|
||||
} = req
|
||||
|
||||
// 1. Permissions verification
|
||||
if (contextAssetId) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: contextAssetId,
|
||||
})
|
||||
}
|
||||
|
||||
for (const fileId of attachedFiles) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
}
|
||||
|
||||
for (const assetId of assetIds) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Project / Asset scoping resolution
|
||||
let targetAssetId = ''
|
||||
|
||||
if (passedSessionId) {
|
||||
const session = await this.prismaClient.agentSession.findUnique({
|
||||
where: { id: passedSessionId },
|
||||
include: { asset: { include: { project: true } } },
|
||||
})
|
||||
if (!session) throw new Error('Session not found')
|
||||
if (session.userId !== user.id) throw new Error('Unauthorized session access')
|
||||
if (!session.assetId) throw new Error('Session has no associated asset')
|
||||
targetAssetId = session.assetId
|
||||
} else {
|
||||
// Start a new session
|
||||
if (contextAssetId) {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: contextAssetId },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!asset) throw new Error('Context asset not found')
|
||||
targetAssetId = contextAssetId
|
||||
} else if (passedProjectId) {
|
||||
const project = await this.prismaClient.project.findUnique({
|
||||
where: { id: passedProjectId },
|
||||
})
|
||||
if (!project || !project.rootFolderId) throw new Error('Project or root folder not found')
|
||||
targetAssetId = project.rootFolderId
|
||||
} else {
|
||||
// Find default project from user's first team
|
||||
const teamMember = await this.prismaClient.teamMember.findFirst({
|
||||
where: { userId: user.id },
|
||||
include: { team: { include: { projects: { include: { rootFolder: true } } } } },
|
||||
})
|
||||
const project = teamMember?.team?.projects?.[0]
|
||||
if (!project || !project.rootFolderId) {
|
||||
throw new Error('No active project found for the user. Please specify a projectId.')
|
||||
}
|
||||
targetAssetId = project.rootFolderId
|
||||
}
|
||||
}
|
||||
|
||||
const finalPrompt = textPrompt || ''
|
||||
|
||||
const resolvedImageUrls: string[] = []
|
||||
for (const fileId of attachedFiles) {
|
||||
const file = await this.prismaClient.asset.findUnique({
|
||||
where: { id: fileId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (file && file.mediaType?.startsWith('image/') && file.storageKey?.key) {
|
||||
resolvedImageUrls.push(file.storageKey.key)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Create database records in a transaction
|
||||
return await this.prismaClient.$transaction(async (tx) => {
|
||||
const asset = await tx.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
include: { project: { include: { team: true } } },
|
||||
})
|
||||
if (!asset || !asset.project) {
|
||||
throw new Error('Resolved asset or project not found')
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
const projectId = asset.project.id
|
||||
|
||||
// Ensure AI agent configuration exists
|
||||
const agent = await tx.agent.findUnique({ where: { id: agentId } })
|
||||
if (!agent) {
|
||||
throw new Error(`Agent with ID "${agentId}" not found`)
|
||||
}
|
||||
|
||||
let activeSessionId = passedSessionId
|
||||
|
||||
if (activeSessionId) {
|
||||
const sessionExists = await tx.agentSession.findUnique({
|
||||
where: { id: activeSessionId },
|
||||
select: { id: true },
|
||||
})
|
||||
if (!sessionExists) throw new Error('Session not found')
|
||||
} else {
|
||||
const newSession = await tx.agentSession.create({
|
||||
data: {
|
||||
agentId,
|
||||
userId: user.id,
|
||||
cwd: process.cwd(),
|
||||
assetId: asset.id,
|
||||
},
|
||||
})
|
||||
activeSessionId = newSession.id
|
||||
}
|
||||
// Trigger chat workflow
|
||||
const task = await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId,
|
||||
agent: {
|
||||
prompt: finalPrompt,
|
||||
imageUrls: resolvedImageUrls,
|
||||
attachedFiles,
|
||||
assetIds,
|
||||
explicitMention: true,
|
||||
agentId,
|
||||
sessionId: activeSessionId,
|
||||
userId: user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
sessionId: activeSessionId!,
|
||||
taskId: task.id,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async listSessions(
|
||||
userId: string,
|
||||
params: { first?: number; after?: string },
|
||||
): Promise<PaginatedData<ChatSessionInfo[]>> {
|
||||
const where: Prisma.AgentSessionWhereInput = {
|
||||
userId,
|
||||
}
|
||||
|
||||
return await paginateQuery(
|
||||
async (skip, take) => {
|
||||
const sessions = await this.prismaClient.agentSession.findMany({
|
||||
where,
|
||||
skip,
|
||||
take,
|
||||
orderBy: { id: 'desc' },
|
||||
})
|
||||
return sessions.map((s) => ({
|
||||
id: s.id,
|
||||
agentId: s.agentId,
|
||||
userId: s.userId,
|
||||
assetId: s.assetId,
|
||||
userCommentId: s.userCommentId,
|
||||
createdAt: s.createdAt.toISOString(),
|
||||
updatedAt: s.updatedAt.toISOString(),
|
||||
}))
|
||||
},
|
||||
async () => this.prismaClient.agentSession.count({ where }),
|
||||
params,
|
||||
)
|
||||
}
|
||||
|
||||
async listMessages(userId: string, sessionId: string): Promise<ChatMessage[]> {
|
||||
const session = await this.prismaClient.agentSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
})
|
||||
if (!session) {
|
||||
throw new Error('Session not found')
|
||||
}
|
||||
if (session.userId !== userId) {
|
||||
throw new Error('Unauthorized session access')
|
||||
}
|
||||
|
||||
const entries = await this.prismaClient.agentSessionEntry.findMany({
|
||||
where: { sessionId },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
const pathEntries = entries.map((e) => {
|
||||
const entryObj = e.entry as unknown as SessionTreeEntry
|
||||
return {
|
||||
...entryObj,
|
||||
id: e.id,
|
||||
}
|
||||
})
|
||||
|
||||
return buildSessionMessages(pathEntries)
|
||||
}
|
||||
|
||||
async deleteSession(userId: string, sessionId: string): Promise<void> {
|
||||
const session = await this.prismaClient.agentSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
})
|
||||
if (!session) {
|
||||
throw new Error('Session not found')
|
||||
}
|
||||
if (session.userId !== userId) {
|
||||
throw new Error('Unauthorized session access')
|
||||
}
|
||||
await this.prismaClient.agentSession.delete({
|
||||
where: { id: sessionId },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const chatService = new ChatService()
|
||||
@@ -20,3 +20,4 @@ export * from './user/avatar'
|
||||
export * from './versionStack/versionStack'
|
||||
export * from './hyrumtoken'
|
||||
export * from './pagination'
|
||||
export * from './chat/chat'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -288,6 +288,10 @@ declare global {
|
||||
sessionId?: string
|
||||
userCommentId?: string
|
||||
explicitMention?: boolean
|
||||
prompt?: string
|
||||
imageUrls?: string[]
|
||||
attachedFiles?: string[]
|
||||
assetIds?: string[]
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.78.0",
|
||||
"zod": "4.4.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { z } from 'zod'
|
||||
import type { AgentMessage } from '@earendil-works/pi-agent-core'
|
||||
|
||||
export const chatRequestSchema = z
|
||||
.object({
|
||||
agentId: z.string(),
|
||||
textPrompt: z.string().optional(),
|
||||
attachedFiles: z.array(z.string()).optional(), // Uploaded file asset IDs
|
||||
assetIds: z.array(z.string()).optional(), // Workspace file/folder IDs referenced
|
||||
sessionId: z.string().optional(), // ID of existing session (to continue)
|
||||
contextAssetId: z.string().optional(), // Active page context asset ID
|
||||
projectId: z.string().optional(), // Target project ID
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
const hasPrompt = data.textPrompt && data.textPrompt.trim().length > 0
|
||||
const hasFiles = data.attachedFiles && data.attachedFiles.length > 0
|
||||
const hasAssets = data.assetIds && data.assetIds.length > 0
|
||||
if (!hasPrompt && !hasFiles && !hasAssets) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'At least one of textPrompt, attachedFiles, or assetIds must be provided.',
|
||||
path: ['textPrompt'],
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export type ChatRequest = z.infer<typeof chatRequestSchema>
|
||||
|
||||
export const chatSessionInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
agentId: z.string(),
|
||||
userId: z.string().nullable(),
|
||||
assetId: z.string().nullable(),
|
||||
userCommentId: z.string().nullable(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
})
|
||||
|
||||
export type ChatSessionInfo = z.infer<typeof chatSessionInfoSchema>
|
||||
|
||||
export const chatMessageSchema = z.intersection(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
z.unknown(),
|
||||
) as unknown as z.ZodType<AgentMessage & { id: string }>
|
||||
|
||||
export type ChatMessage = AgentMessage & { id: string }
|
||||
@@ -18,3 +18,4 @@ export * from './team'
|
||||
export * from './upload'
|
||||
export * from './user-metadata'
|
||||
export * from './versionStack'
|
||||
export * from './chat'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./index.html",
|
||||
|
||||
@@ -51,68 +51,78 @@ const TeamsTeamIdIndexRoute = TeamsTeamIdIndexRouteImport.update({
|
||||
id: '/teams/$teamId/',
|
||||
path: '/teams/$teamId/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() => import('./routes/teams/$teamId/index.lazy').then((d) => d.Route))
|
||||
const ShareShareIdIndexRoute = ShareShareIdIndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => ShareShareIdRoute,
|
||||
} as any)
|
||||
} as any).lazy(() => import('./routes/share/$shareId/index.lazy').then((d) => d.Route))
|
||||
const ProjectsProjectIdIndexRoute = ProjectsProjectIdIndexRouteImport.update({
|
||||
id: '/projects/$projectId/',
|
||||
path: '/projects/$projectId/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() => import('./routes/projects/$projectId/index.lazy').then((d) => d.Route))
|
||||
const TeamsTeamIdSettingsRoute = TeamsTeamIdSettingsRouteImport.update({
|
||||
id: '/teams/$teamId/settings',
|
||||
path: '/teams/$teamId/settings',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() => import('./routes/teams/$teamId/settings.lazy').then((d) => d.Route))
|
||||
const ProjectsProjectIdRecentlyDeletedRoute = ProjectsProjectIdRecentlyDeletedRouteImport.update({
|
||||
id: '/projects/$projectId/recently-deleted',
|
||||
path: '/projects/$projectId/recently-deleted',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() =>
|
||||
import('./routes/projects/$projectId/recently-deleted.lazy').then((d) => d.Route),
|
||||
)
|
||||
const ProjectsProjectIdSharesIndexRoute = ProjectsProjectIdSharesIndexRouteImport.update({
|
||||
id: '/projects/$projectId/shares/',
|
||||
path: '/projects/$projectId/shares/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() => import('./routes/projects/$projectId/shares/index.lazy').then((d) => d.Route))
|
||||
const ProjectsProjectIdCollectionsIndexRoute = ProjectsProjectIdCollectionsIndexRouteImport.update({
|
||||
id: '/projects/$projectId/collections/',
|
||||
path: '/projects/$projectId/collections/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() =>
|
||||
import('./routes/projects/$projectId/collections/index.lazy').then((d) => d.Route),
|
||||
)
|
||||
const ShareShareIdFoldersFolderIdRoute = ShareShareIdFoldersFolderIdRouteImport.update({
|
||||
id: '/folders/$folderId',
|
||||
path: '/folders/$folderId',
|
||||
getParentRoute: () => ShareShareIdRoute,
|
||||
} as any)
|
||||
} as any).lazy(() => import('./routes/share/$shareId/folders/$folderId.lazy').then((d) => d.Route))
|
||||
const ShareShareIdFilesFileIdRoute = ShareShareIdFilesFileIdRouteImport.update({
|
||||
id: '/files/$fileId',
|
||||
path: '/files/$fileId',
|
||||
getParentRoute: () => ShareShareIdRoute,
|
||||
} as any)
|
||||
} as any).lazy(() => import('./routes/share/$shareId/files/$fileId.lazy').then((d) => d.Route))
|
||||
const ProjectsProjectIdSharesShareIdRoute = ProjectsProjectIdSharesShareIdRouteImport.update({
|
||||
id: '/projects/$projectId/shares/$shareId',
|
||||
path: '/projects/$projectId/shares/$shareId',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() =>
|
||||
import('./routes/projects/$projectId/shares/$shareId.lazy').then((d) => d.Route),
|
||||
)
|
||||
const ProjectsProjectIdFoldersFolderIdRoute = ProjectsProjectIdFoldersFolderIdRouteImport.update({
|
||||
id: '/projects/$projectId/folders/$folderId',
|
||||
path: '/projects/$projectId/folders/$folderId',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() =>
|
||||
import('./routes/projects/$projectId/folders/$folderId.lazy').then((d) => d.Route),
|
||||
)
|
||||
const ProjectsProjectIdFilesFileIdRoute = ProjectsProjectIdFilesFileIdRouteImport.update({
|
||||
id: '/projects/$projectId/files/$fileId',
|
||||
path: '/projects/$projectId/files/$fileId',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() => import('./routes/projects/$projectId/files/$fileId.lazy').then((d) => d.Route))
|
||||
const ProjectsProjectIdCollectionsCollectionIdRoute =
|
||||
ProjectsProjectIdCollectionsCollectionIdRouteImport.update({
|
||||
id: '/projects/$projectId/collections/$collectionId',
|
||||
path: '/projects/$projectId/collections/$collectionId',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
} as any).lazy(() =>
|
||||
import('./routes/projects/$projectId/collections/$collectionId.lazy').then((d) => d.Route),
|
||||
)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
import { client } from '@/ui/api/client'
|
||||
import FileSystemManager from '@/ui/components/file-system-manager'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { projectInfoQueryOptions, collectionInfoQueryOptions } from './$collectionId'
|
||||
|
||||
function CollectionPage() {
|
||||
const { projectId, collectionId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const { data: collection, refetch: refetchCollection } = useQuery({
|
||||
...collectionInfoQueryOptions(collectionId),
|
||||
})
|
||||
|
||||
const { mutate: updateCollection } = useMutation({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mutationFn: async (updates: { name?: string; filter?: any }) => {
|
||||
const res = await client.api.collections[':collectionId'].$patch({
|
||||
param: { collectionId },
|
||||
json: updates,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update collection')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
refetchCollection()
|
||||
},
|
||||
})
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder || !collection) {
|
||||
return <div>{m.loading_collection()}</div>
|
||||
}
|
||||
|
||||
const sourceFolderId = collection.filter.sourceFolderId || rootFolderId
|
||||
|
||||
return (
|
||||
<FileSystemManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
assetId={sourceFolderId}
|
||||
rootFolderId={rootFolderId}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
collection={collection as any}
|
||||
onUpdateCollection={updateCollection}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/projects/$projectId/collections/$collectionId')({
|
||||
component: CollectionPage,
|
||||
})
|
||||
@@ -1,12 +1,8 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import FileSystemManager from '@/ui/components/file-system-manager'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useEffect } from 'react'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
const projectInfoQueryOptions = (projectId: string) => ({
|
||||
export const projectInfoQueryOptions = (projectId: string) => ({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
@@ -17,7 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
const collectionInfoQueryOptions = (collectionId: string) => ({
|
||||
export const collectionInfoQueryOptions = (collectionId: string) => ({
|
||||
queryKey: ['collections', collectionId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.collections[':collectionId'].$get({
|
||||
@@ -28,71 +24,7 @@ const collectionInfoQueryOptions = (collectionId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
function CollectionPage() {
|
||||
const { projectId, collectionId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const { data: collection, refetch: refetchCollection } = useQuery({
|
||||
...collectionInfoQueryOptions(collectionId),
|
||||
})
|
||||
|
||||
const { mutate: updateCollection } = useMutation({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mutationFn: async (updates: { name?: string; filter?: any }) => {
|
||||
const res = await client.api.collections[':collectionId'].$patch({
|
||||
param: { collectionId },
|
||||
json: updates,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update collection')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
refetchCollection()
|
||||
},
|
||||
})
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder || !collection) {
|
||||
return <div>{m.loading_collection()}</div>
|
||||
}
|
||||
|
||||
const sourceFolderId = collection.filter.sourceFolderId || rootFolderId
|
||||
|
||||
return (
|
||||
<FileSystemManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
assetId={sourceFolderId}
|
||||
rootFolderId={rootFolderId}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
collection={collection as any}
|
||||
onUpdateCollection={updateCollection}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/collections/$collectionId')({
|
||||
component: CollectionPage,
|
||||
loader: ({ context: { queryClient }, params: { projectId } }) =>
|
||||
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
|
||||
pendingComponent: () => <div>{m.loading_collection()}</div>,
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FolderTree } from '@/ui/components/folder-tree'
|
||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/ui/components/ui/table'
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/ui/components/ui/avatar'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useInfiniteQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Bookmark, Calendar, LayoutGrid, Loader2 } from 'lucide-react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import type { CollectionInfo } from '@shumai/dtos'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { projectInfoQueryOptions } from './index'
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
function CollectionsPage() {
|
||||
const { projectId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
const navigate = useNavigate()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
|
||||
|
||||
const {
|
||||
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
} = useUiStore()
|
||||
|
||||
const {
|
||||
data: collectionsData,
|
||||
isLoading: isCollectionsLoading,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['collections', projectId],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.projects[':projectId'].collections.$get({
|
||||
param: { projectId },
|
||||
query: { first: '20', after: pageParam as string },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch collections')
|
||||
return (await res.json()) as unknown as {
|
||||
data: CollectionInfo[]
|
||||
pageInfo: { cursor?: string; total?: number }
|
||||
}
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
const { ref: inViewRef, inView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const collections = useMemo(
|
||||
() => collectionsData?.pages.flatMap((p) => p.data) || [],
|
||||
[collectionsData],
|
||||
)
|
||||
|
||||
if (!teamId || !rootFolderId || !projectInfo) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col bg-background min-h-0">
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<div
|
||||
className="md:hidden fixed inset-0 bg-black/50 z-40"
|
||||
onClick={() => setIsLeftSidebarCollapsed(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<>
|
||||
<div className="bg-background" style={{ width: leftSidebarWidth }}>
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
</div>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
|
||||
}}
|
||||
className="hidden md:block"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col min-h-0 bg-card overflow-hidden">
|
||||
<header className="h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10">
|
||||
<div className="flex items-center gap-2">
|
||||
<Bookmark className="h-5 w-5 text-primary" />
|
||||
<h1 className="font-bold text-lg text-foreground">{m.all_collections()}</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
{isCollectionsLoading ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
) : collections.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3">
|
||||
<LayoutGrid className="h-10 w-10 text-muted-foreground/50" />
|
||||
<p>{m.no_collections_yet()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border border-border rounded-xl bg-background overflow-hidden shadow-xs">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent bg-muted/20">
|
||||
<TableHead className="font-semibold px-4 py-3">
|
||||
{m.collection_name()}
|
||||
</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3">{m.creator()}</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3 w-[200px]">
|
||||
{m.created_date()}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{collections.map((collection) => (
|
||||
<TableRow
|
||||
key={collection.id}
|
||||
className="hover:bg-muted/10 transition-colors cursor-pointer"
|
||||
onClick={() =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/collections/$collectionId',
|
||||
params: { projectId, collectionId: collection.id },
|
||||
})
|
||||
}
|
||||
>
|
||||
<TableCell className="font-medium px-4 py-3.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Bookmark className="h-4 w-4 text-primary shrink-0" />
|
||||
<span className="text-foreground font-semibold hover:underline">
|
||||
{collection.name}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-6 w-6">
|
||||
{collection.creator?.image && (
|
||||
<AvatarImage
|
||||
src={collection.creator.image}
|
||||
alt={collection.creator.name}
|
||||
className="object-cover"
|
||||
/>
|
||||
)}
|
||||
<AvatarFallback className="text-[10px]">
|
||||
{getInitials(collection.creator?.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-sm font-medium text-foreground truncate max-w-[200px]">
|
||||
{collection.creator?.name || m.unknown()}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5 text-muted-foreground text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="h-3.5 w-3.5 text-muted-foreground/70" />
|
||||
<span>{new Date(collection.createdAt).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div ref={inViewRef} className="h-10 w-full flex items-center justify-center">
|
||||
{isFetchingNextPage && <Loader2 className="h-6 w-6 animate-spin text-primary" />}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/projects/$projectId/collections/')({
|
||||
component: CollectionsPage,
|
||||
})
|
||||
@@ -1,37 +1,8 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FolderTree } from '@/ui/components/folder-tree'
|
||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/ui/components/ui/table'
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/ui/components/ui/avatar'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useInfiniteQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Bookmark, Calendar, LayoutGrid, Loader2 } from 'lucide-react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import type { CollectionInfo } from '@shumai/dtos'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
const projectInfoQueryOptions = (projectId: string) => ({
|
||||
export const projectInfoQueryOptions = (projectId: string) => ({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
@@ -42,191 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
function CollectionsPage() {
|
||||
const { projectId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
const navigate = useNavigate()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
|
||||
|
||||
const {
|
||||
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
} = useUiStore()
|
||||
|
||||
const {
|
||||
data: collectionsData,
|
||||
isLoading: isCollectionsLoading,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['collections', projectId],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.projects[':projectId'].collections.$get({
|
||||
param: { projectId },
|
||||
query: { first: '20', after: pageParam as string },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch collections')
|
||||
return (await res.json()) as unknown as {
|
||||
data: CollectionInfo[]
|
||||
pageInfo: { cursor?: string; total?: number }
|
||||
}
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
const { ref: inViewRef, inView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const collections = useMemo(
|
||||
() => collectionsData?.pages.flatMap((p) => p.data) || [],
|
||||
[collectionsData],
|
||||
)
|
||||
|
||||
if (!teamId || !rootFolderId || !projectInfo) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col bg-background min-h-0">
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<div
|
||||
className="md:hidden fixed inset-0 bg-black/50 z-40"
|
||||
onClick={() => setIsLeftSidebarCollapsed(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<>
|
||||
<div className="bg-background" style={{ width: leftSidebarWidth }}>
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
</div>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
|
||||
}}
|
||||
className="hidden md:block"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col min-h-0 bg-card overflow-hidden">
|
||||
<header className="h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10">
|
||||
<div className="flex items-center gap-2">
|
||||
<Bookmark className="h-5 w-5 text-primary" />
|
||||
<h1 className="font-bold text-lg text-foreground">{m.all_collections()}</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
{isCollectionsLoading ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
) : collections.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3">
|
||||
<LayoutGrid className="h-10 w-10 text-muted-foreground/50" />
|
||||
<p>{m.no_collections_yet()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border border-border rounded-xl bg-background overflow-hidden shadow-xs">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent bg-muted/20">
|
||||
<TableHead className="font-semibold px-4 py-3">
|
||||
{m.collection_name()}
|
||||
</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3">{m.creator()}</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3 w-[200px]">
|
||||
{m.created_date()}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{collections.map((collection) => (
|
||||
<TableRow
|
||||
key={collection.id}
|
||||
className="hover:bg-muted/10 transition-colors cursor-pointer"
|
||||
onClick={() =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/collections/$collectionId',
|
||||
params: { projectId, collectionId: collection.id },
|
||||
})
|
||||
}
|
||||
>
|
||||
<TableCell className="font-medium px-4 py-3.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Bookmark className="h-4 w-4 text-primary shrink-0" />
|
||||
<span className="text-foreground font-semibold hover:underline">
|
||||
{collection.name}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-6 w-6">
|
||||
{collection.creator?.image && (
|
||||
<AvatarImage
|
||||
src={collection.creator.image}
|
||||
alt={collection.creator.name}
|
||||
className="object-cover"
|
||||
/>
|
||||
)}
|
||||
<AvatarFallback className="text-[10px]">
|
||||
{getInitials(collection.creator?.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-sm font-medium text-foreground truncate max-w-[200px]">
|
||||
{collection.creator?.name || m.unknown()}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5 text-muted-foreground text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="h-3.5 w-3.5 text-muted-foreground/70" />
|
||||
<span>{new Date(collection.createdAt).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div ref={inViewRef} className="h-10 w-full flex items-center justify-center">
|
||||
{isFetchingNextPage && <Loader2 className="h-6 w-6 animate-spin text-primary" />}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/collections/')({
|
||||
component: CollectionsPage,
|
||||
loader: ({ context: { queryClient }, params: { projectId } }) =>
|
||||
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
|
||||
pendingComponent: () => <ProjectFolderSkeleton />,
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FileViewer } from '@/ui/components/file-viewer'
|
||||
import { CompareViewer } from '@/ui/components/compare/compare-viewer'
|
||||
import { pickDefaultCompareVersions } from '@/ui/components/compare/compare-utils'
|
||||
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
|
||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { useMemberStore } from '@/ui/stores/members'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useTopNavStore } from '@/ui/stores/top-nav'
|
||||
import { type Annotation } from '@/ui/types'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { InferRequestType, InferResponseType } from 'hono/client'
|
||||
|
||||
import type { AssetInfo, AssetInfoPaginatedList, CommentInfo } from '@shumai/dtos'
|
||||
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { MediaController } from '@/ui/components/viewers/types'
|
||||
|
||||
function FileViewPage() {
|
||||
const { projectId, fileId } = Route.useParams()
|
||||
const search = Route.useSearch()
|
||||
const versionAssetId = search.version
|
||||
const startTime = search.start
|
||||
const activeFileId = versionAssetId || fileId
|
||||
const compareLeftId = search.cmpLeft
|
||||
const compareRightId = search.cmpRight
|
||||
const compareActiveSide = search.cmpActive ?? 'left'
|
||||
const isCompareMode = !!search.compare && !!compareLeftId && !!compareRightId
|
||||
|
||||
const mediaControllerRef = useRef<MediaController | null>(null)
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
|
||||
const [compareActiveAsset, setCompareActiveAsset] = useState<AssetInfo | null>(null)
|
||||
const [seekRequest, setSeekRequest] = useState<{ second: number; nonce: number } | undefined>(
|
||||
undefined,
|
||||
)
|
||||
const [carouselState, setCarouselState] = useState<{
|
||||
show: boolean
|
||||
files: AssetInfo[]
|
||||
nextCursor?: string
|
||||
folderId?: string
|
||||
}>({ show: false, files: [], nextCursor: undefined, folderId: undefined })
|
||||
const $patchMetadata = client.api.files[':fileId'].metadata.$patch
|
||||
const { mutate: patchMetadata } = useMutation<
|
||||
InferResponseType<typeof $patchMetadata>,
|
||||
Error,
|
||||
InferRequestType<typeof $patchMetadata>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $patchMetadata(request)
|
||||
if (!res.ok) throw new Error('Failed to patch metadata')
|
||||
return (await res.json()) as unknown as InferResponseType<typeof $patchMetadata>
|
||||
},
|
||||
})
|
||||
const queryClient = useQueryClient()
|
||||
const { members, fetchMembers } = useMemberStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
useEffect(() => {
|
||||
if (teamId) {
|
||||
fetchMembers(teamId, true)
|
||||
}
|
||||
}, [teamId, fetchMembers])
|
||||
|
||||
const {
|
||||
data: stackData,
|
||||
isLoading: isStackLoading,
|
||||
isError: isStackError,
|
||||
isFetching: isStackFetching,
|
||||
} = useQuery({
|
||||
queryKey: ['files', fileId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: fileId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch stack')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
placeholderData: keepPreviousData,
|
||||
})
|
||||
|
||||
const {
|
||||
data: versionData,
|
||||
isLoading: isVersionLoading,
|
||||
isError: isVersionError,
|
||||
isFetching: isVersionFetching,
|
||||
} = useQuery({
|
||||
queryKey: ['files', versionAssetId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: versionAssetId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch version')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId && !!versionAssetId,
|
||||
placeholderData: keepPreviousData,
|
||||
})
|
||||
|
||||
const { data: versionsList } = useQuery({
|
||||
queryKey: ['version_stacks', fileId, 'versions'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.version_stacks[':stackId'].versions.$get({
|
||||
param: { stackId: fileId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch versions')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!projectId && !!fileId && (!!versionAssetId || isCompareMode),
|
||||
})
|
||||
|
||||
const { data: projectInfo } = useQuery({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
param: { projectId: projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch project')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const navigate = useNavigate()
|
||||
const { setProjectState, clearProjectState } = useTopNavStore()
|
||||
|
||||
const isLoading = isStackLoading || (!!versionAssetId && isVersionLoading)
|
||||
const isError = isStackError || (!!versionAssetId && isVersionError)
|
||||
const isFetching = isStackFetching || (!!versionAssetId && isVersionFetching)
|
||||
const fileData = versionData || stackData
|
||||
const versionsDataList = versionAssetId ? versionsList : stackData?.versionStack?.versions
|
||||
|
||||
useEffect(() => {
|
||||
if (fileData && projectInfo && teamId) {
|
||||
setProjectState({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName: projectInfo.name ?? '',
|
||||
ancestorFolders: fileData.ancestorFolders ?? [],
|
||||
currentAsset: {
|
||||
name: fileData.name,
|
||||
type: 'file',
|
||||
version: versionsDataList
|
||||
? (versionsDataList.find((v: { id: string }) => v.id === activeFileId)?.version ??
|
||||
versionsDataList.length)
|
||||
: undefined,
|
||||
mediaType: fileData.mediaType,
|
||||
},
|
||||
isRootFolder: false,
|
||||
fileId,
|
||||
downloadInfo: {
|
||||
originalKey: fileData.media?.original?.key,
|
||||
videoTranscodes: fileData.media?.videoTranscodes?.map((t) => ({
|
||||
key: t.key,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
isRaw: t.isRaw,
|
||||
})),
|
||||
},
|
||||
versions: versionsDataList,
|
||||
compareMode: isCompareMode,
|
||||
canCompareVersions: (versionsDataList?.length ?? 0) >= 2,
|
||||
onCompareVersions: () => {
|
||||
const pair = pickDefaultCompareVersions(versionsDataList)
|
||||
if (!pair) return
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (p: Record<string, unknown>) => ({
|
||||
...p,
|
||||
version: undefined,
|
||||
compare: true,
|
||||
cmpLeft: pair.left.id,
|
||||
cmpRight: pair.right.id,
|
||||
cmpActive: 'left' as const,
|
||||
}),
|
||||
})
|
||||
},
|
||||
onFolderClick: (id: string) => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: id },
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return () => clearProjectState()
|
||||
}, [
|
||||
teamId,
|
||||
projectId,
|
||||
projectInfo,
|
||||
fileData,
|
||||
versionsDataList,
|
||||
activeFileId,
|
||||
fileId,
|
||||
isCompareMode,
|
||||
setProjectState,
|
||||
clearProjectState,
|
||||
navigate,
|
||||
])
|
||||
|
||||
const parentFolderId = fileData?.ancestorFolders?.[0]?.id ?? projectInfo?.rootFolder ?? ''
|
||||
|
||||
useEffect(() => {
|
||||
if (!parentFolderId || !activeFileId) return
|
||||
if (carouselState.folderId === parentFolderId) {
|
||||
return
|
||||
}
|
||||
|
||||
let isMounted = true
|
||||
|
||||
const fetchCarouselData = async () => {
|
||||
try {
|
||||
let cursor = ''
|
||||
let found = false
|
||||
const allFiles: AssetInfo[] = []
|
||||
let lastCursor: string | undefined = undefined
|
||||
|
||||
for (let batch = 0; batch < 5; batch++) {
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: parentFolderId },
|
||||
json: {
|
||||
assetType: 'file',
|
||||
after: cursor,
|
||||
first: 200,
|
||||
recursively: false,
|
||||
conditions: [],
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error('Failed to search parent folder for carousel')
|
||||
}
|
||||
const result = (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
const batchFiles = (result.data || []) as AssetInfo[]
|
||||
allFiles.push(...batchFiles)
|
||||
|
||||
if (batchFiles.some((f) => f.id === activeFileId)) {
|
||||
found = true
|
||||
lastCursor = result.pageInfo?.cursor || undefined
|
||||
break
|
||||
}
|
||||
if (!result.pageInfo?.cursor || batchFiles.length < 200) {
|
||||
break
|
||||
}
|
||||
cursor = result.pageInfo.cursor
|
||||
}
|
||||
|
||||
if (isMounted) {
|
||||
if (found) {
|
||||
setCarouselState({
|
||||
show: true,
|
||||
files: allFiles,
|
||||
nextCursor: lastCursor,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
} else {
|
||||
setCarouselState({
|
||||
show: false,
|
||||
files: [],
|
||||
nextCursor: undefined,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
if (isMounted) {
|
||||
setCarouselState({
|
||||
show: false,
|
||||
files: [],
|
||||
nextCursor: undefined,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fetchCarouselData()
|
||||
|
||||
return () => {
|
||||
isMounted = false
|
||||
}
|
||||
}, [parentFolderId, activeFileId, carouselState.folderId])
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentTime(0)
|
||||
setSelectedCommentId(null)
|
||||
setAnnotations([])
|
||||
}, [fileData?.id])
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedCommentId(null)
|
||||
setAnnotations([])
|
||||
}, [compareActiveAsset?.id])
|
||||
|
||||
if (isLoading && !fileData) {
|
||||
return <FileDetailSkeleton />
|
||||
}
|
||||
|
||||
if (isError || !fileData || !projectInfo || !teamId) {
|
||||
return <div>{m.file_not_found()}</div>
|
||||
}
|
||||
|
||||
const sidebarFile = isCompareMode ? compareActiveAsset : (fileData as unknown as AssetInfo)
|
||||
const sidebarFileId = sidebarFile?.id ?? activeFileId
|
||||
|
||||
const handleSaveField = (fieldId: string, value: unknown) => {
|
||||
if (!teamId) return
|
||||
patchMetadata(
|
||||
{
|
||||
param: { fileId: sidebarFileId },
|
||||
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['files', sidebarFileId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const updateCompareSearch = (patch: Record<string, unknown>) => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (p: Record<string, unknown>) => ({ ...p, ...patch }),
|
||||
})
|
||||
}
|
||||
|
||||
const handleCompareExit = () => {
|
||||
const activeId = compareActiveSide === 'left' ? compareLeftId : compareRightId
|
||||
updateCompareSearch({
|
||||
compare: undefined,
|
||||
cmpLeft: undefined,
|
||||
cmpRight: undefined,
|
||||
cmpActive: undefined,
|
||||
version: activeId,
|
||||
})
|
||||
}
|
||||
|
||||
const handleCommentSelect = (comment: CommentInfo) => {
|
||||
setSelectedCommentId(comment.id || null)
|
||||
const newAnnotations = comment.annotations as Annotation[]
|
||||
if (newAnnotations && newAnnotations.length > 0) {
|
||||
setAnnotations(newAnnotations)
|
||||
} else {
|
||||
setAnnotations([])
|
||||
}
|
||||
|
||||
if (isCompareMode) {
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
setSeekRequest({ second: comment.second, nonce: Date.now() })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
mediaControllerRef.current?.seekTo(comment.second)
|
||||
mediaControllerRef.current?.pause()
|
||||
} else if (newAnnotations && newAnnotations.length > 0) {
|
||||
mediaControllerRef.current?.pause()
|
||||
}
|
||||
}
|
||||
|
||||
const handlePlay = () => {
|
||||
setAnnotations([])
|
||||
setSelectedCommentId(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-1 flex-col bg-background">
|
||||
<div className="h-full flex flex-1 overflow-hidden">
|
||||
<div className="flex-1 relative">
|
||||
{isFetching && !isCompareMode && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{isCompareMode && compareLeftId && compareRightId ? (
|
||||
<CompareViewer
|
||||
versions={versionsDataList ?? []}
|
||||
leftId={compareLeftId}
|
||||
rightId={compareRightId}
|
||||
activeSide={compareActiveSide}
|
||||
annotations={annotations}
|
||||
seekRequest={seekRequest}
|
||||
onActiveSideChange={(side) => updateCompareSearch({ cmpActive: side })}
|
||||
onSwitchVersion={(side, versionId) =>
|
||||
updateCompareSearch(
|
||||
side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
|
||||
)
|
||||
}
|
||||
onExit={handleCompareExit}
|
||||
onActiveAssetChange={setCompareActiveAsset}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
/>
|
||||
) : (
|
||||
<FileViewer
|
||||
file={fileData as unknown as AssetInfo}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
>
|
||||
{carouselState.show && (
|
||||
<FileViewerLeftSidebar
|
||||
projectId={projectId}
|
||||
currentAssetId={activeFileId}
|
||||
parentFolderId={parentFolderId}
|
||||
initialFiles={carouselState.files}
|
||||
initialNextCursor={carouselState.nextCursor}
|
||||
/>
|
||||
)}
|
||||
</FileViewer>
|
||||
)}
|
||||
</div>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
|
||||
}}
|
||||
className="hidden md:block"
|
||||
/>
|
||||
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
|
||||
<FileViewerRightSidebar
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
file={sidebarFile}
|
||||
onSaveField={handleSaveField}
|
||||
members={members}
|
||||
onCommentSelect={handleCommentSelect}
|
||||
currentTime={currentTime}
|
||||
onTyping={() => {
|
||||
if (isCompareMode) return
|
||||
mediaControllerRef.current?.pause()
|
||||
}}
|
||||
selectedCommentId={selectedCommentId}
|
||||
hideAnnotationControl={sidebarFile?.mediaType?.startsWith('audio/')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/projects/$projectId/files/$fileId')({
|
||||
component: FileViewPage,
|
||||
})
|
||||
@@ -1,465 +1,6 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FileViewer } from '@/ui/components/file-viewer'
|
||||
import { CompareViewer } from '@/ui/components/compare/compare-viewer'
|
||||
import { pickDefaultCompareVersions } from '@/ui/components/compare/compare-utils'
|
||||
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
|
||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { useMemberStore } from '@/ui/stores/members'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useTopNavStore } from '@/ui/stores/top-nav'
|
||||
import { type Annotation } from '@/ui/types'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { InferRequestType, InferResponseType } from 'hono/client'
|
||||
|
||||
import type { AssetInfo, AssetInfoPaginatedList, CommentInfo } from '@shumai/dtos'
|
||||
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { MediaController } from '@/ui/components/viewers/types'
|
||||
|
||||
function FileViewPage() {
|
||||
const { projectId, fileId } = Route.useParams()
|
||||
const search = Route.useSearch()
|
||||
const versionAssetId = search.version
|
||||
const startTime = search.start
|
||||
const activeFileId = versionAssetId || fileId
|
||||
const compareLeftId = search.cmpLeft
|
||||
const compareRightId = search.cmpRight
|
||||
const compareActiveSide = search.cmpActive ?? 'left'
|
||||
const isCompareMode = !!search.compare && !!compareLeftId && !!compareRightId
|
||||
|
||||
const mediaControllerRef = useRef<MediaController | null>(null)
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
|
||||
const [compareActiveAsset, setCompareActiveAsset] = useState<AssetInfo | null>(null)
|
||||
const [seekRequest, setSeekRequest] = useState<{ second: number; nonce: number } | undefined>(
|
||||
undefined,
|
||||
)
|
||||
const [carouselState, setCarouselState] = useState<{
|
||||
show: boolean
|
||||
files: AssetInfo[]
|
||||
nextCursor?: string
|
||||
folderId?: string
|
||||
}>({ show: false, files: [], nextCursor: undefined, folderId: undefined })
|
||||
const $patchMetadata = client.api.files[':fileId'].metadata.$patch
|
||||
const { mutate: patchMetadata } = useMutation<
|
||||
InferResponseType<typeof $patchMetadata>,
|
||||
Error,
|
||||
InferRequestType<typeof $patchMetadata>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $patchMetadata(request)
|
||||
if (!res.ok) throw new Error('Failed to patch metadata')
|
||||
return (await res.json()) as unknown as InferResponseType<typeof $patchMetadata>
|
||||
},
|
||||
})
|
||||
const queryClient = useQueryClient()
|
||||
const { members, fetchMembers } = useMemberStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
useEffect(() => {
|
||||
if (teamId) {
|
||||
fetchMembers(teamId, true)
|
||||
}
|
||||
}, [teamId, fetchMembers])
|
||||
|
||||
const {
|
||||
data: stackData,
|
||||
isLoading: isStackLoading,
|
||||
isError: isStackError,
|
||||
isFetching: isStackFetching,
|
||||
} = useQuery({
|
||||
queryKey: ['files', fileId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: fileId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch stack')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
placeholderData: keepPreviousData,
|
||||
})
|
||||
|
||||
const {
|
||||
data: versionData,
|
||||
isLoading: isVersionLoading,
|
||||
isError: isVersionError,
|
||||
isFetching: isVersionFetching,
|
||||
} = useQuery({
|
||||
queryKey: ['files', versionAssetId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: versionAssetId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch version')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId && !!versionAssetId,
|
||||
placeholderData: keepPreviousData,
|
||||
})
|
||||
|
||||
const { data: versionsList } = useQuery({
|
||||
queryKey: ['version_stacks', fileId, 'versions'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.version_stacks[':stackId'].versions.$get({
|
||||
param: { stackId: fileId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch versions')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!projectId && !!fileId && (!!versionAssetId || isCompareMode),
|
||||
})
|
||||
|
||||
const { data: projectInfo } = useQuery({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
param: { projectId: projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch project')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const navigate = useNavigate()
|
||||
const { setProjectState, clearProjectState } = useTopNavStore()
|
||||
|
||||
const isLoading = isStackLoading || (!!versionAssetId && isVersionLoading)
|
||||
const isError = isStackError || (!!versionAssetId && isVersionError)
|
||||
const isFetching = isStackFetching || (!!versionAssetId && isVersionFetching)
|
||||
const fileData = versionData || stackData
|
||||
const versionsDataList = versionAssetId ? versionsList : stackData?.versionStack?.versions
|
||||
|
||||
useEffect(() => {
|
||||
if (fileData && projectInfo && teamId) {
|
||||
setProjectState({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName: projectInfo.name ?? '',
|
||||
ancestorFolders: fileData.ancestorFolders ?? [],
|
||||
currentAsset: {
|
||||
name: fileData.name,
|
||||
type: 'file',
|
||||
version: versionsDataList
|
||||
? (versionsDataList.find((v: { id: string }) => v.id === activeFileId)?.version ??
|
||||
versionsDataList.length)
|
||||
: undefined,
|
||||
mediaType: fileData.mediaType,
|
||||
},
|
||||
isRootFolder: false,
|
||||
fileId,
|
||||
downloadInfo: {
|
||||
originalKey: fileData.media?.original?.key,
|
||||
videoTranscodes: fileData.media?.videoTranscodes?.map((t) => ({
|
||||
key: t.key,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
isRaw: t.isRaw,
|
||||
})),
|
||||
},
|
||||
versions: versionsDataList,
|
||||
compareMode: isCompareMode,
|
||||
canCompareVersions: (versionsDataList?.length ?? 0) >= 2,
|
||||
onCompareVersions: () => {
|
||||
const pair = pickDefaultCompareVersions(versionsDataList)
|
||||
if (!pair) return
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (p: Record<string, unknown>) => ({
|
||||
...p,
|
||||
version: undefined,
|
||||
compare: true,
|
||||
cmpLeft: pair.left.id,
|
||||
cmpRight: pair.right.id,
|
||||
cmpActive: 'left' as const,
|
||||
}),
|
||||
})
|
||||
},
|
||||
onFolderClick: (id: string) => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: id },
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return () => clearProjectState()
|
||||
}, [
|
||||
teamId,
|
||||
projectId,
|
||||
projectInfo,
|
||||
fileData,
|
||||
versionsDataList,
|
||||
activeFileId,
|
||||
fileId,
|
||||
isCompareMode,
|
||||
setProjectState,
|
||||
clearProjectState,
|
||||
navigate,
|
||||
])
|
||||
|
||||
const parentFolderId = fileData?.ancestorFolders?.[0]?.id ?? projectInfo?.rootFolder ?? ''
|
||||
|
||||
useEffect(() => {
|
||||
if (!parentFolderId || !activeFileId) return
|
||||
if (carouselState.folderId === parentFolderId) {
|
||||
return
|
||||
}
|
||||
|
||||
let isMounted = true
|
||||
|
||||
const fetchCarouselData = async () => {
|
||||
try {
|
||||
let cursor = ''
|
||||
let found = false
|
||||
const allFiles: AssetInfo[] = []
|
||||
let lastCursor: string | undefined = undefined
|
||||
|
||||
for (let batch = 0; batch < 5; batch++) {
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: parentFolderId },
|
||||
json: {
|
||||
assetType: 'file',
|
||||
after: cursor,
|
||||
first: 200,
|
||||
recursively: false,
|
||||
conditions: [],
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error('Failed to search parent folder for carousel')
|
||||
}
|
||||
const result = (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
const batchFiles = (result.data || []) as AssetInfo[]
|
||||
allFiles.push(...batchFiles)
|
||||
|
||||
if (batchFiles.some((f) => f.id === activeFileId)) {
|
||||
found = true
|
||||
lastCursor = result.pageInfo?.cursor || undefined
|
||||
break
|
||||
}
|
||||
if (!result.pageInfo?.cursor || batchFiles.length < 200) {
|
||||
break
|
||||
}
|
||||
cursor = result.pageInfo.cursor
|
||||
}
|
||||
|
||||
if (isMounted) {
|
||||
if (found) {
|
||||
setCarouselState({
|
||||
show: true,
|
||||
files: allFiles,
|
||||
nextCursor: lastCursor,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
} else {
|
||||
setCarouselState({
|
||||
show: false,
|
||||
files: [],
|
||||
nextCursor: undefined,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
if (isMounted) {
|
||||
setCarouselState({
|
||||
show: false,
|
||||
files: [],
|
||||
nextCursor: undefined,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fetchCarouselData()
|
||||
|
||||
return () => {
|
||||
isMounted = false
|
||||
}
|
||||
}, [parentFolderId, activeFileId, carouselState.folderId])
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentTime(0)
|
||||
setSelectedCommentId(null)
|
||||
setAnnotations([])
|
||||
}, [fileData?.id])
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedCommentId(null)
|
||||
setAnnotations([])
|
||||
}, [compareActiveAsset?.id])
|
||||
|
||||
if (isLoading && !fileData) {
|
||||
return <FileDetailSkeleton />
|
||||
}
|
||||
|
||||
if (isError || !fileData || !projectInfo || !teamId) {
|
||||
return <div>{m.file_not_found()}</div>
|
||||
}
|
||||
|
||||
const sidebarFile = isCompareMode ? compareActiveAsset : (fileData as unknown as AssetInfo)
|
||||
const sidebarFileId = sidebarFile?.id ?? activeFileId
|
||||
|
||||
const handleSaveField = (fieldId: string, value: unknown) => {
|
||||
if (!teamId) return
|
||||
patchMetadata(
|
||||
{
|
||||
param: { fileId: sidebarFileId },
|
||||
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['files', sidebarFileId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const updateCompareSearch = (patch: Record<string, unknown>) => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (p: Record<string, unknown>) => ({ ...p, ...patch }),
|
||||
})
|
||||
}
|
||||
|
||||
const handleCompareExit = () => {
|
||||
const activeId = compareActiveSide === 'left' ? compareLeftId : compareRightId
|
||||
updateCompareSearch({
|
||||
compare: undefined,
|
||||
cmpLeft: undefined,
|
||||
cmpRight: undefined,
|
||||
cmpActive: undefined,
|
||||
version: activeId,
|
||||
})
|
||||
}
|
||||
|
||||
const handleCommentSelect = (comment: CommentInfo) => {
|
||||
setSelectedCommentId(comment.id || null)
|
||||
const newAnnotations = comment.annotations as Annotation[]
|
||||
if (newAnnotations && newAnnotations.length > 0) {
|
||||
setAnnotations(newAnnotations)
|
||||
} else {
|
||||
setAnnotations([])
|
||||
}
|
||||
|
||||
if (isCompareMode) {
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
setSeekRequest({ second: comment.second, nonce: Date.now() })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
mediaControllerRef.current?.seekTo(comment.second)
|
||||
mediaControllerRef.current?.pause()
|
||||
} else if (newAnnotations && newAnnotations.length > 0) {
|
||||
mediaControllerRef.current?.pause()
|
||||
}
|
||||
}
|
||||
|
||||
const handlePlay = () => {
|
||||
setAnnotations([])
|
||||
setSelectedCommentId(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-1 flex-col bg-background">
|
||||
<div className="h-full flex flex-1 overflow-hidden">
|
||||
<div className="flex-1 relative">
|
||||
{isFetching && !isCompareMode && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{isCompareMode && compareLeftId && compareRightId ? (
|
||||
<CompareViewer
|
||||
versions={versionsDataList ?? []}
|
||||
leftId={compareLeftId}
|
||||
rightId={compareRightId}
|
||||
activeSide={compareActiveSide}
|
||||
annotations={annotations}
|
||||
seekRequest={seekRequest}
|
||||
onActiveSideChange={(side) => updateCompareSearch({ cmpActive: side })}
|
||||
onSwitchVersion={(side, versionId) =>
|
||||
updateCompareSearch(
|
||||
side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
|
||||
)
|
||||
}
|
||||
onExit={handleCompareExit}
|
||||
onActiveAssetChange={setCompareActiveAsset}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
/>
|
||||
) : (
|
||||
<FileViewer
|
||||
file={fileData as unknown as AssetInfo}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
>
|
||||
{carouselState.show && (
|
||||
<FileViewerLeftSidebar
|
||||
projectId={projectId}
|
||||
currentAssetId={activeFileId}
|
||||
parentFolderId={parentFolderId}
|
||||
initialFiles={carouselState.files}
|
||||
initialNextCursor={carouselState.nextCursor}
|
||||
/>
|
||||
)}
|
||||
</FileViewer>
|
||||
)}
|
||||
</div>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
|
||||
}}
|
||||
className="hidden md:block"
|
||||
/>
|
||||
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
|
||||
<FileViewerRightSidebar
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
file={sidebarFile}
|
||||
onSaveField={handleSaveField}
|
||||
members={members}
|
||||
onCommentSelect={handleCommentSelect}
|
||||
currentTime={currentTime}
|
||||
onTyping={() => {
|
||||
if (isCompareMode) return
|
||||
mediaControllerRef.current?.pause()
|
||||
}}
|
||||
selectedCommentId={selectedCommentId}
|
||||
hideAnnotationControl={sidebarFile?.mediaType?.startsWith('audio/')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/files/$fileId')({
|
||||
component: FileViewPage,
|
||||
validateSearch: (search: Record<string, unknown>) => {
|
||||
return {
|
||||
version: (search.version as string) || undefined,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
import { client } from '@/ui/api/client'
|
||||
import FileSystemManager from '@/ui/components/file-system-manager'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { projectInfoQueryOptions } from './$folderId'
|
||||
|
||||
function FolderPage() {
|
||||
const { projectId, folderId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: () =>
|
||||
(async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
return await res.json()
|
||||
})(),
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<FileSystemManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
assetId={folderId}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/projects/$projectId/folders/$folderId')({
|
||||
component: FolderPage,
|
||||
})
|
||||
@@ -1,12 +1,8 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import FileSystemManager from '@/ui/components/file-system-manager'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
const projectInfoQueryOptions = (projectId: string) => ({
|
||||
export const projectInfoQueryOptions = (projectId: string) => ({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
@@ -17,47 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
function FolderPage() {
|
||||
const { projectId, folderId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: () =>
|
||||
(async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
return await res.json()
|
||||
})(),
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<FileSystemManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
assetId={folderId}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/folders/$folderId')({
|
||||
component: FolderPage,
|
||||
loader: ({ context: { queryClient }, params: { projectId } }) =>
|
||||
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
|
||||
pendingComponent: () => <ProjectFolderSkeleton />,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
import { client } from '@/ui/api/client'
|
||||
import FileSystemManager from '@/ui/components/file-system-manager'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { projectInfoQueryOptions } from './index'
|
||||
|
||||
function ProjectPage() {
|
||||
const { projectId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<FileSystemManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
assetId={rootFolderId}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/projects/$projectId/')({
|
||||
component: ProjectPage,
|
||||
})
|
||||
@@ -1,12 +1,8 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import FileSystemManager from '@/ui/components/file-system-manager'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
const projectInfoQueryOptions = (projectId: string) => ({
|
||||
export const projectInfoQueryOptions = (projectId: string) => ({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
@@ -17,47 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
function ProjectPage() {
|
||||
const { projectId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<FileSystemManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
assetId={rootFolderId}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/')({
|
||||
component: ProjectPage,
|
||||
loader: ({ context: { queryClient }, params: { projectId } }) =>
|
||||
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
|
||||
pendingComponent: () => <ProjectFolderSkeleton />,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
import { client } from '@/ui/api/client'
|
||||
import FileSystemManager from '@/ui/components/file-system-manager'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { projectInfoQueryOptions } from './recently-deleted'
|
||||
|
||||
function RecentlyDeletedPage() {
|
||||
const { projectId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: () =>
|
||||
(async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
return await res.json()
|
||||
})(),
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<FileSystemManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
assetId="recently-deleted"
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/projects/$projectId/recently-deleted')({
|
||||
component: RecentlyDeletedPage,
|
||||
})
|
||||
@@ -1,12 +1,8 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import FileSystemManager from '@/ui/components/file-system-manager'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
const projectInfoQueryOptions = (projectId: string) => ({
|
||||
export const projectInfoQueryOptions = (projectId: string) => ({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
@@ -17,47 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
function RecentlyDeletedPage() {
|
||||
const { projectId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: () =>
|
||||
(async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
return await res.json()
|
||||
})(),
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<FileSystemManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
assetId="recently-deleted"
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/recently-deleted')({
|
||||
component: RecentlyDeletedPage,
|
||||
loader: ({ context: { queryClient }, params: { projectId } }) =>
|
||||
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
|
||||
pendingComponent: () => <ProjectFolderSkeleton />,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import ShareManager from '@/ui/components/share-manager'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { projectInfoQueryOptions } from './$shareId'
|
||||
|
||||
function SharePage() {
|
||||
const { projectId, shareId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<ShareManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
shareId={shareId}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/projects/$projectId/shares/$shareId')({
|
||||
component: SharePage,
|
||||
})
|
||||
@@ -1,12 +1,8 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import ShareManager from '@/ui/components/share-manager'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
const projectInfoQueryOptions = (projectId: string) => ({
|
||||
export const projectInfoQueryOptions = (projectId: string) => ({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
@@ -17,47 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
function SharePage() {
|
||||
const { projectId, shareId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<ShareManager
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
shareId={shareId}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/shares/$shareId')({
|
||||
component: SharePage,
|
||||
loader: ({ context: { queryClient }, params: { projectId } }) =>
|
||||
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
|
||||
pendingComponent: () => <ProjectFolderSkeleton />,
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FolderTree } from '@/ui/components/folder-tree'
|
||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/ui/components/ui/table'
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/ui/components/ui/avatar'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import {
|
||||
useMutation,
|
||||
useInfiniteQuery,
|
||||
useQueryClient,
|
||||
useSuspenseQuery,
|
||||
} from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Copy, ExternalLink, Calendar, Link2, Share2, Loader2 } from 'lucide-react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { toast } from 'sonner'
|
||||
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { projectInfoQueryOptions } from './index'
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
function SharesPage() {
|
||||
const { projectId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
|
||||
|
||||
const {
|
||||
shareConfigLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setShareConfigLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
} = useUiStore()
|
||||
|
||||
const {
|
||||
data: sharesData,
|
||||
isLoading: isSharesLoading,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['shares', projectId],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.projects[':projectId'].shares.$get({
|
||||
param: { projectId },
|
||||
query: { first: '20', after: pageParam as string },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch share links')
|
||||
return (await res.json()) as unknown as {
|
||||
data: ShareLinkInfo[]
|
||||
pageInfo: { cursor?: string; total?: number }
|
||||
}
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
const { ref: inViewRef, inView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const shares = useMemo(() => sharesData?.pages.flatMap((p) => p.data) || [], [sharesData])
|
||||
|
||||
const { mutate: toggleVisibility } = useMutation({
|
||||
mutationFn: async ({ id, isDisabled }: { id: string; isDisabled: boolean }) => {
|
||||
const res = await client.api.shares[':shareId'].$put({
|
||||
param: { shareId: id },
|
||||
json: { isDisabled },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update share link')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
|
||||
toast.success(m.share_link_status_updated())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(m.error_message({ message: err.message }))
|
||||
},
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !projectInfo) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
const handleCopyLink = (shareId: string) => {
|
||||
const url = `${window.location.origin}/share/${shareId}`
|
||||
navigator.clipboard.writeText(url)
|
||||
toast.success(m.link_copied())
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col bg-background min-h-0">
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<div
|
||||
className="md:hidden fixed inset-0 bg-black/50 z-40"
|
||||
onClick={() => setIsLeftSidebarCollapsed(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<>
|
||||
<div className="bg-background" style={{ width: leftSidebarWidth }}>
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
</div>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
|
||||
}}
|
||||
className="hidden md:block"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col min-h-0 bg-card overflow-hidden">
|
||||
<header className="h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10">
|
||||
<div className="flex items-center gap-2">
|
||||
<Share2 className="h-5 w-5 text-primary" />
|
||||
<h1 className="font-bold text-lg text-foreground">{m.all_share_links()}</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
{isSharesLoading ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
) : shares.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3">
|
||||
<Link2 className="h-10 w-10 text-muted-foreground/50" />
|
||||
<p>{m.no_share_links_yet()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border border-border rounded-xl bg-background overflow-hidden shadow-xs">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent bg-muted/20">
|
||||
<TableHead className="font-semibold px-4 py-3">{m.name()}</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3">{m.public_link()}</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3">{m.creator()}</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3 w-[150px]">
|
||||
{m.created_date()}
|
||||
</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3 text-right w-[120px]">
|
||||
{m.active()}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{shares.map((share) => {
|
||||
const shareUrl = `${window.location.origin}/share/${share.id}`
|
||||
return (
|
||||
<TableRow key={share.id} className="hover:bg-muted/10 transition-colors">
|
||||
<TableCell className="font-medium px-4 py-3.5">
|
||||
<span
|
||||
className="cursor-pointer hover:underline text-foreground"
|
||||
onClick={() =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/shares/$shareId',
|
||||
params: { projectId, shareId: share.id },
|
||||
})
|
||||
}
|
||||
>
|
||||
{share.name}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5 max-w-[300px]">
|
||||
<div className="flex items-center gap-2 group">
|
||||
<span
|
||||
className="truncate text-xs font-mono bg-muted/50 text-muted-foreground px-2 py-1 rounded-md border border-border cursor-pointer hover:bg-muted transition-colors flex-1"
|
||||
onClick={() => handleCopyLink(share.id)}
|
||||
title={m.click_to_copy_link()}
|
||||
>
|
||||
{shareUrl}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
onClick={() => handleCopyLink(share.id)}
|
||||
>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<a
|
||||
href={shareUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-muted-foreground hover:text-foreground inline-flex items-center"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-6 w-6">
|
||||
{share.creator?.image && (
|
||||
<AvatarImage
|
||||
src={share.creator.image}
|
||||
alt={share.creator.name}
|
||||
className="object-cover"
|
||||
/>
|
||||
)}
|
||||
<AvatarFallback className="text-[10px]">
|
||||
{getInitials(share.creator?.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-sm font-medium text-foreground truncate max-w-[150px]">
|
||||
{share.creator?.name || m.unknown()}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5 text-muted-foreground text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="h-3.5 w-3.5 text-muted-foreground/70" />
|
||||
<span>{new Date(share.createdAt).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5 text-right">
|
||||
<div className="flex justify-end">
|
||||
<Switch
|
||||
checked={!share.isDisabled}
|
||||
onCheckedChange={(checked) =>
|
||||
toggleVisibility({ id: share.id, isDisabled: !checked })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div ref={inViewRef} className="h-10 w-full flex items-center justify-center">
|
||||
{isFetchingNextPage && <Loader2 className="h-6 w-6 animate-spin text-primary" />}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/projects/$projectId/shares/')({
|
||||
component: SharesPage,
|
||||
})
|
||||
@@ -1,45 +1,8 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FolderTree } from '@/ui/components/folder-tree'
|
||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/ui/components/ui/table'
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/ui/components/ui/avatar'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import {
|
||||
useMutation,
|
||||
useInfiniteQuery,
|
||||
useQueryClient,
|
||||
useSuspenseQuery,
|
||||
} from '@tanstack/react-query'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Copy, ExternalLink, Calendar, Link2, Share2, Loader2 } from 'lucide-react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { toast } from 'sonner'
|
||||
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||
import { ProjectFolderSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
const projectInfoQueryOptions = (projectId: string) => ({
|
||||
export const projectInfoQueryOptions = (projectId: string) => ({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].$get({
|
||||
@@ -50,251 +13,7 @@ const projectInfoQueryOptions = (projectId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
function SharesPage() {
|
||||
const { projectId } = Route.useParams()
|
||||
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
|
||||
useEffect(() => {
|
||||
ensureTeamIdForProject(projectId)
|
||||
}, [projectId, ensureTeamIdForProject])
|
||||
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
|
||||
|
||||
const {
|
||||
shareConfigLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setShareConfigLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
} = useUiStore()
|
||||
|
||||
const {
|
||||
data: sharesData,
|
||||
isLoading: isSharesLoading,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['shares', projectId],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.projects[':projectId'].shares.$get({
|
||||
param: { projectId },
|
||||
query: { first: '20', after: pageParam as string },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch share links')
|
||||
return (await res.json()) as unknown as {
|
||||
data: ShareLinkInfo[]
|
||||
pageInfo: { cursor?: string; total?: number }
|
||||
}
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
const { ref: inViewRef, inView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const shares = useMemo(() => sharesData?.pages.flatMap((p) => p.data) || [], [sharesData])
|
||||
|
||||
const { mutate: toggleVisibility } = useMutation({
|
||||
mutationFn: async ({ id, isDisabled }: { id: string; isDisabled: boolean }) => {
|
||||
const res = await client.api.shares[':shareId'].$put({
|
||||
param: { shareId: id },
|
||||
json: { isDisabled },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update share link')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
|
||||
toast.success(m.share_link_status_updated())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(m.error_message({ message: err.message }))
|
||||
},
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !projectInfo) {
|
||||
return <ProjectFolderSkeleton />
|
||||
}
|
||||
|
||||
const handleCopyLink = (shareId: string) => {
|
||||
const url = `${window.location.origin}/share/${shareId}`
|
||||
navigator.clipboard.writeText(url)
|
||||
toast.success(m.link_copied())
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col bg-background min-h-0">
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<div
|
||||
className="md:hidden fixed inset-0 bg-black/50 z-40"
|
||||
onClick={() => setIsLeftSidebarCollapsed(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<>
|
||||
<div className="bg-background" style={{ width: leftSidebarWidth }}>
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectInfo.name ?? ''}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
</div>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
|
||||
}}
|
||||
className="hidden md:block"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col min-h-0 bg-card overflow-hidden">
|
||||
<header className="h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10">
|
||||
<div className="flex items-center gap-2">
|
||||
<Share2 className="h-5 w-5 text-primary" />
|
||||
<h1 className="font-bold text-lg text-foreground">{m.all_share_links()}</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
{isSharesLoading ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
) : shares.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3">
|
||||
<Link2 className="h-10 w-10 text-muted-foreground/50" />
|
||||
<p>{m.no_share_links_yet()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border border-border rounded-xl bg-background overflow-hidden shadow-xs">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent bg-muted/20">
|
||||
<TableHead className="font-semibold px-4 py-3">{m.name()}</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3">{m.public_link()}</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3">{m.creator()}</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3 w-[150px]">
|
||||
{m.created_date()}
|
||||
</TableHead>
|
||||
<TableHead className="font-semibold px-4 py-3 text-right w-[120px]">
|
||||
{m.active()}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{shares.map((share) => {
|
||||
const shareUrl = `${window.location.origin}/share/${share.id}`
|
||||
return (
|
||||
<TableRow key={share.id} className="hover:bg-muted/10 transition-colors">
|
||||
<TableCell className="font-medium px-4 py-3.5">
|
||||
<span
|
||||
className="cursor-pointer hover:underline text-foreground"
|
||||
onClick={() =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/shares/$shareId',
|
||||
params: { projectId, shareId: share.id },
|
||||
})
|
||||
}
|
||||
>
|
||||
{share.name}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5 max-w-[300px]">
|
||||
<div className="flex items-center gap-2 group">
|
||||
<span
|
||||
className="truncate text-xs font-mono bg-muted/50 text-muted-foreground px-2 py-1 rounded-md border border-border cursor-pointer hover:bg-muted transition-colors flex-1"
|
||||
onClick={() => handleCopyLink(share.id)}
|
||||
title={m.click_to_copy_link()}
|
||||
>
|
||||
{shareUrl}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
onClick={() => handleCopyLink(share.id)}
|
||||
>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<a
|
||||
href={shareUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-muted-foreground hover:text-foreground inline-flex items-center"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-6 w-6">
|
||||
{share.creator?.image && (
|
||||
<AvatarImage
|
||||
src={share.creator.image}
|
||||
alt={share.creator.name}
|
||||
className="object-cover"
|
||||
/>
|
||||
)}
|
||||
<AvatarFallback className="text-[10px]">
|
||||
{getInitials(share.creator?.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-sm font-medium text-foreground truncate max-w-[150px]">
|
||||
{share.creator?.name || m.unknown()}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5 text-muted-foreground text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="h-3.5 w-3.5 text-muted-foreground/70" />
|
||||
<span>{new Date(share.createdAt).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-4 py-3.5 text-right">
|
||||
<div className="flex justify-end">
|
||||
<Switch
|
||||
checked={!share.isDisabled}
|
||||
onCheckedChange={(checked) =>
|
||||
toggleVisibility({ id: share.id, isDisabled: !checked })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div ref={inViewRef} className="h-10 w-full flex items-center justify-center">
|
||||
{isFetchingNextPage && <Loader2 className="h-6 w-6 animate-spin text-primary" />}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/shares/')({
|
||||
component: SharesPage,
|
||||
loader: ({ context: { queryClient }, params: { projectId } }) =>
|
||||
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
|
||||
pendingComponent: () => <ProjectFolderSkeleton />,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { PublicShareManager } from '@/ui/components/public-share-manager'
|
||||
|
||||
function PublicShareFilePage() {
|
||||
const { shareId, fileId } = Route.useParams()
|
||||
const { start, version, compare, cmpLeft, cmpRight, cmpActive } = Route.useSearch()
|
||||
|
||||
return (
|
||||
<PublicShareManager
|
||||
shareId={shareId}
|
||||
initialFileId={fileId}
|
||||
startTime={start}
|
||||
versionId={version}
|
||||
compare={compare}
|
||||
compareLeftId={cmpLeft}
|
||||
compareRightId={cmpRight}
|
||||
compareActiveSide={cmpActive}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/share/$shareId/files/$fileId')({
|
||||
component: PublicShareFilePage,
|
||||
})
|
||||
@@ -1,26 +1,6 @@
|
||||
import { PublicShareManager } from '@/ui/components/public-share-manager'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
function PublicShareFilePage() {
|
||||
const { shareId, fileId } = Route.useParams()
|
||||
const { start, version, compare, cmpLeft, cmpRight, cmpActive } = Route.useSearch()
|
||||
|
||||
return (
|
||||
<PublicShareManager
|
||||
shareId={shareId}
|
||||
initialFileId={fileId}
|
||||
startTime={start}
|
||||
versionId={version}
|
||||
compare={compare}
|
||||
compareLeftId={cmpLeft}
|
||||
compareRightId={cmpRight}
|
||||
compareActiveSide={cmpActive}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/share/$shareId/files/$fileId')({
|
||||
component: PublicShareFilePage,
|
||||
validateSearch: (search: Record<string, unknown>) => {
|
||||
return {
|
||||
start: search.start ? Number(search.start) : undefined,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { PublicShareManager } from '@/ui/components/public-share-manager'
|
||||
|
||||
function PublicShareFolderPage() {
|
||||
const { shareId, folderId } = Route.useParams()
|
||||
|
||||
return <PublicShareManager shareId={shareId} initialFolderId={folderId} />
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/share/$shareId/folders/$folderId')({
|
||||
component: PublicShareFolderPage,
|
||||
})
|
||||
@@ -1,12 +1,3 @@
|
||||
import { PublicShareManager } from '@/ui/components/public-share-manager'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
function PublicShareFolderPage() {
|
||||
const { shareId, folderId } = Route.useParams()
|
||||
|
||||
return <PublicShareManager shareId={shareId} initialFolderId={folderId} />
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/share/$shareId/folders/$folderId')({
|
||||
component: PublicShareFolderPage,
|
||||
})
|
||||
export const Route = createFileRoute('/share/$shareId/folders/$folderId')({})
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { PublicShareManager } from '@/ui/components/public-share-manager'
|
||||
|
||||
function PublicShareIndexPage() {
|
||||
const { shareId } = Route.useParams()
|
||||
|
||||
return <PublicShareManager shareId={shareId} />
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/share/$shareId/')({
|
||||
component: PublicShareIndexPage,
|
||||
})
|
||||
@@ -1,12 +1,3 @@
|
||||
import { PublicShareManager } from '@/ui/components/public-share-manager'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
function PublicShareIndexPage() {
|
||||
const { shareId } = Route.useParams()
|
||||
|
||||
return <PublicShareManager shareId={shareId} />
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/share/$shareId/')({
|
||||
component: PublicShareIndexPage,
|
||||
})
|
||||
export const Route = createFileRoute('/share/$shareId/')({})
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import type { ProjectInfo } from '@shumai/dtos'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { MembersDialog } from '@/ui/components/members-dialog'
|
||||
import { ProjectDialog } from '@/ui/components/project-dialog'
|
||||
import { SortDropdown } from '@/ui/components/sort-dropdown'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { formatDateAgo } from '@/ui/lib/time'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { MoreHorizontal, PlusIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
function TeamPage() {
|
||||
const { teamId } = Route.useParams()
|
||||
const { canEdit, canAdmin } = usePermissions()
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// State for clicked project for animation
|
||||
const [clickedProjectId, setClickedProjectId] = useState<string | null>(null)
|
||||
|
||||
// State for Project Dialog
|
||||
const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false)
|
||||
const [projectDialogMode, setProjectDialogMode] = useState<'create' | 'edit'>('create')
|
||||
const [selectedProject, setSelectedProject] = useState<ProjectInfo | undefined>(undefined)
|
||||
|
||||
// State for Delete Alert
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [projectToDelete, setProjectToDelete] = useState<ProjectInfo | undefined>(undefined)
|
||||
const [deleteConfirmText, setDeleteConfirmText] = useState('')
|
||||
|
||||
// State for Members Dialog
|
||||
const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
|
||||
|
||||
// Sort State
|
||||
const [sortBy, setSortBy] = useState<string>('name')
|
||||
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
|
||||
|
||||
const $getProjects = client.api.teams[':teamId'].projects.$get
|
||||
const { data: projects } = useSuspenseQuery({
|
||||
queryKey: ['teams', teamId, 'projects', sortBy, sortDirection],
|
||||
queryFn: async () => {
|
||||
const res = await $getProjects({
|
||||
param: { teamId: teamId },
|
||||
query: { sortBy, sortDirection },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch projects')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: members } = useQuery({
|
||||
queryKey: ['teams', teamId, 'members'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].members.$get({
|
||||
param: { teamId: teamId },
|
||||
query: {},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch members')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: me } = useQuery({
|
||||
queryKey: ['teams', teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId: teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch me')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const $inviteTeam = client.api.teams[':teamId'].invite.$post
|
||||
const inviteMutation = useMutation<
|
||||
InferResponseType<typeof $inviteTeam>,
|
||||
Error,
|
||||
InferRequestType<typeof $inviteTeam>
|
||||
>({
|
||||
mutationFn: async (args) => {
|
||||
const res = await $inviteTeam(args)
|
||||
if (!res.ok) {
|
||||
throw new Error('Failed to invite')
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const deleteProjectMutation = useMutation({
|
||||
mutationFn: async (projectId: string) => {
|
||||
const res = await client.api.projects[':projectId'].$delete({
|
||||
param: { projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to delete project')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] })
|
||||
},
|
||||
})
|
||||
|
||||
const toggleProjectNotificationsMutation = useMutation({
|
||||
mutationFn: async (project: ProjectInfo) => {
|
||||
const res = await client.api.projects[':projectId'].$put({
|
||||
param: { projectId: project.id! },
|
||||
json: {
|
||||
enableNotification: !project.enableNotification,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update project notification settings')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] })
|
||||
toast.success(m.project_notification_updated())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_update_project_notification())
|
||||
},
|
||||
})
|
||||
|
||||
const handleCreateProjectClick = () => {
|
||||
setProjectDialogMode('create')
|
||||
setSelectedProject(undefined)
|
||||
setIsProjectDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleCreateCardClick = () => {
|
||||
setClickedProjectId('create')
|
||||
setTimeout(() => {
|
||||
setClickedProjectId(null)
|
||||
}, 100)
|
||||
|
||||
setTimeout(() => {
|
||||
handleCreateProjectClick()
|
||||
}, 200)
|
||||
}
|
||||
|
||||
const handleEditProjectClick = (project: ProjectInfo) => {
|
||||
setProjectDialogMode('edit')
|
||||
setSelectedProject(project)
|
||||
setIsProjectDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteProjectClick = (project: ProjectInfo) => {
|
||||
setProjectToDelete(project)
|
||||
setDeleteConfirmText('')
|
||||
setIsDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleConfirmDelete = async () => {
|
||||
if (projectToDelete && deleteConfirmText === 'delete') {
|
||||
try {
|
||||
await deleteProjectMutation.mutateAsync(projectToDelete.id!)
|
||||
setIsDeleteDialogOpen(false)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleCardClick = (projectId: string, e: React.MouseEvent) => {
|
||||
if (e.detail > 1) return
|
||||
|
||||
setClickedProjectId(projectId)
|
||||
|
||||
// Restore scale after 100ms for "shrink and restore" effect
|
||||
setTimeout(() => {
|
||||
setClickedProjectId(null)
|
||||
}, 100)
|
||||
|
||||
// Navigate after 200ms
|
||||
setTimeout(() => {
|
||||
navigate({
|
||||
to: '/projects/$projectId',
|
||||
params: { projectId },
|
||||
})
|
||||
}, 200)
|
||||
}
|
||||
|
||||
const handleInvite = async (role: 'editor' | 'reviewer') => {
|
||||
const res = await inviteMutation.mutateAsync({
|
||||
param: { teamId: teamId },
|
||||
json: { role },
|
||||
})
|
||||
return res.code
|
||||
}
|
||||
|
||||
const updateMemberRoleMutation = useMutation({
|
||||
mutationFn: async ({ userId, role }: { userId: string; role: 'editor' | 'reviewer' }) => {
|
||||
const res = await client.api.teams[':teamId'].members[':userId'].$patch({
|
||||
param: { teamId, userId },
|
||||
json: { role },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update member role')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const removeMemberMutation = useMutation({
|
||||
mutationFn: async (userId: string) => {
|
||||
const res = await client.api.teams[':teamId'].members[':userId'].$delete({
|
||||
param: { teamId, userId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to remove member')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
const handleSortChange = (newSortBy: string, newSortDirection: 'asc' | 'desc') => {
|
||||
setSortBy(newSortBy)
|
||||
setSortDirection(newSortDirection)
|
||||
}
|
||||
|
||||
const safeMembers = Array.isArray(members) ? members : []
|
||||
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="flex flex-wrap items-center justify-between mb-4 gap-4">
|
||||
<h1 className="text-2xl font-bold">{m.projects()}</h1>
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<div
|
||||
className="flex items-center -space-x-2 cursor-pointer hover:opacity-90"
|
||||
onClick={() => setIsMembersDialogOpen(true)}
|
||||
>
|
||||
{safeMembers.slice(0, 3).map((member) => (
|
||||
<Avatar key={member.id} className="border-2 border-background w-8 h-8">
|
||||
{member.image && (
|
||||
<AvatarImage src={member.image} alt={member.name} className="object-cover" />
|
||||
)}
|
||||
<AvatarFallback className="text-[10px]">{getInitials(member.name)}</AvatarFallback>
|
||||
</Avatar>
|
||||
))}
|
||||
{safeMembers.length > 3 && (
|
||||
<div className="flex items-center justify-center w-8 h-8 rounded-full border-2 border-background bg-muted text-[10px] font-medium">
|
||||
+{safeMembers.length - 3}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<SortDropdown
|
||||
sortBy={sortBy}
|
||||
sortDirection={sortDirection}
|
||||
onSortChange={handleSortChange}
|
||||
/>
|
||||
{canEdit && (
|
||||
<Button
|
||||
className="bg-orange-600 hover:bg-orange-700 text-white gap-2"
|
||||
onClick={handleCreateProjectClick}
|
||||
>
|
||||
<PlusIcon className="w-4 h-4" />
|
||||
{m.create_project()}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
|
||||
{projects.data?.map((project: ProjectInfo) => (
|
||||
<div
|
||||
key={project.id}
|
||||
className={cn(
|
||||
'shadow-md relative border rounded-xl overflow-hidden cursor-pointer transition-transform duration-100 ease-in-out',
|
||||
clickedProjectId === project.id ? 'scale-95' : 'scale-100',
|
||||
)}
|
||||
onClick={(e) => handleCardClick(project.id!, e)}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<div className="relative w-full h-full aspect-square flex items-center justify-center bg-zinc-400/20">
|
||||
{project.coverImage ? (
|
||||
<img
|
||||
src={project.coverImage}
|
||||
alt={project.name}
|
||||
className="w-full h-full object-cover rounded"
|
||||
/>
|
||||
) : (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 180.95 164.7"
|
||||
preserveAspectRatio="xMidYMid slice"
|
||||
className="w-full h-full object-cover rounded"
|
||||
>
|
||||
<polygon
|
||||
fill="#FC9F8E"
|
||||
points="0 18.5 0 76.0 151.69 164.7 180.95 164.7 180.95 113.6"
|
||||
/>
|
||||
<polygon
|
||||
fill="#FEBAB8"
|
||||
points="0 0 74.58 61.5 90.53 51.6 110.33 63.9 180.95 18.9 180.95 0"
|
||||
/>
|
||||
<polyline
|
||||
fill="#FAA5A5"
|
||||
points="0 18.5 74.58 61.5 90.53 51.6 110.33 63.9 180.95 18.9 180.95 0 0 0"
|
||||
/>
|
||||
<polygon fill="#EC5B6C" points="0 76.0 0 164.7 151.69 164.7" />
|
||||
<polygon
|
||||
fill="#E85C71"
|
||||
points="180.95 18.9 110.33 63.9 117.37 68.0 117.26 73.4 180.95 113.6"
|
||||
/>
|
||||
<polygon
|
||||
fill="#C8405B"
|
||||
points="117.26 73.4 117.37 99.0 90.53 114.9 174.35 164.7 180.95 164.7 180.95 113.6"
|
||||
/>
|
||||
<polygon fill="#FFCCBE" points="90.53 51.6 63.69 68.1 90.53 83.4" />
|
||||
<path
|
||||
fill="#FB9991"
|
||||
d="M 90.53 51.6 L 90.53 61.3 L 100.87 67.4 L 90.53 73.5 L 90.53 83.4 L 117.37 68.0 C 117.15 67.6 90.53 51.6 90.53 51.6 Z"
|
||||
/>
|
||||
<path
|
||||
fill="#FFEACD"
|
||||
d="M 63.69 68.1 C 63.47 68.5 64.02 99.3 64.02 99.3 C 64.02 99.3 64.46 99.6 64.9 99.9 L 90.53 83.4 L 63.69 68.1 Z"
|
||||
/>
|
||||
<polygon fill="#FFCFB5" points="64.02 99.3 90.53 114.9 90.53 83.4" />
|
||||
<path fill="#F67D73" d="M 90.53 83.4 L 90.53 114.9 L 117.37 99.0 Z" />
|
||||
<path fill="#F26560" d="M 90.53 83.4 L 117.37 99.0 L 117.37 68.0 Z" />
|
||||
<polygon fill="#EB5F5B" points="80.08 67.5 90.53 73.5 90.53 61.3" />
|
||||
<polygon fill="#DB4D50" points="90.53 61.3 90.53 73.5 100.87 67.4" />
|
||||
</svg>
|
||||
)}
|
||||
<div className="absolute bottom-0 left-0 w-full h-[65%] bg-linear-to-t from-black/35 to-black/0" />
|
||||
<p className="absolute left-1 bottom-2 text-white">{project.name}</p>
|
||||
</div>
|
||||
<div className="px-2 h-10 flex justify-between items-center">
|
||||
<p className="truncate pr-1 text-xs text-muted-foreground">
|
||||
{m.updated_ago()} {formatDateAgo((project.updatedAt as string) ?? '')}
|
||||
</p>
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="hover:bg-muted outline-none flex px-1">
|
||||
<MoreHorizontal className="w-5 h-5 text-muted-foreground" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{canEdit && (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleEditProjectClick(project)
|
||||
}}
|
||||
>
|
||||
{m.project_settings()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
className="flex items-center justify-between gap-4 cursor-pointer"
|
||||
onSelect={(e) => {
|
||||
e.preventDefault()
|
||||
toggleProjectNotificationsMutation.mutate(project)
|
||||
}}
|
||||
>
|
||||
<span>{m.notification()}</span>
|
||||
<Switch
|
||||
checked={project.enableNotification ?? true}
|
||||
className="pointer-events-none"
|
||||
/>
|
||||
</DropdownMenuItem>
|
||||
{canAdmin && (
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => handleDeleteProjectClick(project)}
|
||||
>
|
||||
{m.delete()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{canEdit && (
|
||||
<div
|
||||
className={cn(
|
||||
'shadow-md relative border rounded-xl overflow-hidden cursor-pointer transition-transform duration-100 ease-in-out border-dashed hover:border-orange-600/50 group',
|
||||
clickedProjectId === 'create' ? 'scale-95' : 'scale-100',
|
||||
)}
|
||||
onClick={handleCreateCardClick}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<div className="relative w-full aspect-square flex items-center justify-center bg-zinc-400/5 group-hover:bg-orange-600/5 transition-colors">
|
||||
<PlusIcon className="w-8 h-8 text-zinc-400 group-hover:text-orange-600 transition-colors" />
|
||||
</div>
|
||||
<div className="px-2 h-10 flex items-center justify-center bg-zinc-400/10 border-t group-hover:bg-orange-600/10 transition-colors">
|
||||
<p className="text-sm text-muted-foreground group-hover:text-orange-600 transition-colors">
|
||||
{m.create_project()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ProjectDialog
|
||||
open={isProjectDialogOpen}
|
||||
onOpenChange={setIsProjectDialogOpen}
|
||||
mode={projectDialogMode}
|
||||
teamId={teamId}
|
||||
project={selectedProject}
|
||||
/>
|
||||
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.are_you_sure()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{m.delete_project_warning({ name: projectToDelete?.name ?? '' })}
|
||||
<div className="mt-4 flex flex-col gap-2 text-foreground">
|
||||
<span className="text-sm font-medium">{m.type_delete_to_confirm()}</span>
|
||||
<Input
|
||||
value={deleteConfirmText}
|
||||
onChange={(e) => setDeleteConfirmText(e.target.value)}
|
||||
placeholder={m.delete_placeholder()}
|
||||
className="h-9"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteProjectMutation.isPending}>
|
||||
{m.cancel()}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
handleConfirmDelete()
|
||||
}}
|
||||
disabled={deleteConfirmText !== 'delete' || deleteProjectMutation.isPending}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteProjectMutation.isPending ? m.deleting() : m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<MembersDialog
|
||||
open={isMembersDialogOpen}
|
||||
onOpenChange={setIsMembersDialogOpen}
|
||||
title={m.team_members()}
|
||||
type="team"
|
||||
members={safeMembers}
|
||||
isOwner={me?.role === 'owner'}
|
||||
onInvite={handleInvite}
|
||||
onUpdateRole={async (memberId, role) => {
|
||||
await updateMemberRoleMutation.mutateAsync({ userId: memberId, role })
|
||||
}}
|
||||
onRemoveMember={async (memberId) => {
|
||||
await removeMemberMutation.mutateAsync(memberId)
|
||||
}}
|
||||
currentUserId={me?.id}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/teams/$teamId/')({
|
||||
component: TeamPage,
|
||||
})
|
||||
@@ -1,497 +1,3 @@
|
||||
import type { ProjectInfo } from '@shumai/dtos'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { MembersDialog } from '@/ui/components/members-dialog'
|
||||
import { ProjectDialog } from '@/ui/components/project-dialog'
|
||||
import { SortDropdown } from '@/ui/components/sort-dropdown'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { formatDateAgo } from '@/ui/lib/time'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { MoreHorizontal, PlusIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
function TeamPage() {
|
||||
const { teamId } = Route.useParams()
|
||||
const { canEdit, canAdmin } = usePermissions()
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// State for clicked project for animation
|
||||
const [clickedProjectId, setClickedProjectId] = useState<string | null>(null)
|
||||
|
||||
// State for Project Dialog
|
||||
const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false)
|
||||
const [projectDialogMode, setProjectDialogMode] = useState<'create' | 'edit'>('create')
|
||||
const [selectedProject, setSelectedProject] = useState<ProjectInfo | undefined>(undefined)
|
||||
|
||||
// State for Delete Alert
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [projectToDelete, setProjectToDelete] = useState<ProjectInfo | undefined>(undefined)
|
||||
const [deleteConfirmText, setDeleteConfirmText] = useState('')
|
||||
|
||||
// State for Members Dialog
|
||||
const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
|
||||
|
||||
// Sort State
|
||||
const [sortBy, setSortBy] = useState<string>('name')
|
||||
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
|
||||
|
||||
const $getProjects = client.api.teams[':teamId'].projects.$get
|
||||
const { data: projects } = useSuspenseQuery({
|
||||
queryKey: ['teams', teamId, 'projects', sortBy, sortDirection],
|
||||
queryFn: async () => {
|
||||
const res = await $getProjects({
|
||||
param: { teamId: teamId },
|
||||
query: { sortBy, sortDirection },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch projects')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: members } = useQuery({
|
||||
queryKey: ['teams', teamId, 'members'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].members.$get({
|
||||
param: { teamId: teamId },
|
||||
query: {},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch members')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: me } = useQuery({
|
||||
queryKey: ['teams', teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId: teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch me')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const $inviteTeam = client.api.teams[':teamId'].invite.$post
|
||||
const inviteMutation = useMutation<
|
||||
InferResponseType<typeof $inviteTeam>,
|
||||
Error,
|
||||
InferRequestType<typeof $inviteTeam>
|
||||
>({
|
||||
mutationFn: async (args) => {
|
||||
const res = await $inviteTeam(args)
|
||||
if (!res.ok) {
|
||||
throw new Error('Failed to invite')
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const deleteProjectMutation = useMutation({
|
||||
mutationFn: async (projectId: string) => {
|
||||
const res = await client.api.projects[':projectId'].$delete({
|
||||
param: { projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to delete project')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] })
|
||||
},
|
||||
})
|
||||
|
||||
const toggleProjectNotificationsMutation = useMutation({
|
||||
mutationFn: async (project: ProjectInfo) => {
|
||||
const res = await client.api.projects[':projectId'].$put({
|
||||
param: { projectId: project.id! },
|
||||
json: {
|
||||
enableNotification: !project.enableNotification,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update project notification settings')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] })
|
||||
toast.success(m.project_notification_updated())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_update_project_notification())
|
||||
},
|
||||
})
|
||||
|
||||
const handleCreateProjectClick = () => {
|
||||
setProjectDialogMode('create')
|
||||
setSelectedProject(undefined)
|
||||
setIsProjectDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleCreateCardClick = () => {
|
||||
setClickedProjectId('create')
|
||||
setTimeout(() => {
|
||||
setClickedProjectId(null)
|
||||
}, 100)
|
||||
|
||||
setTimeout(() => {
|
||||
handleCreateProjectClick()
|
||||
}, 200)
|
||||
}
|
||||
|
||||
const handleEditProjectClick = (project: ProjectInfo) => {
|
||||
setProjectDialogMode('edit')
|
||||
setSelectedProject(project)
|
||||
setIsProjectDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteProjectClick = (project: ProjectInfo) => {
|
||||
setProjectToDelete(project)
|
||||
setDeleteConfirmText('')
|
||||
setIsDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleConfirmDelete = async () => {
|
||||
if (projectToDelete && deleteConfirmText === 'delete') {
|
||||
try {
|
||||
await deleteProjectMutation.mutateAsync(projectToDelete.id!)
|
||||
setIsDeleteDialogOpen(false)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleCardClick = (projectId: string, e: React.MouseEvent) => {
|
||||
if (e.detail > 1) return
|
||||
|
||||
setClickedProjectId(projectId)
|
||||
|
||||
// Restore scale after 100ms for "shrink and restore" effect
|
||||
setTimeout(() => {
|
||||
setClickedProjectId(null)
|
||||
}, 100)
|
||||
|
||||
// Navigate after 200ms
|
||||
setTimeout(() => {
|
||||
navigate({
|
||||
to: '/projects/$projectId',
|
||||
params: { projectId },
|
||||
})
|
||||
}, 200)
|
||||
}
|
||||
|
||||
const handleInvite = async (role: 'editor' | 'reviewer') => {
|
||||
const res = await inviteMutation.mutateAsync({
|
||||
param: { teamId: teamId },
|
||||
json: { role },
|
||||
})
|
||||
return res.code
|
||||
}
|
||||
|
||||
const updateMemberRoleMutation = useMutation({
|
||||
mutationFn: async ({ userId, role }: { userId: string; role: 'editor' | 'reviewer' }) => {
|
||||
const res = await client.api.teams[':teamId'].members[':userId'].$patch({
|
||||
param: { teamId, userId },
|
||||
json: { role },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update member role')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const removeMemberMutation = useMutation({
|
||||
mutationFn: async (userId: string) => {
|
||||
const res = await client.api.teams[':teamId'].members[':userId'].$delete({
|
||||
param: { teamId, userId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to remove member')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
const handleSortChange = (newSortBy: string, newSortDirection: 'asc' | 'desc') => {
|
||||
setSortBy(newSortBy)
|
||||
setSortDirection(newSortDirection)
|
||||
}
|
||||
|
||||
const safeMembers = Array.isArray(members) ? members : []
|
||||
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="flex flex-wrap items-center justify-between mb-4 gap-4">
|
||||
<h1 className="text-2xl font-bold">{m.projects()}</h1>
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<div
|
||||
className="flex items-center -space-x-2 cursor-pointer hover:opacity-90"
|
||||
onClick={() => setIsMembersDialogOpen(true)}
|
||||
>
|
||||
{safeMembers.slice(0, 3).map((member) => (
|
||||
<Avatar key={member.id} className="border-2 border-background w-8 h-8">
|
||||
{member.image && (
|
||||
<AvatarImage src={member.image} alt={member.name} className="object-cover" />
|
||||
)}
|
||||
<AvatarFallback className="text-[10px]">{getInitials(member.name)}</AvatarFallback>
|
||||
</Avatar>
|
||||
))}
|
||||
{safeMembers.length > 3 && (
|
||||
<div className="flex items-center justify-center w-8 h-8 rounded-full border-2 border-background bg-muted text-[10px] font-medium">
|
||||
+{safeMembers.length - 3}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<SortDropdown
|
||||
sortBy={sortBy}
|
||||
sortDirection={sortDirection}
|
||||
onSortChange={handleSortChange}
|
||||
/>
|
||||
{canEdit && (
|
||||
<Button
|
||||
className="bg-orange-600 hover:bg-orange-700 text-white gap-2"
|
||||
onClick={handleCreateProjectClick}
|
||||
>
|
||||
<PlusIcon className="w-4 h-4" />
|
||||
{m.create_project()}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
|
||||
{projects.data?.map((project: ProjectInfo) => (
|
||||
<div
|
||||
key={project.id}
|
||||
className={cn(
|
||||
'shadow-md relative border rounded-xl overflow-hidden cursor-pointer transition-transform duration-100 ease-in-out',
|
||||
clickedProjectId === project.id ? 'scale-95' : 'scale-100',
|
||||
)}
|
||||
onClick={(e) => handleCardClick(project.id!, e)}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<div className="relative w-full h-full aspect-square flex items-center justify-center bg-zinc-400/20">
|
||||
{project.coverImage ? (
|
||||
<img
|
||||
src={project.coverImage}
|
||||
alt={project.name}
|
||||
className="w-full h-full object-cover rounded"
|
||||
/>
|
||||
) : (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 180.95 164.7"
|
||||
preserveAspectRatio="xMidYMid slice"
|
||||
className="w-full h-full object-cover rounded"
|
||||
>
|
||||
<polygon
|
||||
fill="#FC9F8E"
|
||||
points="0 18.5 0 76.0 151.69 164.7 180.95 164.7 180.95 113.6"
|
||||
/>
|
||||
<polygon
|
||||
fill="#FEBAB8"
|
||||
points="0 0 74.58 61.5 90.53 51.6 110.33 63.9 180.95 18.9 180.95 0"
|
||||
/>
|
||||
<polyline
|
||||
fill="#FAA5A5"
|
||||
points="0 18.5 74.58 61.5 90.53 51.6 110.33 63.9 180.95 18.9 180.95 0 0 0"
|
||||
/>
|
||||
<polygon fill="#EC5B6C" points="0 76.0 0 164.7 151.69 164.7" />
|
||||
<polygon
|
||||
fill="#E85C71"
|
||||
points="180.95 18.9 110.33 63.9 117.37 68.0 117.26 73.4 180.95 113.6"
|
||||
/>
|
||||
<polygon
|
||||
fill="#C8405B"
|
||||
points="117.26 73.4 117.37 99.0 90.53 114.9 174.35 164.7 180.95 164.7 180.95 113.6"
|
||||
/>
|
||||
<polygon fill="#FFCCBE" points="90.53 51.6 63.69 68.1 90.53 83.4" />
|
||||
<path
|
||||
fill="#FB9991"
|
||||
d="M 90.53 51.6 L 90.53 61.3 L 100.87 67.4 L 90.53 73.5 L 90.53 83.4 L 117.37 68.0 C 117.15 67.6 90.53 51.6 90.53 51.6 Z"
|
||||
/>
|
||||
<path
|
||||
fill="#FFEACD"
|
||||
d="M 63.69 68.1 C 63.47 68.5 64.02 99.3 64.02 99.3 C 64.02 99.3 64.46 99.6 64.9 99.9 L 90.53 83.4 L 63.69 68.1 Z"
|
||||
/>
|
||||
<polygon fill="#FFCFB5" points="64.02 99.3 90.53 114.9 90.53 83.4" />
|
||||
<path fill="#F67D73" d="M 90.53 83.4 L 90.53 114.9 L 117.37 99.0 Z" />
|
||||
<path fill="#F26560" d="M 90.53 83.4 L 117.37 99.0 L 117.37 68.0 Z" />
|
||||
<polygon fill="#EB5F5B" points="80.08 67.5 90.53 73.5 90.53 61.3" />
|
||||
<polygon fill="#DB4D50" points="90.53 61.3 90.53 73.5 100.87 67.4" />
|
||||
</svg>
|
||||
)}
|
||||
<div className="absolute bottom-0 left-0 w-full h-[65%] bg-linear-to-t from-black/35 to-black/0" />
|
||||
<p className="absolute left-1 bottom-2 text-white">{project.name}</p>
|
||||
</div>
|
||||
<div className="px-2 h-10 flex justify-between items-center">
|
||||
<p className="truncate pr-1 text-xs text-muted-foreground">
|
||||
{m.updated_ago()} {formatDateAgo((project.updatedAt as string) ?? '')}
|
||||
</p>
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="hover:bg-muted outline-none flex px-1">
|
||||
<MoreHorizontal className="w-5 h-5 text-muted-foreground" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{canEdit && (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleEditProjectClick(project)
|
||||
}}
|
||||
>
|
||||
{m.project_settings()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
className="flex items-center justify-between gap-4 cursor-pointer"
|
||||
onSelect={(e) => {
|
||||
e.preventDefault()
|
||||
toggleProjectNotificationsMutation.mutate(project)
|
||||
}}
|
||||
>
|
||||
<span>{m.notification()}</span>
|
||||
<Switch
|
||||
checked={project.enableNotification ?? true}
|
||||
className="pointer-events-none"
|
||||
/>
|
||||
</DropdownMenuItem>
|
||||
{canAdmin && (
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => handleDeleteProjectClick(project)}
|
||||
>
|
||||
{m.delete()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{canEdit && (
|
||||
<div
|
||||
className={cn(
|
||||
'shadow-md relative border rounded-xl overflow-hidden cursor-pointer transition-transform duration-100 ease-in-out border-dashed hover:border-orange-600/50 group',
|
||||
clickedProjectId === 'create' ? 'scale-95' : 'scale-100',
|
||||
)}
|
||||
onClick={handleCreateCardClick}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<div className="relative w-full aspect-square flex items-center justify-center bg-zinc-400/5 group-hover:bg-orange-600/5 transition-colors">
|
||||
<PlusIcon className="w-8 h-8 text-zinc-400 group-hover:text-orange-600 transition-colors" />
|
||||
</div>
|
||||
<div className="px-2 h-10 flex items-center justify-center bg-zinc-400/10 border-t group-hover:bg-orange-600/10 transition-colors">
|
||||
<p className="text-sm text-muted-foreground group-hover:text-orange-600 transition-colors">
|
||||
{m.create_project()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ProjectDialog
|
||||
open={isProjectDialogOpen}
|
||||
onOpenChange={setIsProjectDialogOpen}
|
||||
mode={projectDialogMode}
|
||||
teamId={teamId}
|
||||
project={selectedProject}
|
||||
/>
|
||||
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.are_you_sure()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{m.delete_project_warning({ name: projectToDelete?.name ?? '' })}
|
||||
<div className="mt-4 flex flex-col gap-2 text-foreground">
|
||||
<span className="text-sm font-medium">{m.type_delete_to_confirm()}</span>
|
||||
<Input
|
||||
value={deleteConfirmText}
|
||||
onChange={(e) => setDeleteConfirmText(e.target.value)}
|
||||
placeholder={m.delete_placeholder()}
|
||||
className="h-9"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteProjectMutation.isPending}>
|
||||
{m.cancel()}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
handleConfirmDelete()
|
||||
}}
|
||||
disabled={deleteConfirmText !== 'delete' || deleteProjectMutation.isPending}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteProjectMutation.isPending ? m.deleting() : m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<MembersDialog
|
||||
open={isMembersDialogOpen}
|
||||
onOpenChange={setIsMembersDialogOpen}
|
||||
title={m.team_members()}
|
||||
type="team"
|
||||
members={safeMembers}
|
||||
isOwner={me?.role === 'owner'}
|
||||
onInvite={handleInvite}
|
||||
onUpdateRole={async (memberId, role) => {
|
||||
await updateMemberRoleMutation.mutateAsync({ userId: memberId, role })
|
||||
}}
|
||||
onRemoveMember={async (memberId) => {
|
||||
await removeMemberMutation.mutateAsync(memberId)
|
||||
}}
|
||||
currentUserId={me?.id}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/teams/$teamId/')({
|
||||
component: TeamPage,
|
||||
})
|
||||
export const Route = createFileRoute('/teams/$teamId/')({})
|
||||
|
||||
@@ -0,0 +1,632 @@
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { VideoTranscodeStrategy, UpdateTeamSettingsRequest } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { AgentsSettings } from '@/ui/components/settings/AgentsSettings'
|
||||
import { ProvidersSettings } from '@/ui/components/settings/ProvidersSettings'
|
||||
import { SandboxSettings } from '@/ui/components/settings/SandboxSettings'
|
||||
import { SkillsConfigCard } from '@/ui/components/settings/SkillsConfigCard'
|
||||
import { NotificationSettings } from '@/ui/components/settings/NotificationSettings'
|
||||
import { DeveloperSettings } from '@/ui/components/settings/DeveloperSettings'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Bot, Cpu, Film, Loader2, Puzzle, Shield, User, Bell, Key } from 'lucide-react'
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { AvatarCropDialog } from '@/ui/components/settings/AvatarCropDialog'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
|
||||
import { getLocale, setLocale } from '@/ui/paraglide/runtime.js'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
type SettingsTab =
|
||||
| 'general'
|
||||
| 'transcode'
|
||||
| 'skills'
|
||||
| 'providers'
|
||||
| 'agents'
|
||||
| 'sandbox'
|
||||
| 'notifications'
|
||||
| 'developer'
|
||||
|
||||
function TeamSettingsPage() {
|
||||
const { teamId } = Route.useParams()
|
||||
const queryClient = useQueryClient()
|
||||
const [activeTab, setActiveTab] = useState<SettingsTab>('general')
|
||||
const [profileName, setProfileName] = useState('')
|
||||
const [isCropOpen, setIsCropOpen] = useState(false)
|
||||
const [cropImageSrc, setCropImageSrc] = useState<string | null>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isUpdatingProfile, setIsUpdatingProfile] = useState(false)
|
||||
|
||||
const { setMetadata, getMetadata } = useUserMetadataStore()
|
||||
const currentLocale = getMetadata<string>('locale') || getLocale()
|
||||
|
||||
const handleLanguageChange = async (newLocale: string) => {
|
||||
if (newLocale === 'en' || newLocale === 'zh') {
|
||||
try {
|
||||
await setMetadata(teamId, 'locale', newLocale)
|
||||
setLocale(newLocale)
|
||||
toast.success(m.language_updated())
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.error(m.failed_update_language())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
data: settings,
|
||||
isLoading: isSettingsLoading,
|
||||
error: settingsError,
|
||||
} = useQuery({
|
||||
queryKey: ['teams', teamId, 'settings'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].settings.$get({
|
||||
param: { teamId: teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch settings')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: me, isLoading: isMeLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId: teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch me')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (me?.name) {
|
||||
setProfileName(me.name)
|
||||
}
|
||||
}, [me])
|
||||
|
||||
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 handleAvatarFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => {
|
||||
setCropImageSrc(reader.result as string)
|
||||
setIsCropOpen(true)
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
e.target.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleConfirmCrop = async (blob: Blob) => {
|
||||
setIsUpdatingProfile(true)
|
||||
try {
|
||||
const fileToUpload = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })
|
||||
const uploadRes = await client.api.teams[':teamId'].files.$post({
|
||||
param: { teamId },
|
||||
form: { file: fileToUpload },
|
||||
})
|
||||
if (!uploadRes.ok) throw new Error('Failed to upload avatar')
|
||||
const uploadData = await uploadRes.json()
|
||||
const key = (uploadData as { key: string }).key
|
||||
|
||||
const patchRes = await client.api.teams[':teamId'].me.$patch({
|
||||
param: { teamId },
|
||||
json: { imageKey: key },
|
||||
})
|
||||
if (!patchRes.ok) throw new Error('Failed to save profile')
|
||||
|
||||
toast.success(m.avatar_updated())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
|
||||
setIsCropOpen(false)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
toast.error(m.failed_update_avatar())
|
||||
} finally {
|
||||
setIsUpdatingProfile(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveAvatar = async () => {
|
||||
setIsUpdatingProfile(true)
|
||||
try {
|
||||
const patchRes = await client.api.teams[':teamId'].me.$patch({
|
||||
param: { teamId },
|
||||
json: { imageKey: null },
|
||||
})
|
||||
if (!patchRes.ok) throw new Error('Failed to remove avatar')
|
||||
|
||||
toast.success(m.avatar_removed())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
toast.error(m.failed_remove_avatar())
|
||||
} finally {
|
||||
setIsUpdatingProfile(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdateProfile = async () => {
|
||||
if (!profileName.trim()) return
|
||||
setIsUpdatingProfile(true)
|
||||
try {
|
||||
const patchRes = await client.api.teams[':teamId'].me.$patch({
|
||||
param: { teamId },
|
||||
json: { name: profileName.trim() },
|
||||
})
|
||||
if (!patchRes.ok) throw new Error('Failed to update name')
|
||||
|
||||
toast.success(m.profile_updated())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
toast.error(m.failed_update_profile())
|
||||
} finally {
|
||||
setIsUpdatingProfile(false)
|
||||
}
|
||||
}
|
||||
|
||||
const { mutate: updateSettings } = useMutation({
|
||||
mutationFn: async (data: { teamId: string; data: UpdateTeamSettingsRequest }) => {
|
||||
const res = await client.api.teams[':teamId'].settings.$patch({
|
||||
param: { teamId: data.teamId },
|
||||
json: data.data,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update settings')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'settings'],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const handleVideoStrategyChange = (value: VideoTranscodeStrategy) => {
|
||||
updateSettings({
|
||||
teamId,
|
||||
data: {
|
||||
key: 'transcode.videoStrategy',
|
||||
value: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (isSettingsLoading || isMeLoading) {
|
||||
return (
|
||||
<div className="flex h-screen items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (settingsError) {
|
||||
return <div className="p-8 text-center text-red-500">{m.failed_load_settings()}</div>
|
||||
}
|
||||
|
||||
let currentVideoStrategy =
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(settings as any)?.transcode?.videoStrategy || VideoTranscodeStrategy.best_match
|
||||
if (currentVideoStrategy === 'single' || currentVideoStrategy === 'disable') {
|
||||
currentVideoStrategy = VideoTranscodeStrategy.best_match
|
||||
} else if (currentVideoStrategy === 'full') {
|
||||
currentVideoStrategy = VideoTranscodeStrategy.all
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full bg-background font-sans selection:bg-primary/20 transition-colors duration-300">
|
||||
<div className="flex flex-col md:flex-row h-full">
|
||||
{/* Sidebar */}
|
||||
<div className="w-full h-full md:w-72 bg-sidebar border-b md:border-b-0 md:border-r border-sidebar-border z-10 md:left-16 overflow-y-auto transition-colors duration-300">
|
||||
<nav className="p-4 space-y-1 mt-4">
|
||||
<div className="mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider">
|
||||
{m.settings()}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('general')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'general'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<User className="w-5 h-5" />
|
||||
{m.general()}
|
||||
{activeTab === 'general' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{me?.role === 'owner' && (
|
||||
<button
|
||||
onClick={() => setActiveTab('transcode')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'transcode'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Film className="w-5 h-5" />
|
||||
{m.media_processing()}
|
||||
{activeTab === 'transcode' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('notifications')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'notifications'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Bell className="w-5 h-5" />
|
||||
{m.notifications()}
|
||||
{activeTab === 'notifications' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('developer')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'developer'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Key className="w-5 h-5" />
|
||||
{m.api_tokens()}
|
||||
{activeTab === 'developer' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{me?.role === 'owner' && (
|
||||
<>
|
||||
<div className="mt-6 mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider pt-4 border-t border-sidebar-border">
|
||||
{m.ai()}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('providers')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'providers'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Cpu className="w-5 h-5" />
|
||||
{m.providers()}
|
||||
{activeTab === 'providers' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('skills')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'skills'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Puzzle className="w-5 h-5" />
|
||||
{m.skills()}
|
||||
{activeTab === 'skills' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('agents')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'agents'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Bot className="w-5 h-5" />
|
||||
{m.agents()}
|
||||
{activeTab === 'agents' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('sandbox')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'sandbox'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Shield className="w-5 h-5" />
|
||||
{m.agent_sandbox()}
|
||||
{activeTab === 'sandbox' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Main Content Area */}
|
||||
<main className="flex-1 bg-background/50 h-full flex flex-col transition-colors duration-300 overflow-y-hidden">
|
||||
<div className="flex-1 flex flex-col max-w-4xl w-full mx-auto p-6 md:p-10 overflow-hidden">
|
||||
<div className="flex-none flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-foreground">
|
||||
{activeTab === 'general' && m.general_settings()}
|
||||
{activeTab === 'transcode' && m.media_processing()}
|
||||
{activeTab === 'skills' && m.skills_management()}
|
||||
{activeTab === 'providers' && m.ai_providers()}
|
||||
{activeTab === 'agents' && m.ai_agents()}
|
||||
{activeTab === 'sandbox' && m.agent_sandbox_settings()}
|
||||
{activeTab === 'notifications' && m.notification_settings()}
|
||||
{activeTab === 'developer' && m.developer_settings()}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{activeTab === 'general' && m.general_settings_description()}
|
||||
{activeTab === 'transcode' && m.transcode_description()}
|
||||
{activeTab === 'skills' && m.skills_description()}
|
||||
{activeTab === 'providers' && m.providers_description()}
|
||||
{activeTab === 'agents' && m.agents_description()}
|
||||
{activeTab === 'sandbox' && m.sandbox_description()}
|
||||
{activeTab === 'notifications' && m.notifications_description()}
|
||||
{activeTab === 'developer' && m.developer_description()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
{activeTab === 'general' && (
|
||||
<div className="h-full overflow-y-auto space-y-6 pr-1">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{m.personal_info()}</CardTitle>
|
||||
<CardDescription>{m.personal_info_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="flex flex-col md:flex-row gap-8 items-start">
|
||||
{/* Avatar Column */}
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{m.avatar()}
|
||||
</span>
|
||||
<div
|
||||
className="group relative cursor-pointer overflow-hidden rounded-full w-24 h-24 border border-border/60 shadow-md transition-all hover:opacity-90"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Avatar className="w-24 h-24">
|
||||
{me?.image && (
|
||||
<AvatarImage
|
||||
src={me.image}
|
||||
alt={me.name}
|
||||
className="object-cover w-24 h-24"
|
||||
/>
|
||||
)}
|
||||
<AvatarFallback className="text-2xl bg-primary/40 text-foreground">
|
||||
{getInitials(me?.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<span className="text-white text-xs font-semibold">{m.change()}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
{m.upload()}
|
||||
</Button>
|
||||
{me?.image && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-red-500 hover:text-red-600"
|
||||
onClick={handleRemoveAvatar}
|
||||
>
|
||||
{m.remove()}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
accept="image/*"
|
||||
onChange={handleAvatarFileChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Details Column */}
|
||||
<div className="flex-1 space-y-4 w-full">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-muted-foreground">
|
||||
{m.name()}
|
||||
</label>
|
||||
<Input
|
||||
value={profileName}
|
||||
onChange={(e) => setProfileName(e.target.value)}
|
||||
placeholder={m.enter_your_name()}
|
||||
className="max-w-md"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-muted-foreground">
|
||||
{m.email()}
|
||||
</label>
|
||||
<Input
|
||||
value={me?.email || ''}
|
||||
disabled
|
||||
className="max-w-md bg-muted/50 cursor-not-allowed"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{m.email_managed_by_auth()}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleUpdateProfile}
|
||||
disabled={isUpdatingProfile || !profileName.trim()}
|
||||
className="mt-2"
|
||||
>
|
||||
{isUpdatingProfile && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
|
||||
{m.save_changes()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border border-slate-200 dark:border-slate-800 mt-6">
|
||||
<CardHeader>
|
||||
<CardTitle>{m.language_settings()}</CardTitle>
|
||||
<CardDescription>{m.select_preferred_language()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="max-w-xs">
|
||||
<Select value={currentLocale} onValueChange={handleLanguageChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={m.select_language()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="en">{m.english()}</SelectItem>
|
||||
<SelectItem value="zh">{m.chinese()}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<AvatarCropDialog
|
||||
isOpen={isCropOpen}
|
||||
onClose={() => setIsCropOpen(false)}
|
||||
imageSrc={cropImageSrc}
|
||||
onConfirm={handleConfirmCrop}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'transcode' && (
|
||||
<div className="h-full overflow-y-auto pr-1">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{m.transcode_settings()}</CardTitle>
|
||||
<CardDescription>
|
||||
<span className="block mb-2">{m.transcode_description()}</span>
|
||||
<span className="block">{m.transcode_strategy_note()}</span>
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Video Strategy */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-lg font-medium">{m.video_strategy()}</h3>
|
||||
<div className="space-y-3">
|
||||
<div
|
||||
className={cn(
|
||||
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
|
||||
currentVideoStrategy === VideoTranscodeStrategy.best_match
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border',
|
||||
)}
|
||||
onClick={() =>
|
||||
handleVideoStrategyChange(VideoTranscodeStrategy.best_match)
|
||||
}
|
||||
>
|
||||
<div className="font-semibold">{m.best_match()}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{m.best_match_description()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
|
||||
currentVideoStrategy === VideoTranscodeStrategy.all
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border',
|
||||
)}
|
||||
onClick={() => handleVideoStrategyChange(VideoTranscodeStrategy.all)}
|
||||
>
|
||||
<div className="font-semibold">{m.all_resolutions()}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{m.all_resolutions_description()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'skills' && (
|
||||
<div className="h-full overflow-y-auto pr-1">
|
||||
<SkillsConfigCard teamId={teamId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'providers' && <ProvidersSettings teamId={teamId} />}
|
||||
|
||||
{activeTab === 'agents' && (
|
||||
<div className="h-full overflow-y-auto pr-1">
|
||||
<AgentsSettings teamId={teamId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'sandbox' && (
|
||||
<div className="h-full overflow-y-auto pr-1">
|
||||
<SandboxSettings teamId={teamId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'notifications' && <NotificationSettings teamId={teamId} />}
|
||||
|
||||
{activeTab === 'developer' && <DeveloperSettings teamId={teamId} />}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/teams/$teamId/settings')({
|
||||
component: TeamSettingsPage,
|
||||
})
|
||||
@@ -1,632 +1,3 @@
|
||||
import { VideoTranscodeStrategy, UpdateTeamSettingsRequest } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { AgentsSettings } from '@/ui/components/settings/AgentsSettings'
|
||||
import { ProvidersSettings } from '@/ui/components/settings/ProvidersSettings'
|
||||
import { SandboxSettings } from '@/ui/components/settings/SandboxSettings'
|
||||
import { SkillsConfigCard } from '@/ui/components/settings/SkillsConfigCard'
|
||||
import { NotificationSettings } from '@/ui/components/settings/NotificationSettings'
|
||||
import { DeveloperSettings } from '@/ui/components/settings/DeveloperSettings'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { Bot, Cpu, Film, Loader2, Puzzle, Shield, User, Bell, Key } from 'lucide-react'
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { AvatarCropDialog } from '@/ui/components/settings/AvatarCropDialog'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
|
||||
import { getLocale, setLocale } from '@/ui/paraglide/runtime.js'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
type SettingsTab =
|
||||
| 'general'
|
||||
| 'transcode'
|
||||
| 'skills'
|
||||
| 'providers'
|
||||
| 'agents'
|
||||
| 'sandbox'
|
||||
| 'notifications'
|
||||
| 'developer'
|
||||
|
||||
function TeamSettingsPage() {
|
||||
const { teamId } = Route.useParams()
|
||||
const queryClient = useQueryClient()
|
||||
const [activeTab, setActiveTab] = useState<SettingsTab>('general')
|
||||
const [profileName, setProfileName] = useState('')
|
||||
const [isCropOpen, setIsCropOpen] = useState(false)
|
||||
const [cropImageSrc, setCropImageSrc] = useState<string | null>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isUpdatingProfile, setIsUpdatingProfile] = useState(false)
|
||||
|
||||
const { setMetadata, getMetadata } = useUserMetadataStore()
|
||||
const currentLocale = getMetadata<string>('locale') || getLocale()
|
||||
|
||||
const handleLanguageChange = async (newLocale: string) => {
|
||||
if (newLocale === 'en' || newLocale === 'zh') {
|
||||
try {
|
||||
await setMetadata(teamId, 'locale', newLocale)
|
||||
setLocale(newLocale)
|
||||
toast.success(m.language_updated())
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.error(m.failed_update_language())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
data: settings,
|
||||
isLoading: isSettingsLoading,
|
||||
error: settingsError,
|
||||
} = useQuery({
|
||||
queryKey: ['teams', teamId, 'settings'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].settings.$get({
|
||||
param: { teamId: teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch settings')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: me, isLoading: isMeLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId: teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch me')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (me?.name) {
|
||||
setProfileName(me.name)
|
||||
}
|
||||
}, [me])
|
||||
|
||||
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 handleAvatarFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => {
|
||||
setCropImageSrc(reader.result as string)
|
||||
setIsCropOpen(true)
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
e.target.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleConfirmCrop = async (blob: Blob) => {
|
||||
setIsUpdatingProfile(true)
|
||||
try {
|
||||
const fileToUpload = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })
|
||||
const uploadRes = await client.api.teams[':teamId'].files.$post({
|
||||
param: { teamId },
|
||||
form: { file: fileToUpload },
|
||||
})
|
||||
if (!uploadRes.ok) throw new Error('Failed to upload avatar')
|
||||
const uploadData = await uploadRes.json()
|
||||
const key = (uploadData as { key: string }).key
|
||||
|
||||
const patchRes = await client.api.teams[':teamId'].me.$patch({
|
||||
param: { teamId },
|
||||
json: { imageKey: key },
|
||||
})
|
||||
if (!patchRes.ok) throw new Error('Failed to save profile')
|
||||
|
||||
toast.success(m.avatar_updated())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
|
||||
setIsCropOpen(false)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
toast.error(m.failed_update_avatar())
|
||||
} finally {
|
||||
setIsUpdatingProfile(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveAvatar = async () => {
|
||||
setIsUpdatingProfile(true)
|
||||
try {
|
||||
const patchRes = await client.api.teams[':teamId'].me.$patch({
|
||||
param: { teamId },
|
||||
json: { imageKey: null },
|
||||
})
|
||||
if (!patchRes.ok) throw new Error('Failed to remove avatar')
|
||||
|
||||
toast.success(m.avatar_removed())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
toast.error(m.failed_remove_avatar())
|
||||
} finally {
|
||||
setIsUpdatingProfile(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdateProfile = async () => {
|
||||
if (!profileName.trim()) return
|
||||
setIsUpdatingProfile(true)
|
||||
try {
|
||||
const patchRes = await client.api.teams[':teamId'].me.$patch({
|
||||
param: { teamId },
|
||||
json: { name: profileName.trim() },
|
||||
})
|
||||
if (!patchRes.ok) throw new Error('Failed to update name')
|
||||
|
||||
toast.success(m.profile_updated())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
toast.error(m.failed_update_profile())
|
||||
} finally {
|
||||
setIsUpdatingProfile(false)
|
||||
}
|
||||
}
|
||||
|
||||
const { mutate: updateSettings } = useMutation({
|
||||
mutationFn: async (data: { teamId: string; data: UpdateTeamSettingsRequest }) => {
|
||||
const res = await client.api.teams[':teamId'].settings.$patch({
|
||||
param: { teamId: data.teamId },
|
||||
json: data.data,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update settings')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'settings'],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const handleVideoStrategyChange = (value: VideoTranscodeStrategy) => {
|
||||
updateSettings({
|
||||
teamId,
|
||||
data: {
|
||||
key: 'transcode.videoStrategy',
|
||||
value: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (isSettingsLoading || isMeLoading) {
|
||||
return (
|
||||
<div className="flex h-screen items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (settingsError) {
|
||||
return <div className="p-8 text-center text-red-500">{m.failed_load_settings()}</div>
|
||||
}
|
||||
|
||||
let currentVideoStrategy =
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(settings as any)?.transcode?.videoStrategy || VideoTranscodeStrategy.best_match
|
||||
if (currentVideoStrategy === 'single' || currentVideoStrategy === 'disable') {
|
||||
currentVideoStrategy = VideoTranscodeStrategy.best_match
|
||||
} else if (currentVideoStrategy === 'full') {
|
||||
currentVideoStrategy = VideoTranscodeStrategy.all
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full bg-background font-sans selection:bg-primary/20 transition-colors duration-300">
|
||||
<div className="flex flex-col md:flex-row h-full">
|
||||
{/* Sidebar */}
|
||||
<div className="w-full h-full md:w-72 bg-sidebar border-b md:border-b-0 md:border-r border-sidebar-border z-10 md:left-16 overflow-y-auto transition-colors duration-300">
|
||||
<nav className="p-4 space-y-1 mt-4">
|
||||
<div className="mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider">
|
||||
{m.settings()}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('general')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'general'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<User className="w-5 h-5" />
|
||||
{m.general()}
|
||||
{activeTab === 'general' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{me?.role === 'owner' && (
|
||||
<button
|
||||
onClick={() => setActiveTab('transcode')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'transcode'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Film className="w-5 h-5" />
|
||||
{m.media_processing()}
|
||||
{activeTab === 'transcode' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('notifications')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'notifications'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Bell className="w-5 h-5" />
|
||||
{m.notifications()}
|
||||
{activeTab === 'notifications' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('developer')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'developer'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Key className="w-5 h-5" />
|
||||
{m.api_tokens()}
|
||||
{activeTab === 'developer' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{me?.role === 'owner' && (
|
||||
<>
|
||||
<div className="mt-6 mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider pt-4 border-t border-sidebar-border">
|
||||
{m.ai()}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('providers')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'providers'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Cpu className="w-5 h-5" />
|
||||
{m.providers()}
|
||||
{activeTab === 'providers' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('skills')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'skills'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Puzzle className="w-5 h-5" />
|
||||
{m.skills()}
|
||||
{activeTab === 'skills' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('agents')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'agents'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Bot className="w-5 h-5" />
|
||||
{m.agents()}
|
||||
{activeTab === 'agents' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('sandbox')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'sandbox'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Shield className="w-5 h-5" />
|
||||
{m.agent_sandbox()}
|
||||
{activeTab === 'sandbox' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Main Content Area */}
|
||||
<main className="flex-1 bg-background/50 h-full flex flex-col transition-colors duration-300 overflow-y-hidden">
|
||||
<div className="flex-1 flex flex-col max-w-4xl w-full mx-auto p-6 md:p-10 overflow-hidden">
|
||||
<div className="flex-none flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-foreground">
|
||||
{activeTab === 'general' && m.general_settings()}
|
||||
{activeTab === 'transcode' && m.media_processing()}
|
||||
{activeTab === 'skills' && m.skills_management()}
|
||||
{activeTab === 'providers' && m.ai_providers()}
|
||||
{activeTab === 'agents' && m.ai_agents()}
|
||||
{activeTab === 'sandbox' && m.agent_sandbox_settings()}
|
||||
{activeTab === 'notifications' && m.notification_settings()}
|
||||
{activeTab === 'developer' && m.developer_settings()}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{activeTab === 'general' && m.general_settings_description()}
|
||||
{activeTab === 'transcode' && m.transcode_description()}
|
||||
{activeTab === 'skills' && m.skills_description()}
|
||||
{activeTab === 'providers' && m.providers_description()}
|
||||
{activeTab === 'agents' && m.agents_description()}
|
||||
{activeTab === 'sandbox' && m.sandbox_description()}
|
||||
{activeTab === 'notifications' && m.notifications_description()}
|
||||
{activeTab === 'developer' && m.developer_description()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
{activeTab === 'general' && (
|
||||
<div className="h-full overflow-y-auto space-y-6 pr-1">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{m.personal_info()}</CardTitle>
|
||||
<CardDescription>{m.personal_info_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="flex flex-col md:flex-row gap-8 items-start">
|
||||
{/* Avatar Column */}
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{m.avatar()}
|
||||
</span>
|
||||
<div
|
||||
className="group relative cursor-pointer overflow-hidden rounded-full w-24 h-24 border border-border/60 shadow-md transition-all hover:opacity-90"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Avatar className="w-24 h-24">
|
||||
{me?.image && (
|
||||
<AvatarImage
|
||||
src={me.image}
|
||||
alt={me.name}
|
||||
className="object-cover w-24 h-24"
|
||||
/>
|
||||
)}
|
||||
<AvatarFallback className="text-2xl bg-primary/40 text-foreground">
|
||||
{getInitials(me?.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<span className="text-white text-xs font-semibold">{m.change()}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
{m.upload()}
|
||||
</Button>
|
||||
{me?.image && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-red-500 hover:text-red-600"
|
||||
onClick={handleRemoveAvatar}
|
||||
>
|
||||
{m.remove()}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
accept="image/*"
|
||||
onChange={handleAvatarFileChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Details Column */}
|
||||
<div className="flex-1 space-y-4 w-full">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-muted-foreground">
|
||||
{m.name()}
|
||||
</label>
|
||||
<Input
|
||||
value={profileName}
|
||||
onChange={(e) => setProfileName(e.target.value)}
|
||||
placeholder={m.enter_your_name()}
|
||||
className="max-w-md"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-muted-foreground">
|
||||
{m.email()}
|
||||
</label>
|
||||
<Input
|
||||
value={me?.email || ''}
|
||||
disabled
|
||||
className="max-w-md bg-muted/50 cursor-not-allowed"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{m.email_managed_by_auth()}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleUpdateProfile}
|
||||
disabled={isUpdatingProfile || !profileName.trim()}
|
||||
className="mt-2"
|
||||
>
|
||||
{isUpdatingProfile && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
|
||||
{m.save_changes()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border border-slate-200 dark:border-slate-800 mt-6">
|
||||
<CardHeader>
|
||||
<CardTitle>{m.language_settings()}</CardTitle>
|
||||
<CardDescription>{m.select_preferred_language()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="max-w-xs">
|
||||
<Select value={currentLocale} onValueChange={handleLanguageChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={m.select_language()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="en">{m.english()}</SelectItem>
|
||||
<SelectItem value="zh">{m.chinese()}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<AvatarCropDialog
|
||||
isOpen={isCropOpen}
|
||||
onClose={() => setIsCropOpen(false)}
|
||||
imageSrc={cropImageSrc}
|
||||
onConfirm={handleConfirmCrop}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'transcode' && (
|
||||
<div className="h-full overflow-y-auto pr-1">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{m.transcode_settings()}</CardTitle>
|
||||
<CardDescription>
|
||||
<span className="block mb-2">{m.transcode_description()}</span>
|
||||
<span className="block">{m.transcode_strategy_note()}</span>
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Video Strategy */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-lg font-medium">{m.video_strategy()}</h3>
|
||||
<div className="space-y-3">
|
||||
<div
|
||||
className={cn(
|
||||
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
|
||||
currentVideoStrategy === VideoTranscodeStrategy.best_match
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border',
|
||||
)}
|
||||
onClick={() =>
|
||||
handleVideoStrategyChange(VideoTranscodeStrategy.best_match)
|
||||
}
|
||||
>
|
||||
<div className="font-semibold">{m.best_match()}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{m.best_match_description()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
|
||||
currentVideoStrategy === VideoTranscodeStrategy.all
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border',
|
||||
)}
|
||||
onClick={() => handleVideoStrategyChange(VideoTranscodeStrategy.all)}
|
||||
>
|
||||
<div className="font-semibold">{m.all_resolutions()}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{m.all_resolutions_description()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'skills' && (
|
||||
<div className="h-full overflow-y-auto pr-1">
|
||||
<SkillsConfigCard teamId={teamId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'providers' && <ProvidersSettings teamId={teamId} />}
|
||||
|
||||
{activeTab === 'agents' && (
|
||||
<div className="h-full overflow-y-auto pr-1">
|
||||
<AgentsSettings teamId={teamId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'sandbox' && (
|
||||
<div className="h-full overflow-y-auto pr-1">
|
||||
<SandboxSettings teamId={teamId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'notifications' && <NotificationSettings teamId={teamId} />}
|
||||
|
||||
{activeTab === 'developer' && <DeveloperSettings teamId={teamId} />}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/teams/$teamId/settings')({
|
||||
component: TeamSettingsPage,
|
||||
})
|
||||
export const Route = createFileRoute('/teams/$teamId/settings')({})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"routesDirectory": "routes",
|
||||
"generatedRouteTree": "routeTree.gen.ts"
|
||||
"generatedRouteTree": "routeTree.gen.ts",
|
||||
"autoCodeSplitting": true
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const APP_VERSION = '0.1.7'
|
||||
export const APP_VERSION = '0.1.8'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -237,13 +237,13 @@ async function buildMainPackage({
|
||||
target: 'bun',
|
||||
outdir: binOutDir,
|
||||
minify: true,
|
||||
splitting: true,
|
||||
naming: `${appName}-app.[ext]`,
|
||||
plugins,
|
||||
external,
|
||||
define: {
|
||||
'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
},
|
||||
publicPath: '/',
|
||||
})
|
||||
|
||||
if (!buildResult.success) {
|
||||
|
||||
Reference in New Issue
Block a user