feat(agentic kanban): phase 1 not-agentic kanban board (#330)

* feat(kanban): implement AI-native kanban database models, services, and REST APIs

* feat(webui): implement team kanban board and task management

* style(webui): increase kanban dialog widths and form container

* fix(webui): ensure kanban dialogs override sm:max-w-lg base class

* style(webui): set edit task dialog max width to 5xl

* chore: untrack kanban plan markdown files

* feat(webui): update kanban page layout to 2 columns and refine task activity UI

* fix(webui): constrain kanban column and board heights for vertical scrolling

* feat(kanban): unify task status transition into updateTask API and allow unconstrained human task transitions

* fix(webui): add optimistic updates to kanban drag-and-drop to eliminate flash

* refactor(webui): remove client-side search box from kanban header

* feat(kanban): redesign task dialog comments area and add attachment support

* refactor(webui): remove top status action bar from task info dialog

* fix(webui): narrow query cache predicate and add defensive guards for kanban drag optimistic update

* feat(kanban): add drag-and-drop task reordering with fractional indexing (#331)

* feat(kanban): add drag-and-drop task reordering with fractional indexing

* fix(kanban): improve card drop zones, snap indicators, and column highlight

* fix(kanban): enable card droppables only during active drag

* fix(kanban): refine hover styles and drop indicators for column boundaries

* fix(kanban): unify bottom drop indicator and fix top indicator clipping

* fix(kanban): ensure full column highlight and full coverage drop target

* minor change

* feat(kanban): allow agent tasks free drag-and-drop and enforce status change permissions (#332)

* refactor(kanban): rename task_type_agentic translation keys to task_type_agent

* feat(kanban): refactor task type enum to isAgentTask boolean (#333)

* refactor(kanban): remove phase 2 agent execution logic and streamline phase 1 kanban

* feat(kanban): add notifications and audit logging for kanban (#334)

* feat(kanban): redesign config area layout and add parent tasks multi-selector (#335)

* feat(webui): redesign kanban task dialog config area

* feat(kanban): simplify task dependencies with parent tasks multi-selector

* refactor(kanban): remove unused links routes and legacy dependency methods

* feat(kanban): connect assets and kanban tasks with many-to-many relationship (#336)

* feat(kanban): connect assets and kanban tasks with many-to-many relationship

* feat(kanban): improve asset picker layout, infinite scrolling, and breadcrumb icon styling

* fix(kanban): ensure asset picker scrollarea is scrollable with min-h-0 and shrink-0 flex styling

* fix(kanban): hide recently deleted in folder tree picker and adjust header padding

* fix(kanban): use lucide files icon instead of paperclip for linked assets

* feat(kanban): improve task deletion, goal sidebar interaction, and card styling (#337)

* feat(kanban): improve task deletion, goal sidebar interaction, and card styling

* feat(kanban): move agent task badge after priority and update to orange style

* feat(kanban): add status Compare-And-Swap (CAS) to prevent drag-and-drop race conditions (#338)

* feat(kanban): add status Compare-And-Swap (CAS) to prevent drag-and-drop race conditions

* style(kanban): rotate kanban icon 180 degrees in sidebar and top nav

* style(kanban): remove rotate-180 from SquareKanban icons

* feat(kanban): add unassigned goal record and fix all tasks count (#339)

* feat(kanban): add unassigned goal record and fix all tasks count

* feat(kanban): toggle task count with three-dot action button on goal card hover

* fix(ci): pin bun version to 1.3.14 across CI and Docker (#340)

* fix(webui): truncate goal name to max 2 lines in kanban sidebar (#341)
This commit is contained in:
Yiling-J
2026-08-23 10:28:56 +08:00
committed by GitHub
parent 4c0fd29b7f
commit 1f2bdc8c9e
363 changed files with 34036 additions and 44 deletions
@@ -0,0 +1,100 @@
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
import { m } from '@/ui/paraglide/messages.js'
import { Loader2, Bot } from 'lucide-react'
import type { KanbanTaskDetail } from '@shumai/dtos'
import { cn } from '@/ui/lib/utils'
import { getStatusBadgeColor, getStatusLabel } from '../kanban-types'
import { TaskInfoForm } from './task-info-form'
import { TaskActivityPane } from './task-activity-pane'
interface EditTaskDialogProps {
teamId: string
taskId: string | null
isOpen: boolean
onClose: () => void
canEdit?: boolean
}
export function EditTaskDialog({
teamId,
taskId,
isOpen,
onClose,
canEdit = true,
}: EditTaskDialogProps) {
const {
data: task,
isLoading,
error,
} = useQuery({
queryKey: ['teams', teamId, 'kanban', 'task', taskId],
queryFn: async () => {
if (!taskId) return null
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].$get({
param: { teamId, taskId },
})
if (!res.ok) throw new Error('Failed to fetch task details')
return (await res.json()) as KanbanTaskDetail
},
enabled: !!teamId && !!taskId && isOpen,
})
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-5xl w-[95vw] h-[88vh] p-0 gap-0 flex flex-col overflow-hidden bg-background">
<DialogHeader className="px-5 py-3 border-b border-border/70 flex flex-row items-center justify-between space-y-0 shrink-0 bg-card/80">
<div className="flex items-center gap-2 min-w-0 pr-4">
{task?.isAgentTask && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-semibold bg-orange-500/15 text-orange-600 dark:text-orange-400 border border-orange-500/30 shrink-0">
<Bot className="w-3.5 h-3.5" />
<span>{m.task_type_agent()}</span>
</span>
)}
{task?.status && (
<span
className={cn(
'px-2 py-0.5 rounded text-[11px] font-medium border uppercase shrink-0',
getStatusBadgeColor(task.status),
)}
>
{getStatusLabel(task.status)}
</span>
)}
<DialogTitle className="text-sm font-semibold truncate text-foreground">
{task?.title || m.edit_task()}
</DialogTitle>
</div>
</DialogHeader>
{/* 2-Columns Body: Left 2/3, Right 1/3 */}
<div className="flex-1 flex flex-col md:flex-row overflow-hidden">
{isLoading ? (
<div className="flex-1 flex items-center justify-center p-12">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
) : error || !task ? (
<div className="flex-1 flex items-center justify-center p-12 text-xs text-muted-foreground">
{m.file_not_found()}
</div>
) : (
<>
{/* Left Column (2/3 width) */}
<div className="flex-1 md:w-2/3 h-full overflow-hidden flex flex-col">
<TaskInfoForm teamId={teamId} task={task} canEdit={canEdit} />
</div>
{/* Right Column (1/3 width) */}
<div className="md:w-1/3 h-full overflow-hidden flex flex-col">
<TaskActivityPane teamId={teamId} task={task} />
</div>
</>
)}
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,53 @@
import { useState } from 'react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
import { m } from '@/ui/paraglide/messages.js'
import { TaskCommentThread } from './task-comment-thread'
import { TaskEventTimeline } from './task-event-timeline'
import type { KanbanTaskDetail } from '@shumai/dtos'
interface TaskActivityPaneProps {
teamId: string
task: KanbanTaskDetail
}
export function TaskActivityPane({ teamId, task }: TaskActivityPaneProps) {
const [activeTab, setActiveTab] = useState<'comments' | 'activity'>('comments')
return (
<div className="flex flex-col h-full bg-sidebar/30 border-l border-border/60 overflow-hidden">
<Tabs
value={activeTab}
onValueChange={(val) => setActiveTab(val as 'comments' | 'activity')}
className="flex flex-col h-full"
>
<div className="px-3 pt-2.5 pb-1 border-b border-border/60 bg-card/50 shrink-0">
<TabsList className="w-full grid grid-cols-2 h-8 bg-muted/60">
<TabsTrigger value="comments" className="text-xs h-7">
<span>{m.comments()}</span>
{task.comments.length > 0 && (
<span className="text-[10px] font-mono text-muted-foreground ml-1">
({task.comments.length})
</span>
)}
</TabsTrigger>
<TabsTrigger value="activity" className="text-xs h-7">
<span>{m.activity()}</span>
</TabsTrigger>
</TabsList>
</div>
<div className="flex-1 overflow-hidden">
<TabsContent
value="comments"
className="h-full m-0 data-[state=active]:flex data-[state=active]:flex-col"
>
<TaskCommentThread teamId={teamId} taskId={task.id} initialComments={task.comments} />
</TabsContent>
<TabsContent value="activity" className="h-full m-0 data-[state=active]:block">
<TaskEventTimeline teamId={teamId} taskId={task.id} initialEvents={task.events} />
</TabsContent>
</div>
</Tabs>
</div>
)
}
@@ -0,0 +1,230 @@
import React, { useState } from 'react'
import { format } from 'date-fns'
import Markdown from 'react-markdown'
import { Download, FileText, MoreHorizontal, Trash2 } from 'lucide-react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { toast } from 'sonner'
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 {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { formatSize } from '@/ui/lib/format'
import type { KanbanAttachmentInfo, KanbanCommentInfo } from '@shumai/dtos'
interface TaskCommentCardProps {
teamId: string
taskId: string
comment: KanbanCommentInfo
currentUserId?: string
isOwnerOrAdmin?: boolean
onViewAttachment?: (attachment: KanbanAttachmentInfo) => void
}
export function TaskCommentCard({
teamId,
taskId,
comment,
currentUserId,
isOwnerOrAdmin,
onViewAttachment,
}: TaskCommentCardProps) {
const queryClient = useQueryClient()
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const canDelete = isOwnerOrAdmin || comment.author.id === currentUserId
const { mutate: deleteComment, isPending: isDeleting } = useMutation({
mutationFn: async () => {
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].comments[
':commentId'
].$delete({
param: { teamId, taskId, commentId: comment.id },
})
if (!res.ok) {
const err = await res.json().catch(() => ({ message: m.error() }))
throw new Error((err as { message?: string }).message || m.error())
}
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'kanban', 'tasks', taskId, 'comments'],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'kanban', 'task', taskId],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'kanban', 'tasks'],
})
toast.success('Comment deleted')
setIsDeleteDialogOpen(false)
},
onError: (err) => {
toast.error(err.message)
},
})
const authorInitials = (comment.author.name || 'U')
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
return (
<div className="relative flex gap-3 p-3 rounded-xl border border-transparent bg-foreground/[0.03] dark:bg-foreground/[0.08] hover:bg-foreground/[0.06] dark:hover:bg-foreground/[0.12] transition-colors group">
{/* Left Avatar */}
<Avatar className="w-7 h-7 shrink-0 mt-0.5 border border-border">
{comment.author.image && (
<AvatarImage src={comment.author.image} alt={comment.author.name} />
)}
<AvatarFallback className="text-[10px] font-medium bg-muted text-muted-foreground">
{authorInitials}
</AvatarFallback>
</Avatar>
{/* Main Content Area */}
<div className="flex-1 min-w-0 space-y-1.5">
{/* Header: Author + Timestamp + Actions */}
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<span className="font-semibold text-xs text-foreground truncate">
{comment.author.name}
</span>
<span className="text-[10px] text-muted-foreground shrink-0 font-mono">
{format(new Date(comment.createdAt), 'MMM d, h:mm a')}
</span>
</div>
{canDelete && (
<div className="opacity-0 group-hover:opacity-100 transition-opacity">
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button size="icon-xs" variant="ghost" className="h-5 w-5 text-muted-foreground">
<MoreHorizontal className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="text-destructive focus:text-destructive cursor-pointer text-xs"
onClick={() => setIsDeleteDialogOpen(true)}
>
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
<span>{m.delete()}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
{/* Markdown Comment Body */}
{comment.body && (
<div className="text-xs leading-relaxed prose prose-xs dark:prose-invert max-w-none break-words text-foreground/90 font-sans">
<Markdown>{comment.body}</Markdown>
</div>
)}
{/* Attachments Section */}
{comment.attachments && comment.attachments.length > 0 && (
<div className="flex flex-wrap gap-2 pt-1.5">
{comment.attachments.map((att) => {
const isImage = att.proxyType === 'image' || att.contentType?.startsWith('image/')
return (
<div
key={att.id}
className="relative group/att rounded-lg border border-border bg-card overflow-hidden transition-all duration-200"
>
{isImage ? (
<div
className="w-40 h-28 relative cursor-pointer overflow-hidden bg-muted/40"
onClick={() => onViewAttachment?.(att)}
>
<img
src={att.url}
alt={att.name}
className="w-full h-full object-cover group-hover/att:scale-105 transition-transform duration-200"
/>
<a
href={att.url}
download={att.name}
target="_blank"
rel="noreferrer"
className="absolute right-1.5 bottom-1.5 bg-black/60 hover:bg-black/80 text-white p-1 rounded-md opacity-0 group-hover/att:opacity-100 transition-opacity shadow-xs"
onClick={(e) => e.stopPropagation()}
title="Download"
>
<Download className="w-3.5 h-3.5" />
</a>
</div>
) : (
<div className="flex items-center gap-2.5 p-2.5 max-w-[240px] bg-card hover:bg-muted/40 transition-colors">
<FileText className="w-7 h-7 text-primary/80 shrink-0" />
<div className="min-w-0 flex-1">
<p
className="text-xs font-medium text-foreground truncate"
title={att.name}
>
{att.name}
</p>
<p className="text-[10px] text-muted-foreground font-mono">
{formatSize(att.sizeByte)}
</p>
</div>
<a
href={att.url}
download={att.name}
target="_blank"
rel="noreferrer"
className="p-1 text-muted-foreground hover:text-foreground shrink-0 rounded-md hover:bg-muted transition-colors"
title="Download"
>
<Download className="w-3.5 h-3.5" />
</a>
</div>
)}
</div>
)
})}
</div>
)}
</div>
{/* Delete Confirmation Alert Dialog */}
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{m.delete_comment_confirm()}</AlertDialogTitle>
<AlertDialogDescription>{m.delete_comment_description()}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>{m.cancel()}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-white"
disabled={isDeleting}
onClick={() => deleteComment()}
>
{m.delete()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
@@ -0,0 +1,370 @@
import React, { useState, useRef, useEffect } from 'react'
import { Paperclip, ArrowUp, X, Loader2, FileText, Image as ImageIcon } from 'lucide-react'
import { useMutation } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { toast } from 'sonner'
import { Button } from '@/ui/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { formatSize } from '@/ui/lib/format'
import { useMemberStore, type MemberInfo } from '@/ui/stores/members'
import type {
KanbanAttachmentPayload,
PostAttachmentRequest,
PostKanbanAttachmentResponse,
} from '@shumai/dtos'
interface UploadingFile {
id: string
file: File
isUploading: boolean
payload?: KanbanAttachmentPayload
error?: string
}
interface TaskCommentInputProps {
teamId: string
onSendMessage: (text: string, attachments?: KanbanAttachmentPayload[]) => Promise<void> | void
isSubmitting?: boolean
}
export function TaskCommentInput({ teamId, onSendMessage, isSubmitting }: TaskCommentInputProps) {
const [text, setText] = useState('')
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
const [showMentionList, setShowMentionList] = useState(false)
const [mentionQuery, setMentionQuery] = useState('')
const [highlightedIndex, setHighlightedIndex] = useState(0)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const mentionListRef = useRef<HTMLDivElement>(null)
const { members, fetchMembers } = useMemberStore()
useEffect(() => {
if (teamId) {
fetchMembers(teamId, true, true)
}
}, [teamId, fetchMembers])
const { mutateAsync: getUploadUrl } = useMutation({
mutationFn: async (data: PostAttachmentRequest) => {
const res = await client.api.teams[':teamId'].kanban.attachments.$post({
param: { teamId },
json: data,
})
if (!res.ok) throw new Error('Failed to get attachment upload url')
return (await res.json()) as PostKanbanAttachmentResponse
},
})
// Auto-resize textarea
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const val = e.target.value
setText(val)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 160)}px`
}
// Mention detection
const cursorPos = e.target.selectionStart || 0
const textBeforeCursor = val.slice(0, cursorPos)
const lastAtPos = textBeforeCursor.lastIndexOf('@')
if (lastAtPos !== -1) {
const isStartOfLine = lastAtPos === 0
const charBeforeAt = textBeforeCursor[lastAtPos - 1]
const hasSpaceBefore = isStartOfLine || /\s/.test(charBeforeAt)
if (hasSpaceBefore) {
const query = textBeforeCursor.slice(lastAtPos + 1)
if (!/\s/.test(query)) {
setMentionQuery(query)
setShowMentionList(true)
return
}
}
}
setShowMentionList(false)
}
const filteredMembers = members.filter((m) =>
m.name?.toLowerCase().includes(mentionQuery.toLowerCase()),
)
useEffect(() => {
setHighlightedIndex(0)
}, [mentionQuery, showMentionList])
const handleSelectMention = (member: MemberInfo) => {
if (!textareaRef.current) return
const cursorPos = textareaRef.current.selectionStart || 0
const textBeforeCursor = text.slice(0, cursorPos)
const textAfterCursor = text.slice(cursorPos)
const lastAtPos = textBeforeCursor.lastIndexOf('@')
if (lastAtPos !== -1) {
const newText = `${text.slice(0, lastAtPos)}@${member.name} ${textAfterCursor}`
setText(newText)
setShowMentionList(false)
setTimeout(() => {
if (textareaRef.current) {
textareaRef.current.focus()
const newCursorPos = lastAtPos + member.name.length + 2
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
}
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || [])
if (files.length === 0) return
const newUploading: UploadingFile[] = files.map((file) => ({
id: `${Date.now()}-${file.name}-${Math.random()}`,
file,
isUploading: true,
}))
setUploadingFiles((prev) => [...prev, ...newUploading])
for (const uf of newUploading) {
try {
const res = await getUploadUrl({
fileName: uf.file.name,
size: uf.file.size,
contentType: uf.file.type || 'application/octet-stream',
})
// Direct upload to S3
const uploadRes = await fetch(res.uploadUrl, {
method: 'PUT',
body: uf.file,
headers: {
'Content-Type': uf.file.type || 'application/octet-stream',
},
})
if (!uploadRes.ok) {
throw new Error('Failed to upload file to storage')
}
setUploadingFiles((prev) =>
prev.map((item) =>
item.id === uf.id
? {
...item,
isUploading: false,
payload: {
id: res.id,
name: res.name,
key: res.key,
sizeByte: res.sizeByte,
contentType: res.contentType,
proxyType: res.proxyType,
},
}
: item,
),
)
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Upload failed'
toast.error(`${uf.file.name}: ${message}`)
setUploadingFiles((prev) =>
prev.map((item) =>
item.id === uf.id ? { ...item, isUploading: false, error: message } : item,
),
)
}
}
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
}
const removeFile = (id: string) => {
setUploadingFiles((prev) => prev.filter((f) => f.id !== id))
}
const isUploadingAny = uploadingFiles.some((f) => f.isUploading)
const successfulAttachments = uploadingFiles
.map((f) => f.payload)
.filter((p): p is KanbanAttachmentPayload => !!p)
const canSend = (text.trim().length > 0 || successfulAttachments.length > 0) && !isUploadingAny
const handleSend = async () => {
if (!canSend || isSubmitting) return
try {
await onSendMessage(
text.trim(),
successfulAttachments.length > 0 ? successfulAttachments : undefined,
)
setText('')
setUploadingFiles([])
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
} catch {
// Error handled by parent
}
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (showMentionList && filteredMembers.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setHighlightedIndex((prev) => (prev + 1) % filteredMembers.length)
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setHighlightedIndex((prev) => (prev - 1 + filteredMembers.length) % filteredMembers.length)
return
}
if (e.key === 'Enter' || e.key === 'Tab') {
e.preventDefault()
const selected = filteredMembers[highlightedIndex]
if (selected) handleSelectMention(selected)
return
}
if (e.key === 'Escape') {
setShowMentionList(false)
return
}
}
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
handleSend()
}
}
return (
<div className="relative flex flex-col w-full border border-border focus-within:border-foreground/40 bg-card rounded-2xl p-2.5 shadow-2xs transition-all">
{/* Mention Popup */}
{showMentionList && filteredMembers.length > 0 && (
<div
ref={mentionListRef}
className="absolute bottom-full left-0 mb-2 w-64 max-h-48 overflow-y-auto rounded-xl border border-border bg-popover p-1 shadow-lg z-50"
>
{filteredMembers.map((member, idx) => (
<button
key={member.id}
type="button"
onClick={() => handleSelectMention(member)}
className={`w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${
idx === highlightedIndex
? 'bg-primary text-primary-foreground font-medium'
: 'hover:bg-muted text-foreground'
}`}
>
<Avatar className="w-5 h-5">
{member.image && <AvatarImage src={member.image} />}
<AvatarFallback className="text-[9px]">
{member.name?.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="truncate">{member.name}</span>
</button>
))}
</div>
)}
{/* Uploading / Attached Files Preview */}
{uploadingFiles.length > 0 && (
<div className="flex flex-wrap gap-1.5 pb-2 mb-1.5 border-b border-border/50">
{uploadingFiles.map((uf) => {
const isImage = uf.file.type.startsWith('image/')
return (
<div
key={uf.id}
className="flex items-center gap-1.5 pl-2 pr-1.5 py-1 rounded-lg bg-muted/60 border border-border text-xs max-w-[200px]"
>
{uf.isUploading ? (
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary shrink-0" />
) : isImage ? (
<ImageIcon className="w-3.5 h-3.5 text-primary shrink-0" />
) : (
<FileText className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
)}
<div className="min-w-0 flex-1 truncate">
<span className="truncate block font-medium text-[11px]">{uf.file.name}</span>
<span className="text-[9px] text-muted-foreground font-mono">
{formatSize(uf.file.size)}
</span>
</div>
<button
type="button"
onClick={() => removeFile(uf.id)}
className="p-0.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted shrink-0"
>
<X className="w-3 h-3" />
</button>
</div>
)
})}
</div>
)}
{/* Text Area */}
<textarea
ref={textareaRef}
value={text}
onChange={handleTextChange}
onKeyDown={handleKeyDown}
placeholder={m.comment_placeholder()}
rows={1}
className="w-full min-h-[44px] max-h-[160px] bg-transparent border-0 focus:outline-hidden focus-visible:ring-0 resize-none text-xs text-foreground placeholder:text-muted-foreground/70 p-1 font-sans leading-relaxed"
/>
{/* Footer Controls: Attachment Button + Send Button */}
<div className="flex items-center justify-between pt-1 mt-1 border-t border-border/40">
<div className="flex items-center gap-1">
<input
ref={fileInputRef}
type="file"
multiple
className="hidden"
onChange={handleFileSelect}
/>
<Button
type="button"
variant="ghost"
size="icon-xs"
onClick={() => fileInputRef.current?.click()}
className="h-7 w-7 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted"
title="Attach files"
disabled={isSubmitting}
>
<Paperclip className="w-3.5 h-3.5" />
</Button>
<span className="text-[10px] text-muted-foreground/60 hidden sm:inline pl-1">
Cmd+Enter to send
</span>
</div>
<Button
type="button"
size="icon-xs"
onClick={handleSend}
disabled={!canSend || isSubmitting}
className="h-7 w-7 rounded-full shadow-xs bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-40 transition-all shrink-0"
title="Send comment"
>
{isSubmitting || isUploadingAny ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<ArrowUp className="w-3.5 h-3.5 stroke-[2.5]" />
)}
</Button>
</div>
</div>
)
}
@@ -0,0 +1,161 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { toast } from 'sonner'
import { Loader2, MessageSquare, X } from 'lucide-react'
import { TaskCommentCard } from './task-comment-card'
import { TaskCommentInput } from './task-comment-input'
import type { KanbanAttachmentInfo, KanbanAttachmentPayload, KanbanCommentInfo } from '@shumai/dtos'
interface TaskCommentThreadProps {
teamId: string
taskId: string
initialComments?: KanbanCommentInfo[]
}
export function TaskCommentThread({ teamId, taskId, initialComments }: TaskCommentThreadProps) {
const queryClient = useQueryClient()
const [viewingAttachment, setViewingAttachment] = useState<KanbanAttachmentInfo | null>(null)
// Query Current User Info
const { data: me } = useQuery({
queryKey: ['teams', teamId, 'me'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].me.$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to fetch me')
return await res.json()
},
enabled: !!teamId,
})
const isOwnerOrAdmin = me?.role?.toLowerCase() === 'owner' || me?.role?.toLowerCase() === 'editor'
// Query Comments
const { data: commentsData, isLoading } = useQuery({
queryKey: ['teams', teamId, 'kanban', 'tasks', taskId, 'comments'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].comments.$get({
param: { teamId, taskId },
})
if (!res.ok) throw new Error('Failed to fetch comments')
return (await res.json()) as { data: KanbanCommentInfo[] }
},
initialData: initialComments ? { data: initialComments } : undefined,
enabled: !!teamId && !!taskId,
refetchInterval: 4000,
})
const comments = commentsData?.data || []
// Add Comment Mutation
const { mutateAsync: addComment, isPending: isAdding } = useMutation({
mutationFn: async ({
body,
attachments,
}: {
body: string
attachments?: KanbanAttachmentPayload[]
}) => {
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].comments.$post({
param: { teamId, taskId },
json: { body, attachments },
})
if (!res.ok) {
const err = await res.json().catch(() => ({ message: m.error() }))
throw new Error((err as { message?: string }).message || m.error())
}
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'kanban', 'tasks', taskId, 'comments'],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'kanban', 'task', taskId],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'kanban', 'tasks'],
})
},
onError: (err) => {
toast.error(err.message)
},
})
const handleSendMessage = async (text: string, attachments?: KanbanAttachmentPayload[]) => {
await addComment({ body: text, attachments })
}
return (
<div className="flex flex-col h-full overflow-hidden bg-background">
{/* Lightbox / Full-screen Attachment Viewer */}
{viewingAttachment && (
<div
className="fixed inset-0 z-50 bg-black/90 flex flex-col items-center justify-center p-4 animate-in fade-in duration-150"
onClick={() => setViewingAttachment(null)}
>
<button
type="button"
onClick={() => setViewingAttachment(null)}
className="absolute top-4 right-4 text-white/80 hover:text-white bg-white/10 hover:bg-white/20 rounded-full p-2 transition-colors z-50 cursor-pointer"
title="Close"
>
<X className="w-6 h-6" />
</button>
<div className="w-full h-full flex items-center justify-center p-2">
<img
src={viewingAttachment.url}
alt={viewingAttachment.name}
className="max-w-full max-h-[85vh] object-contain rounded-lg shadow-2xl"
onClick={(e) => e.stopPropagation()}
/>
</div>
</div>
)}
{/* Comments List */}
<ScrollArea className="flex-1 p-3.5">
<div className="space-y-3 pr-1 pb-2">
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : comments.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-center text-xs text-muted-foreground/80 space-y-2">
<div className="w-10 h-10 rounded-full bg-muted/60 flex items-center justify-center">
<MessageSquare className="w-5 h-5 opacity-40" />
</div>
<p className="font-medium">{m.no_comments_yet()}</p>
</div>
) : (
comments.map((comment) => (
<TaskCommentCard
key={comment.id}
teamId={teamId}
taskId={taskId}
comment={comment}
currentUserId={me?.id}
isOwnerOrAdmin={isOwnerOrAdmin}
onViewAttachment={(att) => setViewingAttachment(att)}
/>
))
)}
</div>
</ScrollArea>
{/* Composer Input Box */}
<div className="p-3 border-t border-border/60 bg-card/60 shrink-0">
<TaskCommentInput
teamId={teamId}
onSendMessage={handleSendMessage}
isSubmitting={isAdding}
/>
</div>
</div>
)
}
@@ -0,0 +1,104 @@
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { KanbanTaskEventType, type KanbanEventInfo } from '@shumai/dtos'
import { getStatusLabel } from '../kanban-types'
import { format } from 'date-fns'
import { Loader2 } from 'lucide-react'
interface TaskEventTimelineProps {
teamId: string
taskId: string
initialEvents?: KanbanEventInfo[]
}
function getEventDescription(event: KanbanEventInfo): string {
const data = event.data || {}
switch (event.type) {
case KanbanTaskEventType.CREATED:
return 'Created task'
case KanbanTaskEventType.STATUS_CHANGED:
return `Changed status from ${event.fromStatus ? getStatusLabel(event.fromStatus) : 'None'} to ${event.toStatus ? getStatusLabel(event.toStatus) : 'None'}`
case KanbanTaskEventType.ASSIGNED:
return 'Assigned task'
case KanbanTaskEventType.UNASSIGNED:
return 'Unassigned task'
case KanbanTaskEventType.PRIORITY_CHANGED:
return `Changed priority to ${String(data.to || '')}`
case KanbanTaskEventType.GOAL_CHANGED:
return 'Updated goal association'
case KanbanTaskEventType.DEPENDENCY_ADDED:
return 'Added prerequisite dependency'
case KanbanTaskEventType.DEPENDENCY_REMOVED:
return 'Removed prerequisite dependency'
case KanbanTaskEventType.CHANGES_REQUESTED:
return `Requested changes: "${String(data.reason || '')}"`
case KanbanTaskEventType.BLOCKED:
return `Task blocked: "${String(data.reason || data.blockReason || '')}"`
case KanbanTaskEventType.UNBLOCKED:
return 'Task unblocked'
case KanbanTaskEventType.COMMENTED:
return 'Added a comment'
default:
return event.type
}
}
export function TaskEventTimeline({ teamId, taskId, initialEvents }: TaskEventTimelineProps) {
const { data: eventsData, isLoading } = useQuery({
queryKey: ['teams', teamId, 'kanban', 'tasks', taskId, 'events'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].events.$get({
param: { teamId, taskId },
})
if (!res.ok) throw new Error('Failed to fetch events')
return (await res.json()) as { data: KanbanEventInfo[] }
},
initialData: initialEvents ? { data: initialEvents } : undefined,
enabled: !!teamId && !!taskId,
})
const events = eventsData?.data || []
return (
<ScrollArea className="h-full p-3">
<div className="space-y-4 pr-2">
{/* Audit Event Stream */}
<div className="space-y-2">
{isLoading ? (
<div className="flex items-center justify-center py-6">
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
</div>
) : events.length === 0 ? (
<div className="py-6 text-center text-xs text-muted-foreground">
{m.no_activity_yet()}
</div>
) : (
<div className="relative pl-4 space-y-3 before:absolute before:left-1.5 before:top-2 before:bottom-2 before:w-0.5 before:bg-border/60">
{events.map((event) => (
<div key={event.id} className="relative flex items-start gap-2 text-xs">
<div className="absolute -left-4 top-1 w-2.5 h-2.5 rounded-full bg-background border-2 border-primary shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-1">
<span className="font-medium text-foreground truncate">
{event.actor?.name || 'System'}
</span>
<span className="text-[10px] text-muted-foreground font-mono shrink-0">
{format(new Date(event.createdAt), 'MM/dd HH:mm')}
</span>
</div>
<p className="text-[11px] text-muted-foreground leading-snug mt-0.5">
{getEventDescription(event)}
</p>
</div>
</div>
))}
</div>
)}
</div>
</div>
</ScrollArea>
)
}
@@ -0,0 +1,469 @@
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Textarea } from '@/ui/components/ui/textarea'
import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { DateTimePicker } from '@/ui/components/datetime-picker'
import { toast } from 'sonner'
import {
KanbanTaskPriority,
type KanbanTaskDetail,
type KanbanGoalInfo,
type AgentInfo,
type KanbanTaskAssetInfo,
type UpdateKanbanTaskRequest,
UNASSIGNED_GOAL_ID,
} from '@shumai/dtos'
import { getPriorityBadgeColor, getPriorityLabel } from '../kanban-types'
import { TaskParentSelector } from '../task-parent-selector'
import { TaskRelatedAssets } from '../task-related-assets'
import { TaskTargetFolderDialog } from './task-target-folder-dialog'
import { Bot, Folder, Target, Loader2 } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
interface TaskInfoFormProps {
teamId: string
task: KanbanTaskDetail
canEdit?: boolean
}
export function TaskInfoForm({ teamId, task, canEdit = true }: TaskInfoFormProps) {
const queryClient = useQueryClient()
// Local state for debounced text inputs
const [title, setTitle] = useState(task.title)
const [description, setDescription] = useState(task.description || '')
const [isFolderPickerOpen, setIsFolderPickerOpen] = useState(false)
const [targetFolderName, setTargetFolderName] = useState<string | null>(null)
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
// Sync with prop changes if task id changed
useEffect(() => {
setTitle(task.title)
setDescription(task.description || '')
}, [task.id, task.title, task.description])
// Queries for selectors
const { data: members = [] } = useQuery({
queryKey: ['teams', teamId, 'members', 'human'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].members.$get({
param: { teamId },
query: { includeAgents: 'false' },
})
if (!res.ok) return []
const data = await res.json()
return Array.isArray(data) ? data : []
},
enabled: !!teamId,
})
const { data: agents = [] } = useQuery({
queryKey: ['teams', teamId, 'agents'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].agents.$get({
param: { teamId },
})
if (!res.ok) return []
return ((await res.json()) as AgentInfo[]) || []
},
enabled: !!teamId,
})
const { data: goalsData } = useQuery({
queryKey: ['teams', teamId, 'kanban', 'goals'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].kanban.goals.$get({
param: { teamId },
query: {},
})
if (!res.ok) return { data: [] }
return (await res.json()) as { data: KanbanGoalInfo[] }
},
enabled: !!teamId,
})
const goals = goalsData?.data || []
// Auto-save update mutation
const { mutate: updateTask, isPending: isUpdating } = useMutation({
mutationFn: async (patch: UpdateKanbanTaskRequest) => {
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].$patch({
param: { teamId, taskId: task.id },
json: patch,
})
if (!res.ok) {
const err = await res.json().catch(() => ({ message: m.error() }))
throw new Error((err as { message?: string }).message || m.error())
}
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'task', task.id] })
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
},
onError: (err) => {
toast.error(err.message)
},
})
const { mutate: linkAssets } = useMutation({
mutationFn: async (newAssets: KanbanTaskAssetInfo[]) => {
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].assets.$post({
param: { teamId, taskId: task.id },
json: { assetIds: newAssets.map((a) => a.id) },
})
if (!res.ok) throw new Error('Failed to link assets')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'task', task.id] })
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
toast.success(m.asset_linked())
},
onError: (err) => {
toast.error(err.message)
},
})
const { mutate: unlinkAsset } = useMutation({
mutationFn: async (assetId: string) => {
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].assets[
':assetId'
].$delete({
param: { teamId, taskId: task.id, assetId },
})
if (!res.ok) throw new Error('Failed to unlink asset')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'task', task.id] })
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
toast.success(m.asset_unlinked())
},
onError: (err) => {
toast.error(err.message)
},
})
// Debounced auto-save handler for text fields
const handleTextChange = (field: 'title' | 'description', value: string) => {
if (field === 'title') setTitle(value)
if (field === 'description') setDescription(value)
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current)
}
debounceTimerRef.current = setTimeout(() => {
if (field === 'title' && value.trim() && value.trim() !== task.title) {
updateTask({ title: value.trim() })
} else if (field === 'description' && value !== (task.description || '')) {
updateTask({ description: value.trim() || null })
}
}, 600)
}
const isAgentic = task.isAgentTask
return (
<ScrollArea className="h-full p-5">
<div className="space-y-6 w-full pr-3">
{/* Title Input */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label
htmlFor="task-title"
className="text-xs font-semibold text-muted-foreground uppercase tracking-wider"
>
{m.task_title()}
</Label>
{isUpdating && (
<span className="flex items-center gap-1 text-[11px] text-muted-foreground animate-pulse">
<Loader2 className="w-3 h-3 animate-spin" />
{m.saving()}
</span>
)}
</div>
<Input
id="task-title"
value={title}
onChange={(e) => handleTextChange('title', e.target.value)}
disabled={!canEdit}
className="text-base font-semibold h-10 bg-background"
placeholder={m.task_title_placeholder()}
/>
</div>
{/* Description Textarea */}
<div className="space-y-1.5">
<Label
htmlFor="task-description"
className="text-xs font-semibold text-muted-foreground uppercase tracking-wider"
>
{m.task_description()}
</Label>
<Textarea
id="task-description"
value={description}
onChange={(e) => handleTextChange('description', e.target.value)}
disabled={!canEdit}
rows={5}
className="text-xs leading-relaxed bg-background"
placeholder={m.task_description_placeholder()}
/>
</div>
{/* Properties Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 p-4 rounded-lg bg-muted/20 border border-border/60">
{/* Row 1: Agent Task Switch (Read-Only) */}
<div className="sm:col-span-2 flex items-center justify-between space-x-2 rounded-md border border-border/60 bg-background/50 px-3 py-2 h-14">
<div className="space-y-0.5 min-w-0 pr-2">
<Label className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
<Bot className="w-3.5 h-3.5 text-orange-500" />
<span>{m.task_type_agent()}</span>
</Label>
<p className="text-[11px] text-muted-foreground/80 line-clamp-1">
{m.task_type_agent_desc()}
</p>
</div>
<Switch checked={task.isAgentTask} disabled={true} />
</div>
{/* Row 2: Priority Selector and Goal Selector */}
<div className="space-y-1.5">
<Label className="text-xs font-medium text-muted-foreground">{m.task_priority()}</Label>
<Select
value={task.priority}
onValueChange={(val) => updateTask({ priority: val as KanbanTaskPriority })}
disabled={!canEdit}
>
<SelectTrigger className="w-full h-8 text-xs bg-background">
<SelectValue />
</SelectTrigger>
<SelectContent>
{Object.values(KanbanTaskPriority).map((p) => (
<SelectItem key={p} value={p}>
<span
className={cn(
'px-1.5 py-0.5 rounded text-[10px] uppercase font-medium',
getPriorityBadgeColor(p),
)}
>
{getPriorityLabel(p)}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-medium text-muted-foreground">{m.goals()}</Label>
<Select
value={task.goal?.id || 'none'}
onValueChange={(val) => updateTask({ goalId: val === 'none' ? null : val })}
disabled={!canEdit}
>
<SelectTrigger className="w-full h-8 text-xs bg-background">
<SelectValue placeholder={m.no_folder_selected()} />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">
<span className="text-muted-foreground italic">None</span>
</SelectItem>
{goals
.filter((g) => g.id !== UNASSIGNED_GOAL_ID)
.map((g) => (
<SelectItem key={g.id} value={g.id}>
<div className="flex items-center gap-2">
<Target className="w-3.5 h-3.5 text-primary" />
<span>{g.title}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Row 3: Assignee Selector and Reporter Selector */}
<div className="space-y-1.5">
<Label className="text-xs font-medium text-muted-foreground">
{isAgentic ? m.select_agent() : m.assignee()}
</Label>
<Select
value={task.assignee?.id || 'none'}
onValueChange={(val) => updateTask({ assigneeId: val === 'none' ? null : val })}
disabled={!canEdit}
>
<SelectTrigger className="w-full h-8 text-xs bg-background">
<SelectValue placeholder={m.unassigned()} />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">
<span className="text-muted-foreground italic">{m.unassigned()}</span>
</SelectItem>
{isAgentic
? agents.map((a) => (
<SelectItem key={a.id} value={a.id}>
<div className="flex items-center gap-2">
<Bot className="w-3.5 h-3.5 text-purple-500" />
<span>{a.name}</span>
</div>
</SelectItem>
))
: members.map((mItem) => (
<SelectItem key={mItem.id} value={mItem.id}>
<div className="flex items-center gap-2">
<Avatar size="sm" className="w-4 h-4">
<AvatarImage src={mItem.image} />
<AvatarFallback className="text-[8px]">
{mItem.name.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span>{mItem.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-medium text-muted-foreground">{m.reporter()}</Label>
<Select
value={task.reporter?.id || 'none'}
onValueChange={(val) => updateTask({ reporterId: val === 'none' ? null : val })}
disabled={!canEdit}
>
<SelectTrigger className="w-full h-8 text-xs bg-background">
<SelectValue placeholder={m.unassigned()} />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">
<span className="text-muted-foreground italic">{m.unassigned()}</span>
</SelectItem>
{members.map((mItem) => (
<SelectItem key={mItem.id} value={mItem.id}>
<div className="flex items-center gap-2">
<Avatar size="sm" className="w-4 h-4">
<AvatarImage src={mItem.image} />
<AvatarFallback className="text-[8px]">
{mItem.name.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span>{mItem.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Row 4: Target Folder Selector (only for agent task) */}
{isAgentic && (
<div className="sm:col-span-2 space-y-1.5">
<Label className="text-xs font-medium text-muted-foreground">
{m.target_folder()}
</Label>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setIsFolderPickerOpen(true)}
disabled={!canEdit}
className="w-full justify-start h-8 text-xs bg-background truncate font-normal"
>
<Folder className="w-3.5 h-3.5 mr-2 text-primary shrink-0" />
<span className="truncate">
{targetFolderName ||
(task.targetFolderId ? 'Selected Folder' : m.select_target_folder())}
</span>
</Button>
</div>
</div>
)}
{/* Row 5: Start Date and Due Date */}
<div className="space-y-1.5">
<Label className="text-xs font-medium text-muted-foreground">{m.start_date()}</Label>
<DateTimePicker
value={task.startDate ? new Date(task.startDate) : undefined}
onChange={(date) => updateTask({ startDate: date ? date.toISOString() : null })}
disabled={!canEdit}
placeholder={m.start_date()}
className="h-8 text-xs bg-background"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-medium text-muted-foreground">{m.due_date()}</Label>
<DateTimePicker
value={task.dueDate ? new Date(task.dueDate) : undefined}
onChange={(date) => updateTask({ dueDate: date ? date.toISOString() : null })}
disabled={!canEdit}
placeholder={m.due_date()}
className="h-8 text-xs bg-background"
/>
</div>
{/* Row 6: Parent Tasks */}
<div className="sm:col-span-2 space-y-1.5">
<Label className="text-xs font-medium text-muted-foreground">{m.parent_tasks()}</Label>
<TaskParentSelector
teamId={teamId}
currentTaskId={task.id}
excludeTaskIds={task.dependents.map((d) => d.id)}
value={task.dependencies.map((d) => d.id)}
knownTasks={[...task.dependencies, ...task.dependents]}
onChange={(parentIds) => updateTask({ parentIds })}
canEdit={canEdit}
/>
</div>
{/* Row 7: Related Assets */}
<div className="sm:col-span-2 pt-1">
<TaskRelatedAssets
teamId={teamId}
projectId={task.projectId}
assets={task.assets || []}
onAddAssets={(newAssets) => linkAssets(newAssets)}
onRemoveAsset={(assetId) => unlinkAsset(assetId)}
disabled={!canEdit}
/>
</div>
</div>
</div>
{/* Target Folder Dialog */}
{isFolderPickerOpen && (
<TaskTargetFolderDialog
teamId={teamId}
currentProjectId={task.projectId}
currentTargetFolderId={task.targetFolderId}
isOpen={isFolderPickerOpen}
onClose={() => setIsFolderPickerOpen(false)}
onSelect={(projId, foldId, foldName) => {
setTargetFolderName(foldName || 'Selected Folder')
updateTask({ projectId: projId, targetFolderId: foldId })
}}
/>
)}
</ScrollArea>
)
}
@@ -0,0 +1,151 @@
import { useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/ui/components/ui/dialog'
import { Button } from '@/ui/components/ui/button'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { FolderTree } from '@/ui/components/folder-tree'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { m } from '@/ui/paraglide/messages.js'
import type { AssetInfo, ProjectInfo } from '@shumai/dtos'
import { Loader2, Folder } from 'lucide-react'
interface TaskTargetFolderDialogProps {
teamId: string
currentProjectId?: string | null
currentTargetFolderId?: string | null
isOpen: boolean
onClose: () => void
onSelect: (projectId: string, folderId: string, folderName?: string) => void
}
export function TaskTargetFolderDialog({
teamId,
currentProjectId,
currentTargetFolderId,
isOpen,
onClose,
onSelect,
}: TaskTargetFolderDialogProps) {
const [selectedProjectId, setSelectedProjectId] = useState<string>(currentProjectId || '')
const [selectedFolder, setSelectedFolder] = useState<AssetInfo | null>(null)
const { data: projectsData, isLoading: isLoadingProjects } = useQuery({
queryKey: ['teams', teamId, 'projects'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].projects.$get({
param: { teamId },
query: { first: '100' },
})
if (!res.ok) throw new Error('Failed to fetch projects')
return (await res.json()) as unknown as { data: ProjectInfo[] }
},
enabled: !!teamId && isOpen,
})
const projects = projectsData?.data || []
const activeProjectId = selectedProjectId || (projects[0]?.id ?? '')
const selectedProject = projects.find((p) => p.id === activeProjectId)
const handleConfirm = () => {
if (!activeProjectId) return
const folderId = selectedFolder?.id || selectedProject?.rootFolder
if (folderId) {
onSelect(activeProjectId, folderId, selectedFolder?.name || selectedProject?.name)
onClose()
}
}
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-2xl flex flex-col h-[580px]">
<DialogHeader>
<div className="flex items-center gap-2">
<Folder className="w-5 h-5 text-primary" />
<DialogTitle>{m.select_target_folder()}</DialogTitle>
</div>
</DialogHeader>
<div className="flex flex-col gap-3 flex-1 overflow-hidden py-2">
{/* Project Select */}
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground">
{m.select_project()}
</label>
<Select
value={activeProjectId}
onValueChange={(val) => {
setSelectedProjectId(val)
setSelectedFolder(null)
}}
>
<SelectTrigger className="h-9">
<SelectValue placeholder={m.select_project()} />
</SelectTrigger>
<SelectContent>
{projects.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Folder Tree Scroll Area */}
<div className="space-y-1.5 flex-1 flex flex-col overflow-hidden">
<label className="text-xs font-medium text-muted-foreground">{m.target_folder()}</label>
<div className="border rounded-md flex-1 overflow-hidden bg-sidebar/50">
<ScrollArea className="h-full">
{selectedProject && selectedProject.rootFolder ? (
<FolderTree
teamId={teamId}
projectId={selectedProject.id}
projectName={selectedProject.name}
rootFolderId={selectedProject.rootFolder}
onSelect={setSelectedFolder}
selectedFolderId={
selectedFolder?.id || currentTargetFolderId || selectedProject.rootFolder
}
hideCollections
hideShares
hideRecentlyDeleted
/>
) : (
<div className="flex items-center justify-center h-full p-6 text-xs text-muted-foreground">
{isLoadingProjects ? (
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
) : (
m.no_project_selected()
)}
</div>
)}
</ScrollArea>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
{m.cancel()}
</Button>
<Button onClick={handleConfirm} disabled={!activeProjectId}>
{m.confirm()}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}