"use client"; import { useEffect, useState, useCallback, useRef } from "react"; import { useTranslation } from "react-i18next"; import Link from "@/components/routing/app-link"; import { IconCopy, IconPlayerPause, IconPlayerPlay, IconPlus, IconRestore, IconTrash, IconPaperclip, } from "@tabler/icons-react"; import { Badge } from "@kandev/ui/badge"; import { Button } from "@kandev/ui/button"; import { Label } from "@kandev/ui/label"; import { Switch } from "@kandev/ui/switch"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; import { Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator, } from "@kandev/ui/breadcrumb"; import { TaskProperties } from "./task-properties"; import { ChatActivityTabs } from "./chat-activity-tabs"; import { ExecutionIndicator } from "@/app/office/components/execution-indicator"; import { OfficeTopbarPortal } from "@/app/office/components/office-topbar-portal"; import { TaskDocuments } from "./task-documents"; import { TaskDetailContextPanel } from "../task-detail-context-panel"; import { useTaskContext } from "@/hooks/use-task-context"; import { StatusIcon } from "@/app/office/tasks/[id]/status-icon"; import { StageProgressBar } from "./stage-progress-bar"; import { SubtaskStepper } from "./subtask-stepper"; import { hasBlockerChain } from "./workflow-sort"; import { copyToClipboard } from "@/lib/utils/copy-to-clipboard"; import { NewTaskDialog } from "@/app/office/components/new-task-dialog"; import { ActiveSessionRefProvider } from "./components/active-session-ref-context"; import { TopbarWorkingIndicator } from "./components/topbar-working-indicator"; import { TreeCancelDialog } from "@/components/task/TreeCancelDialog"; import { cancelTaskTree, pauseTaskTree, previewTaskTree, restoreTaskTree, resumeTaskTree, type TreeHold, type TreePreview, } from "@/lib/api/domains/tree-api"; import type { Task, TaskComment, TaskActivityEntry, TaskSession, TimelineEvent, } from "@/app/office/tasks/[id]/types"; import { toast } from "@/lib/toast/sonner"; const COMMENTABLE_DONE_SESSION_STATES = new Set([ "CREATED", "STARTING", "RUNNING", "IDLE", "WAITING_FOR_INPUT", "COMPLETED", ]); type OfficeSimplePaneProps = { task: Task; comments: TaskComment[]; timeline?: TimelineEvent[]; activity: TaskActivityEntry[]; sessions: TaskSession[]; onToggleAdvanced?: () => void; onCommentsChanged?: () => void; }; function sessionSortTime(session: TaskSession): number { const value = session.updatedAt ?? session.completedAt ?? session.startedAt ?? ""; const time = Date.parse(value); return Number.isNaN(time) ? 0 : time; } function latestSession(sessions: TaskSession[]): TaskSession | undefined { return sessions.reduce((latest, session) => { if (!latest) return session; return sessionSortTime(session) >= sessionSortTime(latest) ? session : latest; }, undefined); } function commentsReadOnly(task: Task, sessions: TaskSession[]): boolean { if (task.status === "cancelled") return true; if (task.status !== "done") return false; const session = latestSession(sessions); return !session || !COMMENTABLE_DONE_SESSION_STATES.has(session.state); } function TaskBreadcrumb({ task }: { task: Task }) { const { t } = useTranslation(); return ( {t("task:tasks")} {task.parentIdentifier && ( <> {task.parentTitle} )} {task.title} ); } function TaskHeaderRow({ task, activeHold }: { task: Task; activeHold: TreeHold | null }) { const { t } = useTranslation(); return (
{task.identifier} {task.projectName && {task.projectName}} {activeHold?.mode === "pause" && {t("task:paused")}} {activeHold?.mode === "cancel" && {t("task:cancelledTree")}}
{t("task:copyIdentifier")}
); } function ChildIssuesList({ items, activeHold, }: { items: Task["children"]; activeHold: TreeHold | null; }) { const { t } = useTranslation(); if (items.length === 0) return null; const holdLabel = activeHold?.mode === "pause" ? t("task:paused") : t("task:cancelledTree"); return (

{t("task:subTasks")}

{items.map((child) => ( {child.identifier} {child.title} {activeHold && {holdLabel}} ))}
); } // Takes a catalog key rather than resolved copy: the call sites are plain // click handlers, and the success toast has to resolve at click time. type TreeActionRunner = (action: () => Promise, messageKey: string) => Promise; function PauseResumeButton({ taskId, activeHold, hasTree, busy, runAction, }: { taskId: string; activeHold: TreeHold | null; hasTree: boolean; busy: boolean; runAction: TreeActionRunner; }) { const { t } = useTranslation(); // The success-toast keys are hoisted out of JSX: they are catalog keys, not // copy, and the literal guard only inspects JSX positions. const handleResume = () => runAction(() => resumeTaskTree(taskId), "task:taskTreeResumed"); const handlePause = () => runAction(() => pauseTaskTree(taskId), "task:taskTreePaused"); if (activeHold?.mode === "pause") { return ( ); } if (!hasTree) return null; return ( ); } function CancelRestoreButton({ taskId, activeHold, hasTree, busy, onCancel, runAction, }: { taskId: string; activeHold: TreeHold | null; hasTree: boolean; busy: boolean; onCancel: () => void; runAction: TreeActionRunner; }) { const { t } = useTranslation(); const handleRestore = () => runAction(() => restoreTaskTree(taskId), "task:taskTreeRestored"); if (activeHold?.mode === "cancel") { return ( ); } if (!hasTree) return null; return ( ); } function TreeControls({ task, preview, activeHold, onChanged, }: { task: Task; preview: TreePreview | null; activeHold: TreeHold | null; onChanged: () => Promise; }) { const { t } = useTranslation(); const [cancelOpen, setCancelOpen] = useState(false); const [busy, setBusy] = useState(false); const hasTree = (preview?.task_count ?? 1) > 1 || task.children.length > 0; const handleConfirmCancel = () => { setCancelOpen(false); void runAction(() => cancelTaskTree(task.id), "task:taskTreeCancelled"); }; const runAction = async (action: () => Promise, messageKey: string) => { setBusy(true); try { await action(); toast.success(t(messageKey)); await onChanged(); } catch (error) { toast.error(error instanceof Error ? error.message : t("task:treeActionFailed")); } finally { setBusy(false); } }; if (!hasTree && !activeHold) return null; return (
setCancelOpen(true)} runAction={runAction} /> {preview && hasTree && ( {t("task:tasksAffected", { count: preview.task_count })} )}
); } function TaskActionRow({ task, treePreview, activeHold, onTreeChanged, onNewSubIssue, }: { task: Task; treePreview: TreePreview | null; activeHold: TreeHold | null; onTreeChanged: () => Promise; onNewSubIssue: () => void; }) { const { t } = useTranslation(); const attachInputRef = useRef(null); const handleAttachFiles = useCallback( async (e: React.ChangeEvent) => { const files = e.target.files; if (!files || files.length === 0) return; const { createOrUpdateDocument } = await import("@/lib/api/domains/office-extended-api"); for (const file of Array.from(files)) { try { const content = await file.text(); const key = file.name.replace(/[^a-zA-Z0-9._-]/g, "_"); await createOrUpdateDocument(task.id, key, { title: file.name, content: content.slice(0, 100_000), }); toast.success(t("task:uploaded", { name: file.name })); } catch { toast.error(t("task:failedToUpload", { name: file.name })); } } e.target.value = ""; }, [task.id, t], ); return ( <>
); } function useTaskTreePreview(taskId: string) { const [treePreview, setTreePreview] = useState(null); const [activeHold, setActiveHold] = useState(null); const refreshTreePreview = useCallback(async () => { try { const preview = await previewTaskTree(taskId); setTreePreview(preview); setActiveHold(preview.active_hold ?? null); } catch { setTreePreview(null); setActiveHold(null); } }, [taskId]); useEffect(() => { let cancelled = false; previewTaskTree(taskId) .then((preview) => { if (cancelled) return; setTreePreview(preview); setActiveHold(preview.active_hold ?? null); }) .catch(() => { if (cancelled) return; setTreePreview(null); setActiveHold(null); }); return () => { cancelled = true; }; }, [taskId]); return { treePreview, activeHold, refreshTreePreview }; } export function OfficeSimplePane({ task, comments, timeline, activity, sessions, onToggleAdvanced, onCommentsChanged, }: OfficeSimplePaneProps) { const { t } = useTranslation(); const [subIssueOpen, setSubIssueOpen] = useState(false); const [scrollParent, setScrollParent] = useState(null); const { treePreview, activeHold, refreshTreePreview } = useTaskTreePreview(task.id); return (
{onToggleAdvanced && (
onToggleAdvanced()} />
)} {t("task:openInAdvancedView")}
{task.executionPolicy && ( )}

{task.title}

{task.description && (
{task.description}
)} setSubIssueOpen(true)} /> {hasBlockerChain(task.children) ? ( ) : ( )}
); } /** * Office task-handoffs phase 8.2 — task detail context section. * * Mounts the TaskDetailContextPanel under TaskDocuments, fetching the * context envelope on mount and re-fetching whenever the task ID * changes. The panel renders nothing when the backend returns null * (no HandoffService configured) so the prior layout is preserved. */ function TaskContextSection({ taskId, revisionKey }: { taskId: string; revisionKey: string }) { const ctx = useTaskContext(taskId, revisionKey); if (!ctx) return null; return (
); }