Add local repo contents

This commit is contained in:
willchen96 2026-04-29 19:49:06 +02:00
parent 65739ef1ce
commit d9690965b5
176 changed files with 68998 additions and 0 deletions

View file

@ -0,0 +1,81 @@
"use client";
import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
interface TabDef {
id: string;
label: string;
href: string;
}
const TABS: TabDef[] = [
{ id: "general", label: "General", href: "/account" },
{ id: "models", label: "Models & API Keys", href: "/account/models" },
];
export default function AccountLayout({
children,
}: {
children: React.ReactNode;
}) {
const router = useRouter();
const pathname = usePathname();
const { isAuthenticated, authLoading } = useAuth();
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/");
}
}, [isAuthenticated, authLoading, router]);
if (authLoading) {
return (
<div className="h-dvh bg-white flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-blue-600" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="flex flex-col h-full md:overflow-y-auto px-6 py-6 md:py-10">
<div className="max-w-5xl w-full mx-auto">
<h1 className="text-4xl font-medium mb-8 font-eb-garamond">
Settings
</h1>
<div className="flex flex-col md:flex-row gap-6 md:gap-10">
<nav
aria-label="Settings"
className="md:w-56 shrink-0 flex md:flex-col gap-1 overflow-x-auto"
>
{TABS.map((tab) => {
const active = pathname === tab.href;
return (
<button
key={tab.id}
onClick={() => router.push(tab.href)}
className={`text-left whitespace-nowrap px-3 py-2 rounded-md text-sm font-medium transition-colors ${
active
? "bg-gray-100 text-gray-900"
: "text-gray-500 hover:text-gray-900 hover:bg-gray-50"
}`}
>
{tab.label}
</button>
);
})}
</nav>
<div className="flex-1 min-w-0">{children}</div>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,263 @@
"use client";
import { useEffect, useState } from "react";
import { AlertCircle, Check, ChevronDown, Eye, EyeOff } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { MODELS } from "@/app/components/assistant/ModelToggle";
import {
isModelAvailable,
modelGroupToProvider,
} from "@/app/lib/modelAvailability";
export default function ModelsAndApiKeysPage() {
const { profile, updateModelPreference, updateApiKey } = useUserProfile();
return (
<div className="space-y-4">
{/* Model Preferences */}
<div className="pb-6">
<div className="flex items-center gap-2 mb-4">
<h2 className="text-2xl font-medium font-serif">
Model Preferences
</h2>
</div>
<div className="space-y-4 max-w-md">
<div>
<label className="text-sm text-gray-600 block mb-2">
Tabular review model
</label>
<TabularModelDropdown
value={
profile?.tabularModel ??
"gemini-3-flash-preview"
}
apiKeys={{
claudeApiKey: profile?.claudeApiKey ?? null,
geminiApiKey: profile?.geminiApiKey ?? null,
}}
onChange={(id) =>
updateModelPreference("tabularModel", id)
}
/>
</div>
</div>
</div>
{/* API Keys */}
<div className="py-6">
<div className="flex items-center gap-2 mb-2">
<h2 className="text-2xl font-medium font-serif">
API Keys
</h2>
</div>
<p className="text-sm text-gray-500 mb-4 max-w-xl">
You must provide your own API keys for the app to work or
add your API keys into the .env file if you are running your
own instance of Mike.
</p>
<p className="text-xs text-gray-400 mb-4 max-w-xl">
Title generation automatically routes to the cheapest model
of whichever provider you&rsquo;ve configured (Gemini Flash
Lite if a Gemini key is set, otherwise Claude Haiku).
</p>
<div className="space-y-4 max-w-xl">
<ApiKeyField
label="Anthropic (Claude) API Key"
placeholder="sk-ant-…"
initialValue={profile?.claudeApiKey ?? ""}
onSave={(value) =>
updateApiKey("claude", value.trim() || null)
}
/>
<ApiKeyField
label="Google (Gemini) API Key"
placeholder="AI…"
initialValue={profile?.geminiApiKey ?? ""}
onSave={(value) =>
updateApiKey("gemini", value.trim() || null)
}
/>
</div>
</div>
</div>
);
}
function TabularModelDropdown({
value,
onChange,
apiKeys,
}: {
value: string;
onChange: (id: string) => void;
apiKeys: { claudeApiKey: string | null; geminiApiKey: string | null };
}) {
const [isOpen, setIsOpen] = useState(false);
const selected = MODELS.find((m) => m.id === value);
const selectedAvailable = isModelAvailable(value, apiKeys);
const groups: ("Anthropic" | "Google")[] = ["Anthropic", "Google"];
return (
<DropdownMenu onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<button
type="button"
className="w-full h-9 rounded-md border border-gray-300 bg-white px-3 text-sm shadow-sm flex items-center justify-between gap-2 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-black/10"
>
<span className="flex items-center gap-2 min-w-0">
{!selectedAvailable && (
<AlertCircle className="h-3.5 w-3.5 shrink-0 text-red-500" />
)}
<span className="truncate text-gray-900">
{selected?.label ?? "Select a model"}
</span>
</span>
<ChevronDown
className={`h-3.5 w-3.5 shrink-0 text-gray-500 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
className="z-50"
style={{ width: "var(--radix-dropdown-menu-trigger-width)" }}
align="start"
>
{groups.map((group, gi) => {
const items = MODELS.filter((m) => m.group === group);
if (items.length === 0) return null;
return (
<div key={group}>
{gi > 0 && <DropdownMenuSeparator />}
<DropdownMenuLabel className="text-[10px] uppercase tracking-wider text-gray-400">
{group}
</DropdownMenuLabel>
{items.map((m) => {
const provider = modelGroupToProvider(m.group);
const available = isModelAvailable(
m.id,
apiKeys,
);
return (
<DropdownMenuItem
key={m.id}
className="cursor-pointer"
onSelect={() => onChange(m.id)}
title={
!available
? `Add a ${provider === "claude" ? "Claude" : "Gemini"} API key to use this model`
: undefined
}
>
<span
className={`flex-1 ${available ? "" : "text-gray-400"}`}
>
{m.label}
</span>
{!available && (
<AlertCircle className="h-3.5 w-3.5 text-red-500 ml-1" />
)}
{m.id === value && available && (
<Check className="h-3.5 w-3.5 text-gray-600 ml-1" />
)}
</DropdownMenuItem>
);
})}
</div>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}
function ApiKeyField({
label,
placeholder,
initialValue,
onSave,
}: {
label: string;
placeholder: string;
initialValue: string;
onSave: (value: string) => Promise<boolean>;
}) {
const [value, setValue] = useState(initialValue);
const [reveal, setReveal] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [saved, setSaved] = useState(false);
useEffect(() => {
setValue(initialValue);
}, [initialValue]);
const dirty = value !== initialValue;
const handleSave = async () => {
setIsSaving(true);
const ok = await onSave(value);
setIsSaving(false);
if (ok) {
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} else {
alert(`Failed to save ${label}.`);
}
};
return (
<div>
<label className="text-sm text-gray-600 block mb-2">{label}</label>
<div className="flex gap-2">
<div className="relative flex-1">
<Input
type={reveal ? "text" : "password"}
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={placeholder}
className="pr-10"
autoComplete="off"
spellCheck={false}
/>
<button
type="button"
onClick={() => setReveal((r) => !r)}
className="absolute inset-y-0 right-2 flex items-center text-gray-400 hover:text-gray-600"
aria-label={reveal ? "Hide key" : "Show key"}
>
{reveal ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
<Button
onClick={handleSave}
disabled={isSaving || !dirty || saved}
className="min-w-[80px] transition-all bg-black hover:bg-gray-900 text-white"
>
{isSaving ? (
"Saving..."
) : saved ? (
<>
<Check className="h-4 w-3" />
Saved
</>
) : (
"Save"
)}
</Button>
</div>
</div>
);
}

View file

@ -0,0 +1,240 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LogOut, Check } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { deleteAccount } from "@/app/lib/mikeApi";
export default function AccountPage() {
const router = useRouter();
const { user, signOut } = useAuth();
const { profile, updateDisplayName, updateOrganisation } = useUserProfile();
const [displayName, setDisplayName] = useState("");
const [isSavingName, setIsSavingName] = useState(false);
const [saved, setSaved] = useState(false);
const [organisation, setOrganisation] = useState("");
const [isSavingOrg, setIsSavingOrg] = useState(false);
const [orgSaved, setOrgSaved] = useState(false);
const [deleteConfirm, setDeleteConfirm] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
useEffect(() => {
if (profile?.displayName) {
setDisplayName(profile.displayName);
}
if (profile?.organisation) {
setOrganisation(profile.organisation);
}
}, [profile]);
const handleLogout = async () => {
await signOut();
router.push("/");
};
const handleDeleteAccount = async () => {
setIsDeleting(true);
try {
await deleteAccount();
await signOut();
router.push("/");
} catch {
setIsDeleting(false);
setDeleteConfirm(false);
alert("Failed to delete account. Please try again.");
}
};
const handleSaveDisplayName = async () => {
setIsSavingName(true);
const success = await updateDisplayName(displayName.trim());
setIsSavingName(false);
if (success) {
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} else {
alert("Failed to update display name. Please try again.");
}
};
const handleSaveOrganisation = async () => {
setIsSavingOrg(true);
const success = await updateOrganisation(organisation.trim());
setIsSavingOrg(false);
if (success) {
setOrgSaved(true);
setTimeout(() => setOrgSaved(false), 2000);
} else {
alert("Failed to update organisation. Please try again.");
}
};
if (!user) return null;
return (
<div className="space-y-4">
{/* Profile Settings */}
<div className="pb-6">
<div className="flex items-center gap-2 mb-4">
<h2 className="text-2xl font-medium font-serif">Profile</h2>
</div>
<div className="space-y-4">
<div>
<label className="text-sm text-gray-600 block mb-2">
Display Name
</label>
<div className="flex gap-2">
<Input
type="text"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
placeholder="Enter your name"
className="flex-1"
/>
<Button
onClick={handleSaveDisplayName}
disabled={
isSavingName || !displayName.trim() || saved
}
className="min-w-[80px] transition-all bg-black hover:bg-gray-900 text-white"
>
{isSavingName ? (
"Saving..."
) : saved ? (
<>
<Check className="h-4 w-3" />
Saved
</>
) : (
"Save"
)}
</Button>
</div>
</div>
<div>
<label className="text-sm text-gray-600 block mb-2">
Organisation
</label>
<div className="flex gap-2">
<Input
type="text"
value={organisation}
onChange={(e) =>
setOrganisation(e.target.value)
}
placeholder="Enter your organisation"
className="flex-1"
/>
<Button
onClick={handleSaveOrganisation}
disabled={
isSavingOrg ||
organisation.trim() ===
(profile?.organisation ?? "") ||
orgSaved
}
className="min-w-[80px] transition-all bg-black hover:bg-gray-900 text-white"
>
{isSavingOrg ? (
"Saving..."
) : orgSaved ? (
<>
<Check className="h-4 w-3" />
Saved
</>
) : (
"Save"
)}
</Button>
</div>
</div>
<div>
<label className="text-sm text-gray-600 block mb-2">
Email
</label>
<p className="text-base">{user?.email}</p>
</div>
</div>
</div>
{/* Plan */}
<div className="py-6">
<div className="flex items-center gap-2 mb-4">
<h2 className="text-2xl font-medium font-serif">
Usage Plan
</h2>
</div>
<div>
<p className="text-base font-medium text-gray-500 capitalize">
{profile?.tier || "Free"}
</p>
</div>
</div>
{/* Actions */}
<div className="py-6">
<h2 className="text-2xl font-medium font-serif mb-4">
Actions
</h2>
<Button
variant="outline"
onClick={handleLogout}
className="w-full sm:w-auto"
>
<LogOut className="h-4 w-4 mr-2" />
Sign Out
</Button>
</div>
{/* Danger Zone */}
<div className="py-6">
<h2 className="text-2xl font-medium font-serif mb-1 text-red-600">
Danger Zone
</h2>
<p className="text-sm text-gray-500 mb-4">
Permanently delete your account and all associated data.
This action cannot be undone.
</p>
{deleteConfirm ? (
<div className="rounded-lg border border-red-200 bg-red-50 p-4 space-y-3 max-w-sm">
<p className="text-sm font-medium text-red-700">
Are you sure? This will permanently delete your
account.
</p>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => setDeleteConfirm(false)}
disabled={isDeleting}
className="text-sm"
>
Cancel
</Button>
<Button
onClick={handleDeleteAccount}
disabled={isDeleting}
className="text-sm bg-red-600 hover:bg-red-700 text-white"
>
{isDeleting ? "Deleting…" : "Delete Account"}
</Button>
</div>
</div>
) : (
<Button
variant="outline"
onClick={() => setDeleteConfirm(true)}
className="w-full sm:w-auto border-red-200 text-red-600 hover:bg-red-50 hover:text-red-700"
>
Delete Account
</Button>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,70 @@
"use client";
import { useEffect, useRef } from "react";
import { useParams, useRouter } from "next/navigation";
import { useAssistantChat } from "@/app/hooks/useAssistantChat";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
import { ChatView } from "@/app/components/assistant/ChatView";
import { getChat } from "@/app/lib/mikeApi";
export default function AssistantChatPage() {
const router = useRouter();
const params = useParams();
const id = params.id as string;
const { setCurrentChatId, newChatMessages, setNewChatMessages } =
useChatHistoryContext();
const initialMessages = newChatMessages ?? [];
const { messages, isResponseLoading, handleChat, setMessages, cancel } =
useAssistantChat({ initialMessages, chatId: id });
const hasAutoSent = useRef(false);
const hasLoaded = useRef(false);
useEffect(() => {
setCurrentChatId(id);
}, [id, setCurrentChatId]);
useEffect(() => {
if (initialMessages.length > 0) {
if (newChatMessages) setNewChatMessages(null);
return;
}
if (hasLoaded.current || messages.length > 0) return;
hasLoaded.current = true;
getChat(id)
.then(({ messages: loaded }) => {
if (loaded.length > 0) {
setMessages(loaded);
} else {
router.replace("/assistant");
}
})
.catch(() => router.replace("/assistant"));
}, [id]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (
newChatMessages &&
newChatMessages.length === 1 &&
newChatMessages[0].role === "user" &&
!hasAutoSent.current &&
!isResponseLoading &&
messages.length === 1
) {
hasAutoSent.current = true;
void handleChat(newChatMessages[0]);
}
}, [newChatMessages, messages.length, isResponseLoading]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<ChatView
messages={messages}
isResponseLoading={isResponseLoading}
handleChat={handleChat}
cancel={cancel}
/>
);
}

View file

@ -0,0 +1,35 @@
"use client";
import { useRouter } from "next/navigation";
import { useAssistantChat } from "@/app/hooks/useAssistantChat";
import { InitialView } from "@/app/components/assistant/InitialView";
import { ChatView } from "@/app/components/assistant/ChatView";
import type { MikeMessage } from "@/app/components/shared/types";
export default function AssistantPage() {
const router = useRouter();
const { messages, isResponseLoading, handleChat, handleNewChat, cancel } =
useAssistantChat();
async function handleInitialSubmit(message: MikeMessage) {
const chatId = await handleNewChat(message);
if (chatId) router.push(`/assistant/chat/${chatId}`);
}
if (messages.length === 0) {
return (
<InitialView
onSubmit={(message) => void handleInitialSubmit(message)}
/>
);
}
return (
<ChatView
messages={messages}
isResponseLoading={isResponseLoading}
handleChat={handleChat}
cancel={cancel}
/>
);
}

View file

@ -0,0 +1,107 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Menu } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { ChatHistoryProvider } from "@/app/contexts/ChatHistoryContext";
import { SidebarContext } from "@/app/contexts/SidebarContext";
import { AppSidebar } from "@/app/components/shared/AppSidebar";
export default function MikeLayout({
children,
}: {
children: React.ReactNode;
}) {
const { isAuthenticated, authLoading } = useAuth();
const router = useRouter();
const [isSidebarOpenDesktop, setIsSidebarOpenDesktop] = useState(() => {
if (typeof window !== "undefined") {
const saved = localStorage.getItem("sidebarOpen");
return saved !== null ? saved === "true" : true;
}
return true;
});
const [isSidebarOpen, setIsSidebarOpen] = useState(() => {
if (typeof window !== "undefined" && window.innerWidth < 768) {
return false;
}
return true;
});
useEffect(() => {
if (typeof window !== "undefined" && window.innerWidth >= 768) {
localStorage.setItem("sidebarOpen", isSidebarOpen.toString());
}
}, [isSidebarOpenDesktop]);
useEffect(() => {
if (typeof window === "undefined") return;
const handleResize = () => {
const isSmall = window.innerWidth < 768;
if (isSmall && isSidebarOpen) setIsSidebarOpen(false);
else if (!isSmall && !isSidebarOpen)
setIsSidebarOpen(isSidebarOpenDesktop);
};
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [isSidebarOpen, isSidebarOpenDesktop]);
const handleSidebarToggle = () => {
if (window.innerWidth >= 768) {
setIsSidebarOpenDesktop(!isSidebarOpenDesktop);
setIsSidebarOpen(!isSidebarOpenDesktop);
} else {
setIsSidebarOpen(!isSidebarOpen);
}
};
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
}
}, [authLoading, isAuthenticated, router]);
if (authLoading) {
return (
<div className="flex h-screen items-center justify-center">
<div className="h-6 w-6 animate-spin rounded-full border-2 border-gray-300 border-t-gray-700" />
</div>
);
}
if (!isAuthenticated) return null;
return (
<ChatHistoryProvider>
<SidebarContext.Provider
value={{ setSidebarOpen: (open) => { setIsSidebarOpen(open); setIsSidebarOpenDesktop(open); } }}
>
<div className="h-dvh bg-white flex flex-col">
<div className="flex-1 flex overflow-hidden">
<AppSidebar
isOpen={isSidebarOpen}
onToggle={handleSidebarToggle}
/>
<div className="flex-1 flex flex-col h-dvh md:overflow-hidden relative w-full">
{/* Mobile header */}
<div className="flex md:hidden items-center gap-3 px-4 py-3 border-b border-gray-100 shrink-0">
<button
onClick={handleSidebarToggle}
className="flex items-center justify-center w-8 h-8 rounded hover:bg-gray-100 text-gray-500 transition-colors"
>
<Menu className="h-5 w-5" />
</button>
</div>
<main className="flex-1 overflow-y-auto md:overflow-hidden w-full h-full">
{children}
</main>
</div>
</div>
</div>
</SidebarContext.Provider>
</ChatHistoryProvider>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
"use client";
import { use } from "react";
import { ProjectPage } from "@/app/components/projects/ProjectPage";
interface Props {
params: Promise<{ id: string }>;
}
export default function ProjectDetailPage({ params }: Props) {
const { id } = use(params);
return <ProjectPage projectId={id} />;
}

View file

@ -0,0 +1,13 @@
"use client";
import { use } from "react";
import { TRView } from "@/app/components/tabular/TabularReviewView";
interface Props {
params: Promise<{ id: string; reviewId: string }>;
}
export default function ProjectTabularReviewPage({ params }: Props) {
const { id, reviewId } = use(params);
return <TRView reviewId={reviewId} projectId={id} />;
}

View file

@ -0,0 +1,7 @@
"use client";
import { ProjectsOverview } from "@/app/components/projects/ProjectsOverview";
export default function ProjectsPage() {
return <ProjectsOverview />;
}

View file

@ -0,0 +1,13 @@
"use client";
import { use } from "react";
import { TRView } from "@/app/components/tabular/TabularReviewView";
interface Props {
params: Promise<{ id: string }>;
}
export default function TabularReviewPage({ params }: Props) {
const { id } = use(params);
return <TRView reviewId={id} />;
}

View file

@ -0,0 +1,539 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Plus, Loader2, ChevronDown, Check, Table2 } from "lucide-react";
import { HeaderSearchBtn } from "@/app/components/shared/HeaderSearchBtn";
import { RowActions } from "@/app/components/shared/RowActions";
import {
deleteTabularReview,
listTabularReviews,
createTabularReview,
listProjects,
updateTabularReview,
} from "@/app/lib/mikeApi";
import type { TabularReview, MikeProject } from "@/app/components/shared/types";
import { ToolbarTabs } from "@/app/components/shared/ToolbarTabs";
import { AddNewTRModal } from "@/app/components/tabular/AddNewTRModal";
import { OwnerOnlyModal } from "@/app/components/shared/OwnerOnlyModal";
import { useAuth } from "@/contexts/AuthContext";
type Tab = "all" | "in-project" | "standalone";
const CHECK_W = "w-8 shrink-0";
const NAME_COL_W = "w-[300px] shrink-0";
const TABS: { id: Tab; label: string }[] = [
{ id: "all", label: "All Reviews" },
{ id: "in-project", label: "In Project" },
{ id: "standalone", label: "Standalone" },
];
function formatDate(iso: string) {
return new Date(iso).toLocaleDateString(undefined, {
day: "numeric",
month: "short",
year: "numeric",
});
}
export default function TabularReviewsPage() {
const [reviews, setReviews] = useState<TabularReview[]>([]);
const [projects, setProjects] = useState<MikeProject[]>([]);
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
const [newTROpen, setNewTROpen] = useState(false);
const [activeTab, setActiveTab] = useState<Tab>("all");
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [projectFilter, setProjectFilter] = useState<string | null>(null);
const [filterOpen, setFilterOpen] = useState(false);
const [search, setSearch] = useState("");
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [actionsOpen, setActionsOpen] = useState(false);
const [ownerOnlyAction, setOwnerOnlyAction] = useState<string | null>(null);
const filterRef = useRef<HTMLDivElement>(null);
const actionsRef = useRef<HTMLDivElement>(null);
const router = useRouter();
const { user } = useAuth();
useEffect(() => {
Promise.all([
listTabularReviews().catch(() => []),
listProjects().catch(() => []),
])
.then(([r, p]) => {
setReviews(r);
setProjects(p);
})
.finally(() => setLoading(false));
}, []);
useEffect(() => {
setSelectedIds([]);
}, [activeTab, projectFilter]);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (filterRef.current && !filterRef.current.contains(e.target as Node)) setFilterOpen(false);
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (
actionsRef.current &&
!actionsRef.current.contains(e.target as Node)
) {
setActionsOpen(false);
}
}
if (actionsOpen) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [actionsOpen]);
const q = search.toLowerCase();
const filtered = reviews
.filter((r) => {
if (activeTab === "in-project") return !!r.project_id;
if (activeTab === "standalone") return !r.project_id;
return true;
})
.filter((r) => !projectFilter || r.project_id === projectFilter)
.filter((r) => !q || (r.title ?? "").toLowerCase().includes(q));
const allSelected =
filtered.length > 0 &&
filtered.every((r) => selectedIds.includes(r.id));
const someSelected =
!allSelected && filtered.some((r) => selectedIds.includes(r.id));
function toggleAll() {
if (allSelected) setSelectedIds([]);
else setSelectedIds(filtered.map((r) => r.id));
}
function toggleOne(id: string) {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
);
}
const selectedProject = projects.find((p) => p.id === projectFilter);
const handleNewReview = async (
title: string,
projectId?: string,
documentIds?: string[],
columnsConfig?:
| import("@/app/components/shared/types").ColumnConfig[]
| null,
) => {
setCreating(true);
try {
const review = await createTabularReview({
title,
document_ids: documentIds ?? [],
columns_config: columnsConfig ?? [],
...(projectId && { project_id: projectId }),
});
router.push(
projectId
? `/projects/${projectId}/tabular-reviews/${review.id}`
: `/tabular-reviews/${review.id}`,
);
} finally {
setCreating(false);
}
};
async function handleRenameSubmit(reviewId: string) {
const trimmed = renameValue.trim();
if (!trimmed) {
setRenamingId(null);
return;
}
const review = reviews.find((r) => r.id === reviewId);
if (review && user?.id && review.user_id !== user.id) {
setRenamingId(null);
setOwnerOnlyAction("rename this tabular review");
return;
}
setReviews((prev) =>
prev.map((r) => (r.id === reviewId ? { ...r, title: trimmed } : r)),
);
setRenamingId(null);
await updateTabularReview(reviewId, { title: trimmed });
}
async function handleDeleteSelected() {
const ids = [...selectedIds];
setActionsOpen(false);
const owned = ids.filter((id) => {
const r = reviews.find((rr) => rr.id === id);
return !r || !user?.id || r.user_id === user.id;
});
const blocked = ids.length - owned.length;
setSelectedIds([]);
await Promise.all(
owned.map((id) => deleteTabularReview(id).catch(() => {})),
);
setReviews((prev) => prev.filter((r) => !owned.includes(r.id)));
if (blocked > 0) {
setOwnerOnlyAction(
`delete ${blocked} of the selected reviews — only the review creator can delete a review`,
);
}
}
const projectFilterButton = (
<div className="relative" ref={filterRef}>
<button
onClick={() => setFilterOpen((o) => !o)}
className={`flex items-center gap-1 text-xs font-medium transition-colors ${
projectFilter
? "text-gray-700 hover:text-gray-900"
: "text-gray-500 hover:text-gray-700"
}`}
>
{selectedProject ? selectedProject.name : "Filter by project"}
<ChevronDown className="h-3 w-3" />
</button>
{filterOpen && (
<div className="absolute right-0 top-full mt-1.5 z-20 w-52 rounded-xl border border-gray-100 bg-white shadow-lg overflow-hidden">
<button
onClick={() => {
setProjectFilter(null);
setFilterOpen(false);
}}
className="flex items-center justify-between w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
All Projects
{!projectFilter && (
<Check className="h-3.5 w-3.5 text-gray-400" />
)}
</button>
{projects.length > 0 && (
<div className="border-t border-gray-100" />
)}
{projects.map((p) => (
<button
key={p.id}
onClick={() => {
setProjectFilter(p.id);
setFilterOpen(false);
}}
className="flex items-center justify-between w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<span className="truncate pr-2">{p.name}</span>
{projectFilter === p.id && (
<Check className="h-3.5 w-3.5 shrink-0 text-gray-400" />
)}
</button>
))}
</div>
)}
</div>
);
const toolbarActions = (
<div className="flex items-center gap-2">
{selectedIds.length > 0 && (
<div ref={actionsRef} className="relative">
<button
onClick={() => setActionsOpen((v) => !v)}
className="flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-gray-900 transition-colors"
>
Actions
<ChevronDown className="h-3.5 w-3.5" />
</button>
{actionsOpen && (
<div className="absolute top-full right-0 mt-1 w-36 rounded-lg border border-gray-100 bg-white shadow-lg z-50 overflow-hidden">
<button
onClick={handleDeleteSelected}
className="w-full px-3 py-1.5 text-left text-xs text-red-600 hover:bg-red-50 transition-colors"
>
Delete
</button>
</div>
)}
</div>
)}
{projectFilterButton}
</div>
);
return (
<div className="flex-1 overflow-y-auto bg-white">
{/* Page header */}
<div className="flex items-center justify-between px-8 py-4">
<h1 className="text-2xl font-medium font-serif text-gray-900">
Tabular Reviews
</h1>
<div className="flex items-center gap-2">
<HeaderSearchBtn value={search} onChange={setSearch} placeholder="Search reviews…" />
<button
onClick={() => setNewTROpen(true)}
disabled={creating}
className="flex items-center justify-center p-1.5 text-gray-500 hover:text-gray-900 transition-colors disabled:opacity-40"
>
{creating ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Plus className="h-4 w-4" />
)}
</button>
</div>
</div>
<ToolbarTabs
tabs={TABS}
active={activeTab}
onChange={setActiveTab}
actions={toolbarActions}
/>
{/* Table */}
<div className="w-full overflow-x-auto">
<div className="min-w-max">
<div className="flex items-center h-8 pr-8 border-b border-gray-200 text-xs text-gray-500 font-medium select-none">
<div className={`sticky left-0 z-[60] ${CHECK_W} relative bg-white flex items-center justify-center self-stretch before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-white`}>
{!loading && (
<input
type="checkbox"
checked={allSelected}
ref={(el) => {
if (el) el.indeterminate = someSelected;
}}
onChange={toggleAll}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
)}
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} bg-white pl-2 text-left`}>
Name
</div>
<div className="ml-auto w-24 shrink-0">Columns</div>
<div className="w-24 shrink-0">Documents</div>
<div className="w-40 shrink-0">Project</div>
<div className="w-32 shrink-0">Created</div>
<div className="w-8 shrink-0" />
</div>
{loading ? (
<div>
{[1, 2, 3].map((i) => (
<div
key={i}
className="flex items-center h-10 pr-8 border-b border-gray-50"
>
<div className="w-8 shrink-0" />
<div className="flex-1 min-w-0 pl-3 pr-4">
<div className="h-3.5 w-48 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-24 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-24 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-40 shrink-0">
<div className="h-3 w-24 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-32 shrink-0">
<div className="h-3 w-20 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-8 shrink-0" />
</div>
))}
</div>
) : filtered.length === 0 ? (
<div className="flex flex-col items-start py-24 w-full max-w-xs mx-auto">
{activeTab === "all" && !projectFilter ? (
<>
<Table2 className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Tabular Reviews
</p>
<p className="mt-1 text-xs text-gray-400 max-w-xs text-left">
Extract data from documents into tables
using AI.
</p>
<button
onClick={() => setNewTROpen(true)}
disabled={creating}
className="mt-4 inline-flex items-center gap-1 rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white hover:bg-gray-700 transition-colors shadow-md disabled:opacity-40"
>
+ Create New
</button>
</>
) : (
<p className="text-sm text-gray-400">
No reviews found
</p>
)}
</div>
) : (
<div>
{filtered.map((review) => {
const project = projects.find(
(p) => p.id === review.project_id,
);
const rowBg = selectedIds.includes(review.id)
? "bg-gray-50"
: "bg-white";
return (
<div
key={review.id}
onClick={() => {
if (renamingId === review.id) return;
router.push(
review.project_id
? `/projects/${review.project_id}/tabular-reviews/${review.id}`
: `/tabular-reviews/${review.id}`,
);
}}
className="group flex items-center h-10 pr-8 border-b border-gray-50 hover:bg-gray-50 cursor-pointer transition-colors"
>
<div
className={`sticky left-0 z-[60] ${CHECK_W} p-2 flex items-center justify-center ${rowBg} group-hover:bg-gray-50`}
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={selectedIds.includes(
review.id,
)}
onChange={() =>
toggleOne(review.id)
}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} p-2 ${rowBg} group-hover:bg-gray-50`}>
{renamingId === review.id ? (
<input
autoFocus
value={renameValue}
onChange={(e) =>
setRenameValue(
e.target.value,
)
}
onKeyDown={(e) => {
if (e.key === "Enter")
handleRenameSubmit(
review.id,
);
if (e.key === "Escape")
setRenamingId(null);
}}
onBlur={() =>
handleRenameSubmit(
review.id,
)
}
onClick={(e) =>
e.stopPropagation()
}
className="w-full text-sm text-gray-800 bg-transparent outline-none"
/>
) : (
<span className="text-sm text-gray-800 truncate block">
{review.title ??
"Untitled Review"}
</span>
)}
</div>
<div className="ml-auto w-24 shrink-0 text-sm text-gray-500 truncate">
{review.columns_config?.length ?? 0}
</div>
<div className="w-24 shrink-0 text-sm text-gray-500 truncate">
{review.document_count ?? 0}
</div>
<div className="w-40 shrink-0 text-sm text-gray-500 truncate pr-2">
{project ? (
project.name
) : (
<span className="text-gray-300">
</span>
)}
</div>
<div className="w-32 shrink-0 text-sm text-gray-500 truncate">
{review.created_at ? (
formatDate(review.created_at)
) : (
<span className="text-gray-300">
</span>
)}
</div>
<div
className="w-8 shrink-0 flex justify-end"
onClick={(e) => e.stopPropagation()}
>
<RowActions
onRename={() => {
if (
user?.id &&
review.user_id !== user.id
) {
setOwnerOnlyAction(
"rename this tabular review",
);
return;
}
setRenameValue(
review.title ??
"Untitled Review",
);
setRenamingId(review.id);
}}
onDelete={async () => {
if (
user?.id &&
review.user_id !== user.id
) {
setOwnerOnlyAction(
"delete this tabular review",
);
return;
}
await deleteTabularReview(
review.id,
);
setReviews((prev) =>
prev.filter(
(r) =>
r.id !== review.id,
),
);
}}
/>
</div>
</div>
);
})}
</div>
)}
</div>
</div>
<AddNewTRModal
open={newTROpen}
onClose={() => setNewTROpen(false)}
onAdd={handleNewReview}
projects={projects}
/>
<OwnerOnlyModal
open={!!ownerOnlyAction}
action={ownerOnlyAction ?? undefined}
onClose={() => setOwnerOnlyAction(null)}
/>
</div>
);
}

View file

@ -0,0 +1,504 @@
"use client";
import { use, useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import { ChevronDown, Plus, Users, X } from "lucide-react";
import { getWorkflow, updateWorkflow } from "@/app/lib/mikeApi";
import { ShareWorkflowModal } from "@/app/components/workflows/ShareWorkflowModal";
import { WFEditColumnModal } from "@/app/components/workflows/WFEditColumnModal";
import { WFColumnViewModal } from "@/app/components/workflows/WFColumnViewModal";
import { AddColumnModal } from "@/app/components/tabular/AddColumnModal";
import type { ColumnConfig, MikeWorkflow } from "@/app/components/shared/types";
import {
BUILT_IN_IDS,
BUILT_IN_WORKFLOWS,
} from "@/app/components/workflows/builtinWorkflows";
import { formatIcon, formatLabel } from "@/app/components/tabular/columnFormat";
import { RenameableTitle } from "@/app/components/shared/RenameableTitle";
// dynamic import keeps Tiptap (browser-only) out of the SSR bundle
const WorkflowPromptEditor = dynamic(
() =>
import("@/app/components/workflows/WorkflowPromptEditor").then(
(m) => ({ default: m.WorkflowPromptEditor }),
),
{ ssr: false },
);
interface Props {
params: Promise<{ id: string }>;
}
type SaveStatus = "idle" | "saving" | "saved";
const CHECK_W = "w-8 shrink-0";
const NAME_COL_W = "w-[300px] shrink-0";
// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------
export default function WorkflowDetailPage({ params }: Props) {
const { id } = use(params);
const router = useRouter();
const [workflow, setWorkflow] = useState<MikeWorkflow | null>(null);
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
const isBuiltin = BUILT_IN_IDS.has(id);
const readOnly =
isBuiltin ||
(workflow?.is_system ?? false) ||
workflow?.allow_edit === false;
const canShare = !readOnly && (workflow?.is_owner ?? true);
// Editor state
const [promptMd, setPromptMd] = useState("");
const [columns, setColumns] = useState<ColumnConfig[]>([]);
// Save status
const [saveStatus, setSaveStatus] = useState<SaveStatus>("idle");
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Column selection
const [selectedColIndices, setSelectedColIndices] = useState<number[]>([]);
// Column modal
const [addColumnOpen, setAddColumnOpen] = useState(false);
const [editingColumn, setEditingColumn] = useState<ColumnConfig | null>(null);
const [viewingColumn, setViewingColumn] = useState<ColumnConfig | null>(null);
// Share popover
const [shareOpen, setShareOpen] = useState(false);
// Column actions dropdown
const [colActionsOpen, setColActionsOpen] = useState(false);
const colActionsRef = useRef<HTMLDivElement>(null);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (colActionsRef.current && !colActionsRef.current.contains(e.target as Node)) {
setColActionsOpen(false);
}
}
if (colActionsOpen) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [colActionsOpen]);
// ---------------------------------------------------------------------------
// Load workflow
// ---------------------------------------------------------------------------
useEffect(() => {
if (isBuiltin) {
const wf = BUILT_IN_WORKFLOWS.find((w) => w.id === id) ?? null;
if (!wf) {
setNotFound(true);
} else {
setWorkflow(wf);
setPromptMd(wf.prompt_md ?? "");
setColumns(wf.columns_config ?? []);
}
setLoading(false);
return;
}
getWorkflow(id)
.then((wf) => {
setWorkflow(wf);
setPromptMd(wf.prompt_md ?? "");
setColumns(
(wf.columns_config ?? [])
.slice()
.sort((a, b) => a.index - b.index),
);
})
.catch(() => setNotFound(true))
.finally(() => setLoading(false));
}, [id, isBuiltin]);
// ---------------------------------------------------------------------------
// Debounced auto-save for prompt
// ---------------------------------------------------------------------------
const save = useCallback(
(newPromptMd: string) => {
if (readOnly) return;
if (debounceRef.current) clearTimeout(debounceRef.current);
setSaveStatus("saving");
debounceRef.current = setTimeout(async () => {
try {
await updateWorkflow(id, { prompt_md: newPromptMd });
setSaveStatus("saved");
setTimeout(() => setSaveStatus("idle"), 2000);
} catch {
setSaveStatus("idle");
}
}, 800);
},
[id, readOnly],
);
async function handleTitleCommit(newTitle: string) {
if (!newTitle || newTitle === workflow?.title) return;
const updated = await updateWorkflow(id, { title: newTitle });
setWorkflow(updated);
}
function handlePromptChange(val: string | undefined) {
const next = val ?? "";
setPromptMd(next);
save(next);
}
// ---------------------------------------------------------------------------
// Column save
// ---------------------------------------------------------------------------
async function saveColumns(next: ColumnConfig[]) {
if (readOnly) return;
setSaveStatus("saving");
try {
const updated = await updateWorkflow(id, { columns_config: next });
setWorkflow(updated);
setSaveStatus("saved");
setTimeout(() => setSaveStatus("idle"), 2000);
} catch {
setSaveStatus("idle");
}
}
function handleColumnsAdded(added: ColumnConfig[]) {
const next = [
...columns,
...added.map((c, i) => ({ ...c, index: columns.length + i })),
];
setColumns(next);
saveColumns(next);
setAddColumnOpen(false);
}
function handleColumnSaved(updated: ColumnConfig) {
const next = columns.map((c) =>
c.index === updated.index ? updated : c,
);
setColumns(next);
saveColumns(next);
setEditingColumn(null);
}
// ---------------------------------------------------------------------------
// Render
// ---------------------------------------------------------------------------
if (loading) {
return (
<div className="flex flex-col h-full">
{/* Header skeleton */}
<div className="flex items-center justify-between px-8 py-4 shrink-0">
<div className="flex items-center gap-1.5">
<div className="h-6 w-24 rounded bg-gray-100 animate-pulse" />
<span className="text-gray-300"></span>
<div className="h-6 w-40 rounded bg-gray-100 animate-pulse" />
</div>
</div>
{/* Toolbar skeleton */}
<div className="flex items-center px-8 h-10 border-b border-gray-200 shrink-0">
<div className="h-3 w-20 rounded bg-gray-100 animate-pulse" />
</div>
{/* Table header skeleton */}
<div className="flex items-center h-8 pr-8 border-b border-gray-200 shrink-0">
<div className="w-8 shrink-0 border-r border-gray-100 self-stretch" />
<div className="flex-1 pl-3">
<div className="h-2.5 w-20 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-36 shrink-0">
<div className="h-2.5 w-14 rounded bg-gray-100 animate-pulse" />
</div>
<div className="flex-1">
<div className="h-2.5 w-12 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-8 shrink-0" />
</div>
{/* Row skeletons */}
<div className="flex-1 overflow-hidden">
{[1, 2, 3, 4, 5].map((i) => (
<div key={i} className="flex items-center h-10 pr-8 border-b border-gray-50">
<div className="w-8 shrink-0 border-r border-gray-100 self-stretch" />
<div className="flex-1 pl-3 pr-4">
<div className="h-3 rounded bg-gray-100 animate-pulse" style={{ width: `${40 + (i * 13) % 35}%` }} />
</div>
<div className="w-36 shrink-0">
<div className="h-3 w-16 rounded bg-gray-100 animate-pulse" />
</div>
<div className="flex-1 pr-4">
<div className="h-3 rounded bg-gray-100 animate-pulse" style={{ width: `${50 + (i * 17) % 35}%` }} />
</div>
<div className="w-8 shrink-0" />
</div>
))}
</div>
</div>
);
}
if (notFound || !workflow) {
return (
<div className="flex-1 flex items-center justify-center">
<p className="text-gray-400 font-serif">Workflow not found.</p>
</div>
);
}
return (
<div className="flex flex-col h-full">
{/* Page header */}
<div className="flex items-center justify-between px-8 py-4 shrink-0">
<div className="flex items-center gap-1.5 text-2xl font-medium font-serif">
<button
onClick={() => router.push("/workflows")}
className="text-gray-500 hover:text-gray-700 transition-colors"
>
Workflows
</button>
<span className="text-gray-300"></span>
{readOnly ? (
<span className="text-gray-900 truncate max-w-xs">{workflow.title}</span>
) : (
<RenameableTitle value={workflow.title} onCommit={handleTitleCommit} />
)}
</div>
<div className="flex items-center gap-3">
{/* Save status */}
<span className="text-xs text-gray-400">
{saveStatus === "saving"
? "Saving…"
: saveStatus === "saved"
? "Saved"
: ""}
</span>
{/* Share button (custom workflows only) */}
{canShare && (
<button
onClick={() => setShareOpen(true)}
aria-label="Open workflow people"
title="People"
className="flex items-center text-gray-500 hover:text-gray-900 transition-colors"
>
<Users className="h-4 w-4" />
</button>
)}
{shareOpen && (
<ShareWorkflowModal
workflowId={id}
workflowName={workflow.title}
onClose={() => setShareOpen(false)}
/>
)}
</div>
</div>
{/* Read-only badge for built-in workflows */}
{readOnly && (
<div className="flex items-center h-10 px-8 border-b border-gray-200">
<span className="text-xs text-gray-400">Read-only</span>
</div>
)}
{/* Body */}
<div className="flex-1 min-h-0 flex flex-col">
{workflow.type === "assistant" ? (
/* ── Assistant: WYSIWYG editor ── */
<div className="flex-1 min-h-0 p-6">
<WorkflowPromptEditor
value={promptMd}
onChange={readOnly ? undefined : handlePromptChange}
readOnly={readOnly}
/>
</div>
) : (
/* ── Tabular: Column table ── */
<div className="flex flex-col flex-1 min-h-0">
{/* Toolbar */}
{!readOnly && (
<div className="flex items-center justify-between px-8 h-10 border-b border-gray-200 shrink-0">
<button
onClick={() => setAddColumnOpen(true)}
className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-700 transition-colors"
>
<Plus className="h-3.5 w-3.5" />
Add Column
</button>
{selectedColIndices.length > 0 && (
<div ref={colActionsRef} className="relative">
<button
onClick={() => setColActionsOpen((v) => !v)}
className="flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-gray-900 transition-colors"
>
Actions
<ChevronDown className="h-3.5 w-3.5" />
</button>
{colActionsOpen && (
<div className="absolute top-full right-0 mt-1 w-36 rounded-lg border border-gray-100 bg-white shadow-lg z-50 overflow-hidden">
<button
onClick={() => {
const next = columns
.filter((c) => !selectedColIndices.includes(c.index))
.map((c, i) => ({ ...c, index: i }));
setColumns(next);
saveColumns(next);
setSelectedColIndices([]);
setColActionsOpen(false);
}}
className="w-full px-3 py-1.5 text-left text-xs text-red-600 hover:bg-red-50 transition-colors"
>
Delete
</button>
</div>
)}
</div>
)}
</div>
)}
<div className="flex-1 min-h-0 overflow-auto">
<div className="min-w-max flex min-h-full flex-col">
{/* Table header */}
<div className="flex items-center h-8 pr-8 border-b border-gray-200 text-xs text-gray-500 font-medium shrink-0 select-none">
<div className={`sticky left-0 z-[60] ${CHECK_W} relative bg-white flex items-center justify-center self-stretch before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-white`}>
{columns.length > 0 && (
<input
type="checkbox"
checked={columns.length > 0 && selectedColIndices.length === columns.length}
ref={(el) => { if (el) el.indeterminate = selectedColIndices.length > 0 && selectedColIndices.length < columns.length; }}
onChange={() => setSelectedColIndices(selectedColIndices.length === columns.length ? [] : columns.map((c) => c.index))}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
)}
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} bg-white pl-2 text-left`}>
Column Title
</div>
<div className="ml-auto w-36 shrink-0">Format</div>
<div className="flex-1 min-w-0">Prompt</div>
{!readOnly && <div className="w-8 shrink-0" />}
</div>
{/* Rows */}
<div className="flex-1">
{columns.length === 0 ? (
<div className="flex flex-col items-start py-24 w-full max-w-xs mx-auto">
<Plus className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Columns
</p>
<p className="mt-1 text-xs text-gray-400 text-left">
Add columns to define what this tabular review workflow extracts from each document.
</p>
{!readOnly && (
<button
onClick={() => setAddColumnOpen(true)}
className="mt-4 inline-flex items-center gap-1 rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white hover:bg-gray-700 transition-colors shadow-md"
>
+ Add Column
</button>
)}
</div>
) : (
columns.map((col) => {
const FormatIcon = formatIcon(col.format ?? "text");
const isChecked = selectedColIndices.includes(col.index);
return (
<div
key={col.index}
onClick={() => readOnly ? setViewingColumn(col) : setEditingColumn(col)}
className="group flex items-center h-10 pr-8 border-b border-gray-50 hover:bg-gray-50 cursor-pointer transition-colors"
>
<div
className={`sticky left-0 z-[60] ${CHECK_W} p-2 flex items-center justify-center ${isChecked ? "bg-gray-50" : "bg-white"} group-hover:bg-gray-50`}
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={isChecked}
onChange={() => setSelectedColIndices((prev) => prev.includes(col.index) ? prev.filter((i) => i !== col.index) : [...prev, col.index])}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} p-2 ${isChecked ? "bg-gray-50" : "bg-white"} group-hover:bg-gray-50`}>
<span className="text-sm text-gray-800 truncate block">
{col.name}
</span>
</div>
<div className="ml-auto w-36 shrink-0">
<span className="inline-flex items-center gap-1.5 text-xs text-gray-600">
<FormatIcon className="h-3.5 w-3.5 text-gray-400" />
{formatLabel(col.format ?? "text")}
</span>
</div>
<div className="flex-1 min-w-0 pr-4">
<span className="text-xs text-gray-500 truncate block">
{col.prompt}
</span>
</div>
{!readOnly && (
<div className="w-8 shrink-0 flex justify-end">
<button
onClick={(e) => {
e.stopPropagation();
const next = columns
.filter((c) => c.index !== col.index)
.map((c, i) => ({ ...c, index: i }));
setColumns(next);
saveColumns(next);
}}
className="p-1 text-gray-300 hover:text-red-500 transition-colors"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
)}
</div>
);
})
)}
</div>
</div>
</div>
</div>
)}
</div>
{/* Read-only column view modal */}
{viewingColumn && (
<WFColumnViewModal col={viewingColumn} onClose={() => setViewingColumn(null)} />
)}
{/* Add column modal */}
<AddColumnModal
open={addColumnOpen}
existingCount={columns.length}
onClose={() => setAddColumnOpen(false)}
onAdd={handleColumnsAdded}
/>
{/* Edit column modal */}
{editingColumn && (
<WFEditColumnModal
column={editingColumn}
onClose={() => setEditingColumn(null)}
onSave={handleColumnSaved}
onDelete={() => {
const next = columns
.filter((c) => c.index !== editingColumn.index)
.map((c, i) => ({ ...c, index: i }));
setColumns(next);
saveColumns(next);
setEditingColumn(null);
}}
/>
)}
</div>
);
}

View file

@ -0,0 +1,7 @@
"use client";
import { WorkflowList } from "@/app/components/workflows/WorkflowList";
export default function WorkflowsPage() {
return <WorkflowList />;
}

View file

@ -0,0 +1,110 @@
"use client";
import { useRef, useState } from "react";
import { PlusIcon, Upload, LayoutGridIcon, Loader2Icon } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { uploadStandaloneDocument } from "@/app/lib/mikeApi";
import type { MikeDocument } from "../shared/types";
interface Props {
onSelectDoc: (doc: MikeDocument) => void;
onBrowseAll: () => void;
selectedDocIds?: string[];
}
export function AddDocButton({ onSelectDoc, onBrowseAll, selectedDocIds = [] }: Props) {
const [isOpen, setIsOpen] = useState(false);
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
if (!files.length) return;
setUploading(true);
try {
const uploaded = await Promise.all(
files.map((f) => uploadStandaloneDocument(f)),
);
uploaded.forEach((doc) => onSelectDoc(doc));
} catch (err) {
console.error("Upload failed:", err);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
};
return (
<>
<input
ref={fileInputRef}
type="file"
accept=".pdf,.docx,.doc"
multiple
className="hidden"
onChange={handleUpload}
/>
<DropdownMenu onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<button
className={`flex items-center gap-1 px-2 h-8 rounded-lg text-sm transition-colors cursor-pointer ${
selectedDocIds.length > 0
? "text-black hover:bg-gray-100"
: "text-gray-400 hover:text-gray-700 hover:bg-gray-100"
} ${isOpen ? "bg-gray-100" : ""}`}
title="Add documents"
aria-label="Add documents"
>
{selectedDocIds.length > 0 ? (
<span className="font-medium tabular-nums">{selectedDocIds.length}</span>
) : (
<PlusIcon
className={`h-4 w-4 shrink-0 transition-transform duration-300 ${isOpen ? "rotate-[135deg]" : ""}`}
/>
)}
<span className="hidden sm:inline">
{selectedDocIds.length === 1
? "Document"
: "Documents"}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-44 z-50"
side="bottom"
align="start"
>
<DropdownMenuItem
className="cursor-pointer"
disabled={uploading}
onSelect={(e) => {
e.preventDefault();
fileInputRef.current?.click();
}}
>
{uploading ? (
<Loader2Icon className="h-4 w-4 mr-2 animate-spin text-gray-400" />
) : (
<Upload className="h-4 w-4 mr-2 text-gray-500" />
)}
<span className="text-sm">
{uploading ? "Uploading…" : "Upload files"}
</span>
</DropdownMenuItem>
<DropdownMenuItem
className="cursor-pointer"
onClick={onBrowseAll}
>
<LayoutGridIcon className="h-4 w-4 mr-2 text-gray-500" />
<span className="text-sm">Browse all</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,274 @@
"use client";
import { useCallback, useRef, useState } from "react";
import { X } from "lucide-react";
import { DocPanel, type DocPanelMode } from "../shared/DocPanel";
import type {
MikeCitationAnnotation,
MikeEditAnnotation,
} from "../shared/types";
// ---------------------------------------------------------------------------
// Tab data
// ---------------------------------------------------------------------------
//
// Each tab represents ONE of:
// - a document view (no specific annotation),
// - a single citation quote,
// - a single tracked change.
// There is no selector UI inside the panel — the user picks what to view
// by clicking a different tab (or opening a new one from a citation pill,
// an EditCard's View button, or the download card).
type CommonTab = {
id: string;
documentId: string;
filename: string;
versionId: string | null;
versionNumber: number | null;
warning?: string | null;
initialScrollTop?: number | null;
};
export type DocumentTab = CommonTab & { kind: "document" };
export type CitationTab = CommonTab & {
kind: "citation";
citation: MikeCitationAnnotation;
};
export type EditTab = CommonTab & {
kind: "edit";
edit: MikeEditAnnotation;
};
export type AssistantSidePanelTab = DocumentTab | CitationTab | EditTab;
interface Props {
tabs: AssistantSidePanelTab[];
activeTabId: string | null;
onActivateTab: (id: string) => void;
onCloseTab: (id: string) => void;
onCloseAll: () => void;
/**
* Parent-driven reloading flag per document. Download buttons in
* DocPanel show a spinner iff this returns true for the tab's
* documentId. Used to signal "accept/reject in flight".
*/
isEditorReloading?: (documentId: string) => boolean;
/**
* True while an accept/reject for this exact edit is in flight.
* Disables the panel's Accept/Reject buttons for only the edit
* currently being resolved sibling edits stay clickable.
*/
isEditReloading?: (editId: string) => boolean;
onEditResolveStart?: (args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => void;
onEditResolved?: (args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => void;
onEditError?: (args: {
editId: string;
documentId: string;
versionId: string | null;
message: string;
}) => void;
onWarningDismiss?: (tabId: string) => void;
onScrollChange?: (tabId: string, scrollTop: number) => void;
}
const MIN_WIDTH = 300;
const MAX_WIDTH_OFFSET = 56; // sidebar width
export function AssistantSidePanel({
tabs,
activeTabId,
onActivateTab,
onCloseTab,
onCloseAll,
isEditorReloading,
isEditReloading,
onEditResolveStart,
onEditResolved,
onEditError,
onWarningDismiss,
onScrollChange,
}: Props) {
const panelRef = useRef<HTMLDivElement>(null);
const [panelWidth, setPanelWidth] = useState(() =>
typeof window !== "undefined"
? Math.round((window.innerWidth - MAX_WIDTH_OFFSET) / 2)
: 600,
);
const dragStartX = useRef<number>(0);
const dragStartWidth = useRef<number>(0);
const onMouseDown = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
dragStartX.current = e.clientX;
dragStartWidth.current =
panelRef.current?.offsetWidth ?? panelWidth;
const onMouseMove = (ev: MouseEvent) => {
const delta = dragStartX.current - ev.clientX;
const maxWidth = window.innerWidth - MAX_WIDTH_OFFSET - 200;
setPanelWidth(
Math.min(
maxWidth,
Math.max(MIN_WIDTH, dragStartWidth.current + delta),
),
);
};
const onMouseUp = () => {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
};
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
},
[panelWidth],
);
const active = tabs.find((t) => t.id === activeTabId) ?? tabs[0] ?? null;
if (!active) return null;
return (
<div
ref={panelRef}
className="flex h-full shrink-0 flex-col bg-white relative border-l border-gray-200 shadow-[-4px_0_12px_rgba(0,0,0,0.02)]"
style={{ width: panelWidth }}
>
{/* Drag handle */}
<div
onMouseDown={onMouseDown}
className="absolute left-0 top-0 h-full w-1 cursor-col-resize hover:bg-blue-400 transition-colors z-10"
style={{ marginLeft: -2 }}
/>
{/* Tab strip (Chrome-style) */}
<div className="flex items-end gap-1 pr-2 pt-2 bg-gray-100">
<div className="flex-1 flex items-end gap-1 overflow-x-auto pl-2 pr-2">
{tabs.map((tab) => {
const isActive = tab.id === active.id;
const showVersionBadge =
typeof tab.versionNumber === "number" &&
Number.isFinite(tab.versionNumber) &&
tab.versionNumber > 1;
return (
<div
key={tab.id}
onClick={() => onActivateTab(tab.id)}
className={`group relative flex items-center gap-1.5 pl-3 pr-1.5 h-8 min-w-0 max-w-[220px] rounded-t-lg cursor-pointer select-none transition-colors ${
isActive
? "bg-white text-gray-800 before:content-[''] before:absolute before:bottom-0 before:-left-2 before:w-2 before:h-2 before:bg-[radial-gradient(circle_at_top_left,transparent_8px,white_9px)] after:content-[''] after:absolute after:bottom-0 after:-right-2 after:w-2 after:h-2 after:bg-[radial-gradient(circle_at_top_right,transparent_8px,white_9px)]"
: "bg-gray-200/70 text-gray-600 hover:bg-gray-200"
}`}
>
<span
className={`min-w-0 flex-1 truncate text-xs ${isActive ? "font-medium" : "font-normal"}`}
title={tab.filename}
>
{tab.filename}
</span>
{showVersionBadge && (
<span
className={`shrink-0 inline-flex items-center rounded border px-1 py-px text-[9px] font-medium ${
isActive
? "border-gray-200 bg-white text-gray-600"
: "border-gray-300 bg-white/70 text-gray-500"
}`}
>
V{tab.versionNumber}
</span>
)}
<button
onClick={(e) => {
e.stopPropagation();
onCloseTab(tab.id);
}}
className="shrink-0 rounded-full p-0.5 text-gray-400 hover:bg-gray-300 hover:text-gray-700"
>
<X className="h-3 w-3" />
</button>
</div>
);
})}
</div>
<button
onClick={onCloseAll}
className="shrink-0 mb-1 ml-1 rounded-lg p-1.5 text-gray-400 hover:bg-gray-200 hover:text-gray-700"
title="Close panel"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Tab bodies all mounted, inactive ones hidden. Each tab
preserves its state (scroll, docx-preview render, etc.)
when inactive. */}
<div className="flex-1 min-h-0 relative">
{tabs.map((tab) => {
const isActive = tab.id === active.id;
const mode: DocPanelMode =
tab.kind === "citation"
? {
kind: "citation",
citation: tab.citation,
}
: tab.kind === "edit"
? {
kind: "edit",
edit: tab.edit,
isEditReloading:
isEditReloading?.(tab.edit.edit_id) ??
false,
onResolveStart: onEditResolveStart,
onResolved: onEditResolved,
onError: onEditError,
}
: { kind: "document" };
return (
<div
key={tab.id}
className={`absolute inset-0 flex flex-col ${isActive ? "" : "invisible pointer-events-none"}`}
aria-hidden={!isActive}
>
<DocPanel
documentId={tab.documentId}
filename={tab.filename}
versionId={tab.versionId}
versionNumber={tab.versionNumber}
mode={mode}
isReloading={
isEditorReloading?.(tab.documentId) ?? false
}
warning={tab.warning ?? null}
onWarningDismiss={() =>
onWarningDismiss?.(tab.id)
}
initialScrollTop={tab.initialScrollTop ?? null}
onScrollChange={(scrollTop) =>
onScrollChange?.(tab.id, scrollTop)
}
/>
</div>
);
})}
</div>
</div>
);
}

View file

@ -0,0 +1,293 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { ChevronLeft, Search, X } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { MikeWorkflow } from "../shared/types";
import { listWorkflows } from "@/app/lib/mikeApi";
import { BUILT_IN_WORKFLOWS } from "../workflows/builtinWorkflows";
interface Props {
open: boolean;
onClose: () => void;
onSelect: (workflow: MikeWorkflow) => void;
projectName?: string;
projectCmNumber?: string | null;
initialWorkflowId?: string;
}
export function AssistantWorkflowModal({
open,
onClose,
onSelect,
projectName,
projectCmNumber,
initialWorkflowId,
}: Props) {
const [workflows, setWorkflows] = useState<MikeWorkflow[]>([]);
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState<MikeWorkflow | null>(null);
const [search, setSearch] = useState("");
const [rightVisible, setRightVisible] = useState(false);
useEffect(() => {
if (!selected) {
setRightVisible(false);
return;
}
const frame = requestAnimationFrame(() => setRightVisible(true));
return () => cancelAnimationFrame(frame);
}, [selected]);
useEffect(() => {
if (!open) {
setSelected(null);
setSearch("");
return;
}
const builtins = BUILT_IN_WORKFLOWS.filter(
(w) => w.type === "assistant",
);
setWorkflows(builtins);
setLoading(true);
listWorkflows("assistant")
.then((custom) => {
const all = [...builtins, ...custom];
setWorkflows(all);
if (initialWorkflowId) {
const match = all.find((w) => w.id === initialWorkflowId);
if (match) setSelected(match);
}
})
.catch(() => {
if (initialWorkflowId) {
const match = builtins.find((w) => w.id === initialWorkflowId);
if (match) setSelected(match);
}
})
.finally(() => setLoading(false));
// Pre-select from builtins immediately if possible
if (initialWorkflowId) {
const match = builtins.find((w) => w.id === initialWorkflowId);
if (match) setSelected(match);
}
}, [open, initialWorkflowId]);
if (!open) return null;
const filteredWorkflows = search
? workflows.filter((w) => w.title.toLowerCase().includes(search.toLowerCase()))
: workflows;
function handleUse() {
if (!selected) return;
onSelect(selected);
onClose();
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div
className={`w-full rounded-2xl bg-white shadow-2xl flex flex-col h-[600px] ${selected ? "max-w-4xl" : "max-w-2xl"}`}
>
{/* Header */}
<div className="flex items-center justify-between px-4 py-4 shrink-0 border-b border-gray-100">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{projectName ? (
<>
<span>Projects</span>
<span></span>
<span>
{projectName}
{projectCmNumber
? ` (#${projectCmNumber})`
: ""}
</span>
<span></span>
<span>Assistant</span>
<span></span>
<span>Add workflow</span>
</>
) : (
<>
<span>Assistant</span>
<span></span>
<span>Add workflow</span>
</>
)}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Content */}
<div className="flex flex-row flex-1 min-h-0 overflow-hidden">
{/* Left panel — workflow list */}
<div
className={`overflow-y-auto ${selected ? "w-80 shrink-0" : "flex-1"}`}
>
{/* Search */}
<div className="px-4 pt-3 pb-2 shrink-0">
<div className="flex items-center gap-1.5 rounded-md border border-gray-200 bg-gray-50 px-2.5 py-1">
<Search className="h-3 w-3 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search workflows…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 outline-none"
/>
{search && (
<button onClick={() => setSearch("")} className="text-gray-400 hover:text-gray-600">
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
{loading ? (
<div className="space-y-px px-4 pt-1">
{[60, 45, 75, 50, 65, 40, 55].map((w, i) => (
<div
key={i}
className="flex items-center justify-between gap-3 py-3 border-b border-gray-50"
>
<div
className="h-3 rounded bg-gray-100 animate-pulse"
style={{ width: `${w}%` }}
/>
<div className="h-3 w-10 rounded bg-gray-100 animate-pulse shrink-0" />
</div>
))}
</div>
) : filteredWorkflows.length === 0 ? (
<p className="px-4 py-8 text-sm text-center text-gray-400">
{search ? "No matches found" : "No assistant workflows found"}
</p>
) : (
filteredWorkflows.map((wf) => (
<button
key={wf.id}
type="button"
onClick={() =>
setSelected((prev) =>
prev?.id === wf.id ? null : wf,
)
}
className={`w-full flex items-center gap-3 px-4 py-3 text-xs text-left transition-colors border-b border-gray-50 ${
selected?.id === wf.id
? "bg-gray-50"
: "hover:bg-gray-50"
}`}
>
<span className="flex-1 truncate text-gray-800">
{wf.title}
</span>
<span className="shrink-0 text-xs text-gray-400">
{wf.is_system ? "Built-in" : "Custom"}
</span>
</button>
))
)}
</div>
{/* Right panel — prompt preview */}
{selected && (
<div className={`flex-1 border-l border-gray-100 flex flex-col overflow-hidden px-3 pb-3 transition-opacity duration-200 ${rightVisible ? "opacity-100" : "opacity-0"}`}>
<div className="flex items-center justify-between py-3 shrink-0">
<p className="text-xs font-medium text-gray-700">
Workflow Prompt
</p>
<button
onClick={() => setSelected(null)}
className="rounded-lg p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<ChevronLeft className="h-3.5 w-3.5" />
</button>
</div>
<div className="flex-1 overflow-y-auto px-4 py-3 text-sm border border-gray-200 rounded-md text-gray-600 leading-relaxed font-serif bg-gray-50">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
h1: ({ children }) => (
<h1 className="text-base font-semibold text-gray-900 mt-4 mb-1 first:mt-0">
{children}
</h1>
),
h2: ({ children }) => (
<h2 className="text-sm font-semibold text-gray-900 mt-3 mb-1 first:mt-0">
{children}
</h2>
),
h3: ({ children }) => (
<h3 className="text-xs font-semibold text-gray-900 mt-2 mb-0.5 first:mt-0">
{children}
</h3>
),
p: ({ children }) => (
<p className="mb-2 last:mb-0">
{children}
</p>
),
ul: ({ children }) => (
<ul className="list-disc pl-4 mb-2 space-y-0.5">
{children}
</ul>
),
ol: ({ children }) => (
<ol className="list-decimal pl-4 mb-2 space-y-0.5">
{children}
</ol>
),
li: ({ children }) => (
<li>{children}</li>
),
strong: ({ children }) => (
<strong className="font-semibold text-gray-800">
{children}
</strong>
),
em: ({ children }) => (
<em className="italic">
{children}
</em>
),
}}
>
{selected.prompt_md ??
"_No prompt defined._"}
</ReactMarkdown>
</div>
</div>
)}
</div>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-end gap-2 shrink-0">
<button
type="button"
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
type="button"
onClick={handleUse}
disabled={!selected}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
Use
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,326 @@
"use client";
import {
useState,
useCallback,
useRef,
forwardRef,
useImperativeHandle,
} from "react";
import {
ArrowRight,
Check,
File,
FileText,
FolderOpen,
Library,
Square,
X,
} from "lucide-react";
import { AddDocButton } from "./AddDocButton";
import { AddDocumentsModal } from "../shared/AddDocumentsModal";
import { AssistantWorkflowModal } from "./AssistantWorkflowModal";
import { ApiKeyMissingModal } from "../shared/ApiKeyMissingModal";
import { ModelToggle } from "./ModelToggle";
import { useSelectedModel } from "@/app/hooks/useSelectedModel";
import { useUserProfile } from "@/contexts/UserProfileContext";
import {
getModelProvider,
isModelAvailable,
type ModelProvider,
} from "@/app/lib/modelAvailability";
import type { MikeDocument, MikeMessage } from "../shared/types";
export interface ChatInputHandle {
addDoc: (doc: MikeDocument) => void;
}
interface Props {
onSubmit: (message: MikeMessage) => void;
onCancel: () => void;
isLoading: boolean;
hideAddDocButton?: boolean;
hideWorkflowButton?: boolean;
onProjectsClick?: () => void;
projectName?: string;
projectCmNumber?: string | null;
}
export const ChatInput = forwardRef<ChatInputHandle, Props>(function ChatInput(
{
onSubmit,
onCancel,
isLoading,
hideAddDocButton,
hideWorkflowButton,
onProjectsClick,
projectName,
projectCmNumber,
}: Props,
ref,
) {
const [value, setValue] = useState("");
const [attachedDocs, setAttachedDocs] = useState<MikeDocument[]>([]);
const [selectedWorkflow, setSelectedWorkflow] = useState<{
id: string;
title: string;
} | null>(null);
const [model, setModel] = useSelectedModel();
const { profile } = useUserProfile();
const apiKeys = {
claudeApiKey: profile?.claudeApiKey ?? null,
geminiApiKey: profile?.geminiApiKey ?? null,
};
const textareaRef = useRef<HTMLTextAreaElement>(null);
const [docSelectorOpen, setDocSelectorOpen] = useState(false);
const [workflowModalOpen, setWorkflowModalOpen] = useState(false);
const [apiKeyModalProvider, setApiKeyModalProvider] =
useState<ModelProvider | null>(null);
useImperativeHandle(ref, () => ({
addDoc: (doc: MikeDocument) => {
setAttachedDocs((prev) => {
if (prev.some((d) => d.id === doc.id)) return prev;
return [...prev, doc];
});
},
}));
const handleAddDocFromProject = useCallback((doc: MikeDocument) => {
setAttachedDocs((prev) => {
if (prev.some((d) => d.id === doc.id)) return prev;
return [...prev, doc];
});
}, []);
const handleAddDocsFromSelector = useCallback(
(selectedDocs: MikeDocument[]) => {
setAttachedDocs((prev) => {
const existing = new Set(prev.map((d) => d.id));
return [
...prev,
...selectedDocs.filter((d) => !existing.has(d.id)),
];
});
},
[],
);
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setValue(e.target.value);
const el = e.target;
el.style.height = "auto";
el.style.height = `${el.scrollHeight}px`;
};
const handleSubmit = () => {
const query = value.trim();
if (!query || isLoading) return;
if (!isModelAvailable(model, apiKeys)) {
setApiKeyModalProvider(getModelProvider(model));
return;
}
setValue("");
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
}
const files = attachedDocs.map((d) => ({
filename: d.filename,
document_id: d.id,
}));
setAttachedDocs([]);
const wf = selectedWorkflow;
setSelectedWorkflow(null);
onSubmit?.({
role: "user",
content: query,
files: files.length > 0 ? files : undefined,
workflow: wf ?? undefined,
model,
});
};
const handleActionClick = () => {
if (isLoading) {
onCancel();
} else {
handleSubmit();
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSubmit();
}
};
return (
<>
<div className="w-full">
<div className="border border-gray-300 rounded-[16px] md:rounded-[20px] bg-white">
{/* Attached chips */}
{(selectedWorkflow || attachedDocs.length > 0) && (
<div className="flex flex-wrap gap-1.5 px-2 pt-2">
{selectedWorkflow && (
<div className="inline-flex items-center gap-1 pl-2.5 pr-1 py-0.5 rounded-full text-xs bg-blue-600 text-white border border-white/20 shadow backdrop-blur-sm">
<Library className="h-2.5 w-2.5 shrink-0" />
<span className="max-w-[140px] truncate">
{selectedWorkflow.title}
</span>
<button
type="button"
onClick={() =>
setSelectedWorkflow(null)
}
className="rounded-full p-0.5 ml-0.5 text-white/60 hover:text-white hover:bg-white/20 transition-colors"
>
<X className="h-2.5 w-2.5" />
</button>
</div>
)}
{attachedDocs.map((doc) => {
const ft = doc.file_type?.toLowerCase();
const isPdf = ft === "pdf";
return (
<div
key={doc.id}
className="inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded-full text-xs text-white shadow border border-white/20 bg-black backdrop-blur-sm"
>
{isPdf ? (
<FileText className="h-2.5 w-2.5 shrink-0 text-red-400" />
) : (
<File className="h-2.5 w-2.5 shrink-0 text-blue-400" />
)}
<span className="max-w-[140px] truncate">
{doc.filename}
</span>
<button
type="button"
onClick={() =>
setAttachedDocs((prev) =>
prev.filter(
(d) => d.id !== doc.id,
),
)
}
className="rounded-full p-0.5 ml-0.5 text-white/60 hover:text-white hover:bg-white/20 transition-colors"
>
<X className="h-2.5 w-2.5" />
</button>
</div>
);
})}
</div>
)}
{/* Input */}
<div className="px-4 pt-4">
<textarea
ref={textareaRef}
rows={1}
placeholder="Ask a question about your documents..."
value={value}
onChange={handleChange}
onKeyDown={handleKeyDown}
className="w-full resize-none text-sm overflow-hidden border-0 text-base p-0 bg-transparent outline-none placeholder:text-gray-400 leading-6 max-h-48"
/>
</div>
{/* Controls */}
<div className="flex items-center justify-between md:p-2.5 p-2">
<div className="flex items-center gap-1">
{!hideAddDocButton && (
<AddDocButton
onSelectDoc={handleAddDocFromProject}
onBrowseAll={() => setDocSelectorOpen(true)}
selectedDocIds={attachedDocs.map(
(d) => d.id,
)}
/>
)}
{onProjectsClick && (
<button
type="button"
onClick={onProjectsClick}
aria-label="Open projects"
className="flex items-center gap-1.5 rounded-lg px-2 h-8 text-sm text-gray-400 hover:bg-gray-100 hover:text-gray-700 transition-colors"
>
<FolderOpen className="h-3.5 w-3.5" />
<span className="hidden sm:inline">
Projects
</span>
</button>
)}
{!hideWorkflowButton && (
<button
type="button"
onClick={() => setWorkflowModalOpen(true)}
aria-label="Open workflows"
className={`flex items-center gap-1.5 rounded-lg px-2 h-8 text-sm transition-colors ${selectedWorkflow ? "text-blue-600 hover:bg-blue-50" : "text-gray-400 hover:bg-gray-100 hover:text-gray-700"}`}
>
{selectedWorkflow ? (
<Check className="h-3.5 w-3.5" />
) : (
<Library className="h-3.5 w-3.5" />
)}
<span className="hidden sm:inline">
Workflows
</span>
</button>
)}
</div>
<div className="flex items-center gap-1">
<ModelToggle
value={model}
onChange={setModel}
apiKeys={apiKeys}
/>
<button
type="button"
className="relative bg-gradient-to-b from-neutral-700 to-black text-white rounded-[10px] h-8 w-8 flex items-center justify-center cursor-pointer disabled:cursor-default disabled:from-neutral-600 disabled:to-black backdrop-blur-xl border border-white/30 active:enabled:scale-95 transition-all duration-150"
onClick={handleActionClick}
disabled={!isLoading && !value.trim()}
>
{isLoading ? (
<Square
className="h-4 w-4"
fill="currentColor"
strokeWidth={0}
/>
) : (
<ArrowRight className="h-4 w-4" />
)}
</button>
</div>
</div>
</div>
</div>
<AddDocumentsModal
open={docSelectorOpen}
onClose={() => setDocSelectorOpen(false)}
onSelect={handleAddDocsFromSelector}
breadcrumb={["Assistant", "Add Documents"]}
/>
<AssistantWorkflowModal
open={workflowModalOpen}
onClose={() => setWorkflowModalOpen(false)}
onSelect={(wf) => {
setSelectedWorkflow({ id: wf.id, title: wf.title });
setWorkflowModalOpen(false);
}}
projectName={projectName}
projectCmNumber={projectCmNumber}
/>
<ApiKeyMissingModal
open={apiKeyModalProvider !== null}
provider={apiKeyModalProvider}
onClose={() => setApiKeyModalProvider(null)}
/>
</>
);
});

View file

@ -0,0 +1,627 @@
"use client";
import { useCallback, useState, useRef, useEffect } from "react";
import { ArrowDown } from "lucide-react";
import { UserMessage } from "./UserMessage";
import { AssistantMessage } from "./AssistantMessage";
import { ChatInput } from "./ChatInput";
import {
AssistantSidePanel,
type AssistantSidePanelTab,
} from "./AssistantSidePanel";
import { AssistantWorkflowModal } from "./AssistantWorkflowModal";
import type {
MikeCitationAnnotation,
MikeEditAnnotation,
MikeMessage,
} from "../shared/types";
import { useSidebar } from "@/app/contexts/SidebarContext";
import { invalidateDocxBytes } from "@/app/hooks/useFetchDocxBytes";
interface Props {
messages: MikeMessage[];
isResponseLoading: boolean;
handleChat: (message: MikeMessage) => Promise<string | null>;
cancel: () => void;
}
export function ChatView({
messages,
isResponseLoading,
handleChat,
cancel,
}: Props) {
const [tabs, setTabs] = useState<AssistantSidePanelTab[]>([]);
const [activeTabId, setActiveTabId] = useState<string | null>(null);
const [panelMounted, setPanelMounted] = useState(false);
const [panelVisible, setPanelVisible] = useState(false);
const [workflowModalOpen, setWorkflowModalOpen] = useState(false);
const [workflowModalInitialId, setWorkflowModalInitialId] = useState<
string | undefined
>();
const [reloadingDocIds, setReloadingDocIds] = useState<Set<string>>(
() => new Set(),
);
// Per-edit in-flight set — disables Accept/Reject on only the one
// edit currently being resolved, so sibling edits in the same message
// (and their twins in DocPanel) stay clickable.
const [reloadingEditIds, setReloadingEditIds] = useState<Set<string>>(
() => new Set(),
);
const { setSidebarOpen } = useSidebar();
const showPanel = useCallback(() => {
setPanelMounted(true);
setSidebarOpen(false);
requestAnimationFrame(() =>
requestAnimationFrame(() => setPanelVisible(true)),
);
}, [setSidebarOpen]);
const closeAllTabs = useCallback(() => {
setPanelVisible(false);
setTimeout(() => {
setTabs([]);
setActiveTabId(null);
setPanelMounted(false);
setSidebarOpen(true);
}, 300);
}, [setSidebarOpen]);
const closeTab = useCallback(
(id: string) => {
setTabs((prev) => {
const next = prev.filter((t) => t.id !== id);
if (next.length === 0) {
setPanelVisible(false);
setTimeout(() => {
setActiveTabId(null);
setPanelMounted(false);
setSidebarOpen(true);
}, 300);
return next;
}
if (activeTabId === id) {
const idx = prev.findIndex((t) => t.id === id);
const neighbour = next[idx] ?? next[idx - 1] ?? next[0];
setActiveTabId(neighbour?.id ?? null);
}
return next;
});
},
[activeTabId, setSidebarOpen],
);
/**
* One tab per document. If a tab for `tab.documentId` already exists,
* the panel stays mounted and only the header-relevant fields swap
* (kind, citation/edit, version, filename). Per-tab UI state the
* dismissable warning and the saved scroll position is preserved
* so switching headers doesn't blow away viewer state. If no tab
* exists for the document, a new one is appended.
*/
const upsertTab = useCallback(
(tab: AssistantSidePanelTab) => {
setTabs((prev) => {
const idx = prev.findIndex(
(t) => t.documentId === tab.documentId,
);
if (idx >= 0) {
const existing = prev[idx];
const copy = prev.slice();
copy[idx] = {
...tab,
id: existing.id,
warning: existing.warning,
initialScrollTop: existing.initialScrollTop,
};
return copy;
}
return [...prev, tab];
});
setActiveTabId(tab.id);
showPanel();
},
[showPanel],
);
/**
* Open a tab showing a single citation quote. Called from
* AssistantMessage when the user clicks a numbered citation pill.
*/
const openCitation = useCallback(
(citation: MikeCitationAnnotation) => {
upsertTab({
kind: "citation",
id: citation.document_id,
documentId: citation.document_id,
filename: citation.filename,
versionId: citation.version_id ?? null,
versionNumber: citation.version_number ?? null,
citation,
});
},
[upsertTab],
);
/**
* Open a tab showing a single tracked change. Called from
* AssistantMessage when the user clicks an EditCard's View button.
*/
const openEditor = useCallback(
(ann: MikeEditAnnotation, filename: string) => {
upsertTab({
kind: "edit",
id: ann.document_id,
documentId: ann.document_id,
filename,
versionId: ann.version_id ?? null,
versionNumber: ann.version_number ?? null,
edit: ann,
});
},
[upsertTab],
);
/**
* Open a tab showing a document without targeting a specific
* citation/edit used by the download-card click.
*/
const openDocument = useCallback(
(args: {
documentId: string;
filename: string;
versionId: string | null;
versionNumber: number | null;
}) => {
upsertTab({
kind: "document",
id: args.documentId,
documentId: args.documentId,
filename: args.filename,
versionId: args.versionId,
versionNumber: args.versionNumber,
});
},
[upsertTab],
);
const [resolvedEditStatuses, setResolvedEditStatuses] = useState<
Record<string, "accepted" | "rejected">
>({});
const handleEditResolveStart = useCallback(
(args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => {
setReloadingDocIds((prev) => {
if (prev.has(args.documentId)) return prev;
const next = new Set(prev);
next.add(args.documentId);
return next;
});
setReloadingEditIds((prev) => {
if (prev.has(args.editId)) return prev;
const next = new Set(prev);
next.add(args.editId);
return next;
});
},
[],
);
const handleEditResolved = useCallback(
(args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => {
setResolvedEditStatuses((prev) => ({
...prev,
[args.editId]: args.status,
}));
setReloadingDocIds((prev) => {
if (!prev.has(args.documentId)) return prev;
const next = new Set(prev);
next.delete(args.documentId);
return next;
});
setReloadingEditIds((prev) => {
if (!prev.has(args.editId)) return prev;
const next = new Set(prev);
next.delete(args.editId);
return next;
});
// Propagate the new status onto any open edit-tab for this
// edit so DocPanel's Accept/Reject buttons flip and disable
// (their sync effect keys off edit.status). Without this, a
// resolve triggered from the inline EditCard or BulkEditActions
// leaves the panel buttons looking live.
setTabs((prev) =>
prev.map((t) =>
t.kind === "edit" && t.edit.edit_id === args.editId
? {
...t,
edit: { ...t.edit, status: args.status },
}
: t,
),
);
// Accept/reject mutates bytes for this document's current
// version; drop the cache so the next DocxView render (or an
// explicit re-open) fetches the fresh file.
invalidateDocxBytes(args.documentId);
},
[],
);
const patchTab = useCallback(
(
tabId: string,
patch: Partial<Pick<AssistantSidePanelTab, "warning" | "initialScrollTop">>,
) => {
setTabs((prev) => {
const idx = prev.findIndex((t) => t.id === tabId);
if (idx < 0) return prev;
const copy = prev.slice();
copy[idx] = { ...copy[idx], ...patch };
return copy;
});
},
[],
);
const handleEditError = useCallback(
(args: {
editId?: string;
documentId: string;
versionId?: string | null;
message: string;
}) => {
// Surface the warning on every tab tied to this document.
setTabs((prev) =>
prev.map((t) =>
t.documentId === args.documentId
? { ...t, warning: args.message }
: t,
),
);
setReloadingDocIds((prev) => {
if (!prev.has(args.documentId)) return prev;
const next = new Set(prev);
next.delete(args.documentId);
return next;
});
if (args.editId) {
setReloadingEditIds((prev) => {
if (!prev.has(args.editId!)) return prev;
const next = new Set(prev);
next.delete(args.editId!);
return next;
});
}
},
[],
);
const handleWarningDismiss = useCallback(
(tabId: string) => {
patchTab(tabId, { warning: null });
},
[patchTab],
);
const handleScrollChange = useCallback(
(tabId: string, scrollTop: number) => {
patchTab(tabId, { initialScrollTop: scrollTop });
},
[patchTab],
);
const messagesContainerRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const latestUserMessageRef = useRef<HTMLDivElement>(null);
const chatInputRef = useRef<HTMLDivElement>(null);
const hasScrolledRef = useRef(false);
const [messagesVisible, setMessagesVisible] = useState(false);
const [showScrollButton, setShowScrollButton] = useState(false);
const [inputHeight, setInputHeight] = useState(0);
const [minHeight, setMinHeight] = useState("0px");
useEffect(() => {
const el = chatInputRef.current;
if (!el) return;
const observer = new ResizeObserver(() =>
setInputHeight(el.offsetHeight),
);
observer.observe(el);
setInputHeight(el.offsetHeight);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (latestUserMessageRef.current) {
const headerHeight = window.innerWidth < 768 ? 56 : 0;
const gap = window.innerWidth < 768 ? 16 : 24;
const paddingBottom = 128;
const marginBottom = 48;
const userMessageHeight = latestUserMessageRef.current.offsetHeight;
setMinHeight(
`calc(100dvh - ${headerHeight + gap + userMessageHeight + paddingBottom + marginBottom}px)`,
);
}
}, [messages.length, latestUserMessageRef.current]); // eslint-disable-line react-hooks/exhaustive-deps
const updateScrollButton = useCallback(() => {
const c = messagesContainerRef.current;
if (!c) return;
const isScrolledUp = c.scrollHeight - c.scrollTop - c.clientHeight > 10;
setShowScrollButton(isScrolledUp && c.scrollHeight > c.clientHeight);
}, []);
useEffect(() => {
const c = messagesContainerRef.current;
if (!c) return;
c.addEventListener("scroll", updateScrollButton);
updateScrollButton();
return () => c.removeEventListener("scroll", updateScrollButton);
}, [messages, updateScrollButton]);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
const scrollLatestUserToTop = useCallback(() => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const container = messagesContainerRef.current;
const element = latestUserMessageRef.current;
if (!container || !element) return;
container.scrollTo({
top: element.offsetTop - 24,
behavior: "smooth",
});
});
});
}, []);
useEffect(() => {
const last = messages[messages.length - 1];
if (last?.role === "user") scrollLatestUserToTop();
}, [messages, scrollLatestUserToTop]);
useEffect(() => {
if (isResponseLoading) scrollLatestUserToTop();
}, [isResponseLoading, scrollLatestUserToTop]);
useEffect(() => {
if (messages.length === 0) {
hasScrolledRef.current = false;
setMessagesVisible(false);
} else if (!hasScrolledRef.current) {
const userMsgCount = messages.filter(
(m) => m.role === "user",
).length;
if (
userMsgCount >= 2 &&
latestUserMessageRef.current &&
messagesContainerRef.current
) {
setTimeout(() => {
const container = messagesContainerRef.current;
const element = latestUserMessageRef.current;
if (container && element) {
container.scrollTo({
top: element.offsetTop - 24,
behavior: "instant",
});
}
hasScrolledRef.current = true;
setMessagesVisible(true);
}, 100);
} else {
hasScrolledRef.current = true;
setMessagesVisible(true);
}
}
}, [messages]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (panelMounted && window.innerWidth < 768) {
document.body.style.overflow = "hidden";
} else {
document.body.style.overflow = "unset";
}
return () => {
document.body.style.overflow = "unset";
};
}, [panelMounted]);
return (
<div className="h-full w-full flex relative">
{/* Chat column */}
<div className="flex flex-col h-full flex-1 relative">
{/* Scrollable messages */}
<div
ref={messagesContainerRef}
className="flex-1 w-full overflow-y-auto"
style={{ scrollbarGutter: "stable both-edges" }}
>
<div className="w-full max-w-4xl mx-auto pb-32 px-6 md:px-8 pt-4 md:pt-6 min-h-full flex flex-col relative">
{!messagesVisible && (
<div className="space-y-6 w-full">
<div className="flex justify-end">
<div className="bg-gray-100 rounded-2xl p-4 w-2/5">
<div className="h-4 bg-gradient-to-r from-gray-200 via-gray-300 to-gray-200 bg-[length:200%_100%] animate-[shimmer_2s_ease-in-out_infinite] rounded w-full" />
</div>
</div>
<div className="space-y-3">
{[1, 2, 3, 4].map((i) => (
<div
key={i}
className={`h-4 bg-gradient-to-r from-gray-200 via-gray-300 to-gray-200 bg-[length:200%_100%] animate-[shimmer_2s_ease-in-out_infinite] rounded ${i === 3 ? "w-5/6" : i === 4 ? "w-4/6" : "w-full"}`}
/>
))}
</div>
</div>
)}
<div
className="space-y-6 transition-opacity duration-150"
style={{ opacity: messagesVisible ? 1 : 0 }}
>
{(() => {
const lastUserIndex = messages
.map((m) => m.role)
.lastIndexOf("user");
const lastAssistantIndex = messages
.map((m) => m.role)
.lastIndexOf("assistant");
return messages.map((msg, i) => (
<div
key={i}
ref={
i === lastUserIndex
? latestUserMessageRef
: null
}
>
{msg.role === "user" ? (
<UserMessage
content={msg.content ?? ""}
files={(msg as any).files}
workflow={(msg as any).workflow}
/>
) : (
<AssistantMessage
content={msg.content ?? ""}
events={msg.events}
isStreaming={
i === messages.length - 1 &&
isResponseLoading
}
isError={!!(msg as any).error}
errorMessage={
typeof (msg as any).error ===
"string"
? (msg as any).error
: undefined
}
annotations={msg.annotations}
onCitationClick={openCitation}
minHeight={
i === lastAssistantIndex
? minHeight
: "0px"
}
onWorkflowClick={(id) => {
setWorkflowModalInitialId(
id,
);
setWorkflowModalOpen(true);
}}
onEditViewClick={openEditor}
onOpenDocument={openDocument}
onEditResolveStart={
handleEditResolveStart
}
onEditResolved={
handleEditResolved
}
onEditError={handleEditError}
isDocReloading={(docId) =>
reloadingDocIds.has(docId)
}
isEditReloading={(editId) =>
reloadingEditIds.has(editId)
}
resolvedEditStatuses={
resolvedEditStatuses
}
/>
)}
</div>
));
})()}
<div ref={messagesEndRef} />
</div>
</div>
</div>
{/* Scroll to bottom button */}
{showScrollButton && (
<div
className="absolute left-1/2 -translate-x-1/2 z-19"
style={{ bottom: inputHeight + 12 }}
>
<button
onClick={scrollToBottom}
className="p-2 rounded-full bg-white/70 backdrop-blur-xs shadow-lg cursor-pointer border border-gray-300"
>
<ArrowDown className="h-6 w-6 text-gray-500" />
</button>
</div>
)}
{/* Chat input */}
<div
ref={chatInputRef}
className="absolute bottom-0 left-0 right-0 w-full z-30"
>
<div className="w-full max-w-4xl mx-auto px-4 md:px-6">
<div className="w-full rounded-t-[20px] bg-white">
<ChatInput
onSubmit={handleChat}
onCancel={cancel}
isLoading={isResponseLoading}
/>
<div className="py-3 text-center">
<p className="text-xs text-gray-500">
AI can make mistakes. Answers are not legal
advice.
</p>
</div>
</div>
</div>
</div>
</div>
<AssistantWorkflowModal
open={workflowModalOpen}
onClose={() => setWorkflowModalOpen(false)}
onSelect={() => setWorkflowModalOpen(false)}
initialWorkflowId={workflowModalInitialId}
/>
{panelMounted && (
<div
className={`fixed md:relative inset-0 md:inset-auto md:h-full md:flex-shrink-0 z-40 md:z-auto transition-transform duration-300 ease-in-out ${panelVisible ? "translate-x-0" : "translate-x-full"}`}
>
<AssistantSidePanel
tabs={tabs}
activeTabId={activeTabId}
onActivateTab={setActiveTabId}
onCloseTab={closeTab}
onCloseAll={closeAllTabs}
isEditorReloading={(documentId) =>
reloadingDocIds.has(documentId)
}
isEditReloading={(editId) =>
reloadingEditIds.has(editId)
}
onEditResolveStart={handleEditResolveStart}
onEditResolved={handleEditResolved}
onEditError={handleEditError}
onWarningDismiss={handleWarningDismiss}
onScrollChange={handleScrollChange}
/>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,348 @@
"use client";
import { useState } from "react";
import { supabase } from "@/lib/supabase";
import type { MikeEditAnnotation } from "../shared/types";
function normalizeText(s: string) {
return s.replace(/\s+/g, " ").trim();
}
function findMatch(
container: Element,
tag: "ins" | "del",
opts: { w_id?: string | null; text?: string },
): HTMLElement | null {
if (opts.w_id) {
// Values are numeric strings from our own backend — CSS.escape
// makes them hex-encoded which works but is harder to debug.
const byId = container.querySelector(
`${tag}[data-w-id="${opts.w_id}"]`,
) as HTMLElement | null;
console.log("[EditCard] findMatch by w_id", {
tag,
w_id: opts.w_id,
found: !!byId,
totalTagged: container.querySelectorAll(`${tag}[data-w-id]`).length,
totalAny: container.querySelectorAll(tag).length,
});
if (byId) return byId;
}
const text = opts.text ?? "";
const target = normalizeText(text);
if (!target) return null;
const candidates = Array.from(
container.querySelectorAll(tag),
) as HTMLElement[];
const byText =
candidates.find(
(el) => normalizeText(el.textContent ?? "") === target,
) ??
candidates.find((el) =>
normalizeText(el.textContent ?? "").includes(target),
) ??
null;
console.log("[EditCard] findMatch by text", {
tag,
target,
found: !!byText,
candidateCount: candidates.length,
});
return byText;
}
/**
* Ephemeral DOM mutation so the tracked change visually resolves the
* instant the user clicks Accept/Reject, instead of waiting for the
* backend round-trip + re-render. The real re-render from the new
* version supersedes this shortly after.
*/
/**
* Apply the optimistic DOM mutation for an accept/reject click. Returns
* a revert function that undoes every style + class the mutation added,
* so if the backend call later fails we can restore the original look.
*/
export function applyOptimisticResolution(
annotation: MikeEditAnnotation,
verb: "accept" | "reject",
): () => void {
const reverts: (() => void)[] = [];
if (typeof document === "undefined") return () => {};
const hide = (el: HTMLElement) => {
el.classList.add("docx-edit-hidden");
const prev = el.style.getPropertyValue("display");
const prevPriority = el.style.getPropertyPriority("display");
el.style.setProperty("display", "none", "important");
reverts.push(() => {
el.classList.remove("docx-edit-hidden");
if (prev) el.style.setProperty("display", prev, prevPriority);
else el.style.removeProperty("display");
});
};
const keep = (el: HTMLElement) => {
el.classList.add("docx-edit-kept");
const snapshot = {
color: [
el.style.getPropertyValue("color"),
el.style.getPropertyPriority("color"),
] as const,
bg: [
el.style.getPropertyValue("background-color"),
el.style.getPropertyPriority("background-color"),
] as const,
td: [
el.style.getPropertyValue("text-decoration"),
el.style.getPropertyPriority("text-decoration"),
] as const,
};
el.style.setProperty("color", "inherit", "important");
el.style.setProperty("background-color", "transparent", "important");
el.style.setProperty("text-decoration", "none", "important");
reverts.push(() => {
el.classList.remove("docx-edit-kept");
const restore = (
prop: "color" | "background-color" | "text-decoration",
[v, p]: readonly [string, string],
) => {
if (v) el.style.setProperty(prop, v, p);
else el.style.removeProperty(prop);
};
restore("color", snapshot.color);
restore("background-color", snapshot.bg);
restore("text-decoration", snapshot.td);
});
};
const scrolls = document.querySelectorAll(
`[data-document-id="${CSS.escape(annotation.document_id)}"]`,
);
console.log("[EditCard] optimistic scrolls found:", scrolls.length, {
document_id: annotation.document_id,
ins_w_id: annotation.ins_w_id,
del_w_id: annotation.del_w_id,
inserted_text: annotation.inserted_text?.slice(0, 40),
deleted_text: annotation.deleted_text?.slice(0, 40),
});
scrolls.forEach((scroll) => {
const container = scroll.querySelector(".docx-view-container");
if (!container) return;
const insEl = findMatch(container, "ins", {
w_id: annotation.ins_w_id,
text: annotation.inserted_text,
});
const delEl = findMatch(container, "del", {
w_id: annotation.del_w_id,
text: annotation.deleted_text,
});
if (verb === "accept") {
if (insEl) keep(insEl);
if (delEl) hide(delEl);
} else {
if (insEl) hide(insEl);
if (delEl) keep(delEl);
}
});
return () => reverts.forEach((fn) => fn());
}
interface Props {
annotation: MikeEditAnnotation;
/**
* External override for this edit's status. When set, takes
* precedence over the annotation's DB status and the card's own
* internal state used so bulk-resolved edits flip their per-card
* UI the moment the bulk handler calls onResolved.
*/
resolvedStatus?: "accepted" | "rejected";
/**
* True while an accept/reject request for any edit on this document
* is in flight (from here, DocPanel, or the bulk bar). When true the
* Accept/Reject buttons disable so the user can't race resolutions.
*/
isReloading?: boolean;
onViewClick?: (ann: MikeEditAnnotation) => void;
/**
* Fires immediately when the user clicks Accept or Reject, before the
* backend round-trip. Parents use this to show an in-progress spinner
* on download cards / editor panels tied to the same document while
* the version is being mutated.
*/
onResolveStart?: (args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => void;
onResolved?: (args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => void;
/**
* Fires when the backend accept/reject call fails. The optimistic
* DOM mutation has already been reverted. Parent should surface a
* warning (e.g. on the DocxView for this document + version) and
* clear the per-edit in-flight state keyed on `editId`.
*/
onError?: (args: {
editId: string;
documentId: string;
versionId: string | null;
message: string;
}) => void;
}
/**
* Renders a single tracked-change proposal as a card in the assistant
* message with Accept / Reject / View controls.
*/
export function EditCard({
annotation,
resolvedStatus,
isReloading,
onViewClick,
onResolveStart,
onResolved,
onError,
}: Props) {
const [busy, setBusy] = useState(false);
const [localStatus, setLocalStatus] = useState<
"pending" | "accepted" | "rejected"
>(annotation.status);
// External override (from a bulk resolve) takes precedence over the
// card's own click-driven state.
const status = resolvedStatus ?? localStatus;
const setStatus = setLocalStatus;
const resolved = status !== "pending";
// True while an accept/reject request for any edit on this card's
// document is in flight — triggered here, in DocPanel, or in the
// bulk bar. Disables the buttons so the user can't race resolutions.
const inFlight = busy || !!isReloading;
const handle = async (verb: "accept" | "reject") => {
if (busy || resolved) return;
setBusy(true);
onResolveStart?.({
editId: annotation.edit_id,
documentId: annotation.document_id,
verb,
});
let revert: (() => void) | null = null;
try {
revert = applyOptimisticResolution(annotation, verb);
} catch (e) {
console.error("[EditCard] optimistic update threw", e);
}
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3001";
const resp = await fetch(
`${apiBase}/single-documents/${annotation.document_id}/edits/${annotation.edit_id}/${verb}`,
{
method: "POST",
headers: token
? { Authorization: `Bearer ${token}` }
: undefined,
},
);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = (await resp.json()) as {
ok: boolean;
already_resolved?: boolean;
status?: "accepted" | "rejected";
version_id: string | null;
download_url: string | null;
};
const nextStatus =
data.status ?? (verb === "accept" ? "accepted" : "rejected");
setStatus(nextStatus);
onResolved?.({
editId: annotation.edit_id,
documentId: annotation.document_id,
status: nextStatus,
versionId: data.version_id,
downloadUrl: data.download_url,
});
} catch (e) {
console.error("EditCard resolve failed", e);
try {
revert?.();
} catch (revertErr) {
console.error("[EditCard] revert threw", revertErr);
}
onError?.({
editId: annotation.edit_id,
documentId: annotation.document_id,
versionId: annotation.version_id ?? null,
message:
verb === "accept"
? "Couldn't save accept — reverted."
: "Couldn't save reject — reverted.",
});
} finally {
setBusy(false);
}
};
return (
<div className="border border-gray-200 rounded-lg p-3 bg-gray-50">
{annotation.reason && (
<p className="text-xs text-gray-500 mb-2">
{annotation.reason}
</p>
)}
<div className="text-sm leading-relaxed font-serif bg-white border border-gray-200 rounded-md px-2 py-2">
{annotation.inserted_text && (
<span className="text-green-700">
{annotation.inserted_text}
</span>
)}
{annotation.deleted_text && (
<span className="text-red-600 line-through">
{annotation.deleted_text}
</span>
)}
</div>
<div className="flex gap-2 mt-3">
<button
onClick={() => handle("accept")}
disabled={inFlight || resolved}
className="px-2 py-1 text-xs rounded border border-gray-900 bg-gray-900 text-white hover:bg-gray-800 disabled:opacity-50"
>
{status === "accepted" ? "Accepted" : "Accept"}
</button>
<button
onClick={() => handle("reject")}
disabled={inFlight || resolved}
className="px-2 py-1 text-xs rounded border border-gray-200 bg-white text-gray-700 hover:bg-gray-100 disabled:opacity-50"
>
{status === "rejected" ? "Rejected" : "Reject"}
</button>
{onViewClick && (
<button
onClick={() => onViewClick(annotation)}
disabled={resolved}
title={
resolved
? "This change has been resolved and is no longer in the document."
: undefined
}
className="ml-auto px-2 py-1 text-xs rounded border border-gray-200 bg-white text-gray-700 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-white"
>
View
</button>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,99 @@
"use client";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { MikeIcon } from "@/components/chat/mike-icon";
import { ChatInput } from "./ChatInput";
import { SelectAssistantProjectModal } from "./SelectAssistantProjectModal";
import type { MikeMessage } from "../shared/types";
interface InitialViewProps {
onSubmit: (message: MikeMessage) => void;
}
const ICON_SIZE = 35;
const GAP = 16; // gap-4 = 1rem = 16px
export function InitialView({ onSubmit }: InitialViewProps) {
const { user } = useAuth();
const { profile } = useUserProfile();
const [loaded, setLoaded] = useState(false);
const [projectModalOpen, setProjectModalOpen] = useState(false);
const [iconOffset, setIconOffset] = useState(0);
const [textOffset, setTextOffset] = useState(0);
const textRef = useRef<HTMLHeadingElement>(null);
const username =
profile?.displayName?.trim() || user?.email?.split("@")[0] || "there";
useLayoutEffect(() => {
if (!profile || !textRef.current) return;
const h1Width = textRef.current.offsetWidth;
setIconOffset((h1Width + GAP) / 2);
setTextOffset((ICON_SIZE + GAP) / 2);
}, [profile]);
useEffect(() => {
if (!iconOffset) return;
const t = setTimeout(() => setLoaded(true), 100);
return () => clearTimeout(t);
}, [iconOffset]);
return (
<div className="flex flex-col h-full w-full px-6">
<div className="flex-1 flex flex-col items-center justify-center">
<div className="flex-col items-center w-full max-w-4xl relative px-0 xl:px-8">
<div className="mb-10 relative flex items-center justify-center">
<div
className="absolute h-[35px]"
style={{
left: "50%",
transform: loaded
? `translateX(calc(-50% - ${iconOffset}px))`
: "translateX(-50%)",
transition:
"transform 900ms cubic-bezier(0.25, 0.46, 0.45, 0.94)",
}}
>
<MikeIcon size={ICON_SIZE} />
</div>
<h1
ref={textRef}
className="absolute text-4xl font-serif font-light text-gray-900 whitespace-nowrap"
style={{
left: "50%",
transform: loaded
? `translateX(calc(-50% + ${textOffset}px))`
: "translateX(-50%)",
opacity: loaded ? 1 : 0,
transition:
"transform 900ms cubic-bezier(0.25, 0.46, 0.45, 0.94), opacity 800ms ease-in-out 300ms",
}}
>
Hi, {username}
</h1>
</div>
<ChatInput
onSubmit={onSubmit}
onCancel={() => {}}
isLoading={false}
onProjectsClick={() => setProjectModalOpen(true)}
/>
<div className="text-center">
<p className="text-xs py-3 mb-3 text-gray-500">
AI can make mistakes. Answers are not legal advice.
</p>
</div>
</div>
</div>
<SelectAssistantProjectModal
open={projectModalOpen}
onClose={() => setProjectModalOpen(false)}
/>
</div>
);
}

View file

@ -0,0 +1,115 @@
"use client";
import { useState } from "react";
import { ChevronDown, Check, AlertCircle } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { isModelAvailable } from "@/app/lib/modelAvailability";
export interface ModelOption {
id: string;
label: string;
group: "Anthropic" | "Google";
}
export const MODELS: ModelOption[] = [
{ id: "claude-opus-4-7", label: "Claude Opus 4.7", group: "Anthropic" },
{ id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6", group: "Anthropic" },
{ id: "gemini-3.1-pro-preview", label: "Gemini 3.1 Pro", group: "Google" },
{ id: "gemini-3-flash-preview", label: "Gemini 3 Flash", group: "Google" },
];
export const DEFAULT_MODEL_ID = "gemini-3-flash-preview";
export const ALLOWED_MODEL_IDS = new Set(MODELS.map((m) => m.id));
const GROUP_ORDER: ModelOption["group"][] = ["Anthropic", "Google"];
interface Props {
value: string;
onChange: (id: string) => void;
apiKeys?: {
claudeApiKey: string | null;
geminiApiKey: string | null;
};
}
export function ModelToggle({ value, onChange, apiKeys }: Props) {
const [isOpen, setIsOpen] = useState(false);
const selected = MODELS.find((m) => m.id === value);
const selectedLabel = selected?.label ?? "Model";
const selectedAvailable = apiKeys
? isModelAvailable(value, apiKeys)
: true;
return (
<DropdownMenu onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<button
type="button"
className={`flex items-center gap-1.5 rounded-lg px-2 h-8 text-sm transition-colors cursor-pointer text-gray-400 hover:bg-gray-100 hover:text-gray-700 ${isOpen ? "bg-gray-100 text-gray-700" : ""}`}
title={
!selectedAvailable
? "API key missing for selected model"
: "Choose model"
}
>
{!selectedAvailable && (
<AlertCircle className="h-3 w-3 shrink-0 text-red-500" />
)}
<span className="max-w-[140px] truncate">{selectedLabel}</span>
<ChevronDown
className={`h-3 w-3 shrink-0 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56 z-50" side="top" align="start">
{GROUP_ORDER.map((group, gi) => {
const items = MODELS.filter((m) => m.group === group);
if (items.length === 0) return null;
return (
<div key={group}>
{gi > 0 && <DropdownMenuSeparator />}
<DropdownMenuLabel className="text-[10px] uppercase tracking-wider text-gray-400">
{group}
</DropdownMenuLabel>
{items.map((m) => {
const available = apiKeys
? isModelAvailable(m.id, apiKeys)
: true;
return (
<DropdownMenuItem
key={m.id}
className="cursor-pointer"
onSelect={() => onChange(m.id)}
>
<span
className={`flex-1 ${available ? "" : "text-gray-400"}`}
>
{m.label}
</span>
{!available && (
<AlertCircle
className="h-3.5 w-3.5 text-red-500 ml-1"
aria-label="API key missing"
/>
)}
{m.id === value && available && (
<Check className="h-3.5 w-3.5 text-gray-600 ml-1" />
)}
</DropdownMenuItem>
);
})}
</div>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}

View file

@ -0,0 +1,92 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { X, Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
import { useDirectoryData } from "../shared/useDirectoryData";
import { ProjectPicker } from "../shared/ProjectPicker";
interface Props {
open: boolean;
onClose: () => void;
}
export function SelectAssistantProjectModal({ open, onClose }: Props) {
const [selectedId, setSelectedId] = useState<string | null>(null);
const [creating, setCreating] = useState(false);
const router = useRouter();
const { saveChat } = useChatHistoryContext();
const { loading, projects } = useDirectoryData(open);
useEffect(() => {
if (!open) return;
setSelectedId(null);
}, [open]);
if (!open) return null;
async function handleContinue() {
if (!selectedId) return;
setCreating(true);
try {
const chatId = await saveChat(selectedId);
if (!chatId) return;
onClose();
router.push(`/projects/${selectedId}/assistant/chat/${chatId}`);
} finally {
setCreating(false);
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Assistant</span>
<span></span>
<span>Start Chat in a Project</span>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
<ProjectPicker
projects={projects}
loading={loading}
selectedId={selectedId}
onSelect={setSelectedId}
/>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-end gap-2">
<button
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleContinue}
disabled={!selectedId || creating}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40"
>
{creating ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
"Continue"
)}
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,47 @@
"use client";
import { File, FileText, Library } from "lucide-react";
interface Props {
content: string;
files?: { filename: string; document_id?: string }[];
workflow?: { id: string; title: string };
}
export function UserMessage({ content, files, workflow }: Props) {
const hasFiles = files && files.length > 0;
return (
<div className="w-full flex justify-end">
<div className="max-w-[80%] bg-gray-100 rounded-xl px-4 py-3">
<p className="text-sm text-gray-900 whitespace-pre-wrap">{content}</p>
{(workflow || hasFiles) && (
<div className="flex flex-wrap justify-end gap-1.5 mt-3">
{workflow && (
<div className="inline-flex items-center gap-1 pl-2 pr-2.5 py-0.5 rounded-full text-xs bg-blue-600 text-white shadow border border-blue-600">
<Library className="h-2.5 w-2.5 shrink-0" />
<span className="max-w-[140px] truncate">{workflow.title}</span>
</div>
)}
{hasFiles && files.map((f, i) => {
const ext = f.filename.split(".").pop()?.toLowerCase();
const isPdf = ext === "pdf";
return (
<div
key={i}
className="inline-flex items-center gap-1 pl-2 pr-2.5 py-0.5 rounded-full text-xs text-white shadow border border-black bg-black"
>
{isPdf
? <FileText className="h-2.5 w-2.5 shrink-0 text-red-400" />
: <File className="h-2.5 w-2.5 shrink-0 text-blue-400" />
}
<span className="max-w-[140px] truncate">{f.filename}</span>
</div>
);
})}
</div>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,81 @@
import { X } from "lucide-react";
import { createPortal } from "react-dom";
interface CreditsExhaustedModalProps {
isOpen: boolean;
onClose: () => void;
resetDate: string;
}
export function CreditsExhaustedModal({
isOpen,
onClose,
resetDate,
}: CreditsExhaustedModalProps) {
if (!isOpen) return null;
// Format the reset date
const formatResetDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString("en-US", {
month: "long",
day: "numeric",
year: "numeric",
});
};
return createPortal(
<>
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/50 z-[200]"
onClick={onClose}
/>
{/* Modal */}
<div className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[201] w-full max-w-md px-4">
<div className="relative bg-white rounded-2xl shadow-2xl p-6">
{/* Header */}
<div className="flex items-start justify-between mb-4">
<h2 className="text-3xl font-light font-eb-garamond text-gray-900">
Message Limit Reached
</h2>
</div>
{/* Content */}
<div className="space-y-4">
<p className="text-gray-600">
You've reached your monthly message limit of 100
messages.
</p>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<p className="text-sm text-blue-900 font-medium mb-1">
Your credits will reset on:
</p>
<p className="text-lg font-semibold text-blue-700">
{formatResetDate(resetDate)}
</p>
</div>
<p className="text-sm text-gray-500">
Your message credits automatically reset on the
first day of each month.
</p>
</div>
{/* Actions */}
<div className="mt-6 flex gap-3">
<button
onClick={onClose}
className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors"
>
Close
</button>
</div>
</div>
</div>
</>,
document.body,
);
}

View file

@ -0,0 +1,97 @@
"use client";
import { Button } from "@/components/ui/button";
import { X, Check } from "lucide-react";
interface DeleteChatsModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
chatCount: number;
isDeleting: boolean;
isSuccess?: boolean;
}
export function DeleteChatsModal({
isOpen,
onClose,
onConfirm,
chatCount,
isDeleting,
isSuccess = false,
}: DeleteChatsModalProps) {
if (!isOpen) return null;
return (
<>
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/50 z-199"
onClick={isDeleting || isSuccess ? undefined : onClose}
/>
{/* Modal */}
<div className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-200 w-full max-w-md">
<div className="bg-white rounded-2xl shadow-2xl p-8">
{isSuccess ? (
<>
{/* Success State */}
<div className="text-center">
<div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4">
<Check className="h-8 w-8 text-green-600" />
</div>
<h2 className="text-3xl font-light font-eb-garamond text-gray-900 mb-2">
All Chats Deleted
</h2>
<p className="text-gray-600 text-sm">
Your chat history has been successfully
deleted.
</p>
</div>
</>
) : (
<>
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-4xl font-light font-eb-garamond text-red-700">
Delete All Chats
</h2>
</div>
{/* Content */}
<div className="space-y-4">
<p className="text-gray-600 text-sm leading-relaxed">
Are you sure you want to delete all{" "}
{chatCount} chat
{chatCount !== 1 ? "s" : ""}? This action is
permanent and cannot be undone.
</p>
<div className="space-y-3 pt-4">
<Button
onClick={onConfirm}
disabled={isDeleting}
variant="destructive"
className="w-full bg-red-600 hover:bg-red-700 text-white"
>
{isDeleting
? "Deleting..."
: "Delete All Chats"}
</Button>
<Button
onClick={onClose}
variant="outline"
disabled={isDeleting}
className="w-full border-gray-300 text-gray-700 hover:bg-gray-50"
>
Cancel
</Button>
</div>
</div>
</>
)}
</div>
</div>
</>
);
}

View file

@ -0,0 +1,90 @@
import { X, Link2, Check } from "lucide-react";
import { useState } from "react";
import { createPortal } from "react-dom";
interface SimpleLinkDialogProps {
isOpen: boolean;
onClose: () => void;
shareUrl: string | null;
}
export function SimpleLinkDialog({
isOpen,
onClose,
shareUrl,
}: SimpleLinkDialogProps) {
const [linkCopied, setLinkCopied] = useState(false);
if (!isOpen) return null;
const handleCopyLink = async () => {
if (!shareUrl) return;
try {
await navigator.clipboard.writeText(shareUrl);
setLinkCopied(true);
setTimeout(() => setLinkCopied(false), 2000);
} catch (err) {}
};
return createPortal(
<>
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/50 z-[199]"
onClick={onClose}
/>
{/* Dialog */}
<div className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[200] w-full max-w-md px-4">
<div className="relative bg-white rounded-2xl shadow-2xl p-6">
{/* Close Button */}
<button
onClick={onClose}
className="absolute right-4 top-4 text-gray-400 hover:text-gray-600 transition-colors"
>
<X className="h-5 w-5" />
</button>
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-3xl font-light font-eb-garamond text-gray-900">
Share Chat
</h2>
</div>
{/* Content */}
<div className="space-y-4">
{/* Link display */}
<div className="bg-gray-50 rounded-lg p-3 border border-gray-200">
<p className="text-sm text-gray-600 mb-2 font-medium">
Share Link
</p>
<p className="text-sm text-gray-800 break-all font-mono">
{shareUrl}
</p>
</div>
{/* Copy button */}
<button
onClick={handleCopyLink}
className="w-full flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white py-2.5 px-4 rounded-lg transition-colors font-medium"
>
{linkCopied ? (
<>
<Check className="h-5 w-5" />
Copied!
</>
) : (
<>
<Link2 className="h-5 w-5" />
Copy Link
</>
)}
</button>
</div>
</div>
</div>
</>,
document.body,
);
}

View file

@ -0,0 +1,204 @@
"use client";
import { useRef, useState } from "react";
import { X, Users, Upload } from "lucide-react";
import {
addDocumentToProject,
createProject,
uploadProjectDocument,
} from "@/app/lib/mikeApi";
import { useDirectoryData } from "../shared/useDirectoryData";
import { FileDirectory } from "../shared/FileDirectory";
import { EmailPillInput } from "../shared/EmailPillInput";
import type { MikeProject } from "../shared/types";
interface Props {
open: boolean;
onClose: () => void;
onCreated: (project: MikeProject) => void;
}
export function NewProjectModal({ open, onClose, onCreated }: Props) {
const [name, setName] = useState("");
const [cmNumber, setCmNumber] = useState("");
const [sharedEmails, setSharedEmails] = useState<string[]>([]);
const [showMembers, setShowMembers] = useState(false);
const [selectedDocIds, setSelectedDocIds] = useState<Set<string>>(new Set());
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const fileInputRef = useRef<HTMLInputElement>(null);
const { loading: dirLoading, standaloneDocuments, projects: dirProjects } = useDirectoryData(open);
if (!open) return null;
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files ?? []);
e.target.value = "";
if (!files.length) return;
setPendingFiles((prev) => [...prev, ...files.filter((f) => !prev.some((p) => p.name === f.name))]);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setLoading(true);
setError("");
try {
const project = await createProject(
name.trim(),
cmNumber.trim() || undefined,
sharedEmails,
);
await Promise.all([
...[...selectedDocIds].map((id) => addDocumentToProject(project.id, id).catch(() => {})),
...pendingFiles.map((f) => uploadProjectDocument(project.id, f).catch(() => {})),
]);
onCreated({ ...project, document_count: selectedDocIds.size + pendingFiles.length });
resetForm();
onClose();
} catch (err: unknown) {
setError((err as Error).message || "Failed to create project");
} finally {
setLoading(false);
}
}
function resetForm() {
setName("");
setCmNumber("");
setSharedEmails([]);
setShowMembers(false);
setSelectedDocIds(new Set());
setPendingFiles([]);
setError("");
}
function handleClose() {
resetForm();
onClose();
}
return (
<div className="fixed inset-0 z-101 flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-6 pt-5 pb-2">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Projects</span>
<span></span>
<span>New project</span>
</div>
<button
onClick={handleClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
<form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0">
<div className="px-6 pt-3 pb-5 flex-1 overflow-y-auto">
{/* Title */}
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Project name"
className="w-full text-2xl font-serif text-gray-800 placeholder-gray-300 focus:outline-none bg-transparent"
autoFocus
/>
{/* CM Number */}
<input
type="text"
value={cmNumber}
onChange={(e) => setCmNumber(e.target.value)}
placeholder="Add a CM number..."
className="mt-1.5 w-full text-sm text-gray-500 placeholder-gray-300 focus:outline-none bg-transparent"
/>
{/* Attribute pills */}
<div className="mt-4 flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setShowMembers((v) => !v)}
className="flex items-center gap-1.5 rounded-full border border-gray-200 px-3 py-1 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<Users className="h-3 w-3 text-gray-400" />
Members{sharedEmails.length > 0 ? ` (${sharedEmails.length})` : ""}
</button>
</div>
{/* Members panel */}
{showMembers && (
<div className="mt-3">
<EmailPillInput
emails={sharedEmails}
onChange={setSharedEmails}
placeholder="Add colleagues by email…"
/>
</div>
)}
{/* Documents */}
<div className="mt-4 space-y-2">
<p className="text-xs font-medium text-gray-700">Select documents</p>
<FileDirectory
standaloneDocs={standaloneDocuments}
directoryProjects={dirProjects}
loading={dirLoading}
selectedIds={selectedDocIds}
onChange={setSelectedDocIds}
emptyMessage="No existing documents"
/>
</div>
{error && (
<p className="mt-3 text-sm text-red-500">{error}</p>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between border-t border-gray-100 px-6 py-4 shrink-0">
<div className="flex items-center gap-2">
<input
ref={fileInputRef}
type="file"
multiple
className="hidden"
onChange={handleFileChange}
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-xs text-gray-500 hover:bg-gray-50 transition-colors"
>
<Upload className="h-3.5 w-3.5" />
Upload files{pendingFiles.length > 0 ? ` (${pendingFiles.length})` : ""}
</button>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleClose}
className="rounded-lg px-4 py-2 text-sm text-gray-500 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={!name.trim() || loading}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
{loading ? "Creating…" : "Create project"}
</button>
</div>
</div>
</form>
</div>
</div>
);
}

View file

@ -0,0 +1,425 @@
"use client";
import { useEffect, useRef, useState } from "react";
import {
FileText,
File,
Folder,
FolderOpen,
ChevronRight,
ChevronDown,
FolderPlus,
Trash2,
} from "lucide-react";
import type { MikeDocument, MikeFolder } from "@/app/components/shared/types";
import { VersionChip } from "@/app/components/shared/VersionChip";
interface Props {
projectName?: string | null;
documents: MikeDocument[];
folders?: MikeFolder[];
selectedDocId?: string | null;
onDocClick: (doc: MikeDocument) => void;
onCreateFolder?: (parentFolderId: string | null, name: string) => Promise<void>;
onRenameFolder?: (folderId: string, name: string) => Promise<void>;
onDeleteFolder?: (folderId: string) => Promise<void>;
onDeleteDoc?: (docId: string) => Promise<void>;
onMoveDoc?: (docId: string, targetFolderId: string | null) => Promise<void>;
onMoveFolder?: (folderId: string, targetFolderId: string | null) => Promise<void>;
}
function DocIcon({ fileType }: { fileType: string | null }) {
if (fileType === "pdf")
return <FileText className="h-3.5 w-3.5 text-red-500 shrink-0" />;
if (fileType === "docx" || fileType === "doc")
return <File className="h-3.5 w-3.5 text-blue-500 shrink-0" />;
return <File className="h-3.5 w-3.5 text-gray-400 shrink-0" />;
}
type ContextMenuState = {
x: number;
y: number;
parentId: string | null; // folder to create inside (null = root)
folderId?: string; // set if right-clicked on a specific folder
docId?: string; // set if right-clicked on a specific document
};
export function ProjectExplorer({
projectName,
documents,
folders = [],
selectedDocId,
onDocClick,
onCreateFolder,
onRenameFolder,
onDeleteFolder,
onDeleteDoc,
onMoveDoc,
onMoveFolder,
}: Props) {
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
const [creatingIn, setCreatingIn] = useState<string | null | undefined>(undefined);
const [newFolderName, setNewFolderName] = useState("");
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [dragOverFolderId, setDragOverFolderId] = useState<string | null>(null);
const [dragOverRoot, setDragOverRoot] = useState(false);
const newFolderInputRef = useRef<HTMLInputElement>(null);
const contextMenuRef = useRef<HTMLDivElement>(null);
// Close context menu on outside click
useEffect(() => {
if (!contextMenu) return;
function handle(e: MouseEvent) {
if (contextMenuRef.current && !contextMenuRef.current.contains(e.target as Node)) {
setContextMenu(null);
}
}
document.addEventListener("mousedown", handle);
return () => document.removeEventListener("mousedown", handle);
}, [contextMenu]);
// Clear all drag state when drag ends
useEffect(() => {
function handleDragEnd() {
setDragOverFolderId(null);
setDragOverRoot(false);
}
document.addEventListener("dragend", handleDragEnd);
return () => document.removeEventListener("dragend", handleDragEnd);
}, []);
function toggleFolder(id: string) {
setExpandedIds((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
}
async function commitNewFolder(parentId: string | null) {
const name = newFolderName.trim();
// Empty name → leave the input in place. Users dismiss with Escape.
// This guards against a React StrictMode race where the simulated
// unmount fires a blur that would otherwise immediately collapse
// the freshly-mounted input.
if (!name) return;
setCreatingIn(undefined);
setNewFolderName("");
if (!onCreateFolder) return;
await onCreateFolder(parentId, name);
if (parentId) setExpandedIds((prev) => new Set([...prev, parentId]));
}
async function commitRename(folderId: string) {
const name = renameValue.trim();
setRenamingId(null);
if (!name || !onRenameFolder) return;
await onRenameFolder(folderId, name);
}
function openContextMenu(
e: React.MouseEvent,
parentId: string | null,
folderId?: string,
docId?: string,
) {
e.preventDefault();
e.stopPropagation();
setContextMenu({ x: e.clientX, y: e.clientY, parentId, folderId, docId });
}
function wouldCreateCycle(movingId: string, targetId: string): boolean {
let cur: MikeFolder | undefined = folders.find((f) => f.id === targetId);
while (cur) {
if (cur.id === movingId) return true;
if (!cur.parent_folder_id) break;
cur = folders.find((f) => f.id === cur!.parent_folder_id);
}
return false;
}
async function handleDropOnTarget(targetFolderId: string | null, e: React.DragEvent) {
const docId = e.dataTransfer.getData("application/mike-doc");
const movingFolderId = e.dataTransfer.getData("application/mike-folder");
if (docId && onMoveDoc) {
const doc = documents.find((d) => d.id === docId);
if (!doc || (doc.folder_id ?? null) === targetFolderId) return;
await onMoveDoc(docId, targetFolderId);
} else if (movingFolderId && movingFolderId !== targetFolderId && onMoveFolder) {
if (targetFolderId !== null && wouldCreateCycle(movingFolderId, targetFolderId)) return;
const folder = folders.find((f) => f.id === movingFolderId);
if (!folder || (folder.parent_folder_id ?? null) === targetFolderId) return;
await onMoveFolder(movingFolderId, targetFolderId);
}
}
function isInternalDrag(e: React.DragEvent): boolean {
return (
Array.from(e.dataTransfer.types).includes("application/mike-doc") ||
Array.from(e.dataTransfer.types).includes("application/mike-folder")
);
}
function renderLevel(parentId: string | null, depth: number): React.ReactNode {
const basePadding = 28 + (depth - 1) * 16; // pl-7 at depth 1, +16px per level
const childFolders = folders
.filter((f) => f.parent_folder_id === parentId)
.sort((a, b) => a.name.localeCompare(b.name));
const childDocs = documents.filter((d) => (d.folder_id ?? null) === parentId);
return (
<>
{/* Inline new-folder input */}
{creatingIn === parentId && (
<li
className="flex items-center gap-1.5 py-1.5 pr-2 select-none"
style={{ paddingLeft: basePadding }}
>
<ChevronRight className="h-3 w-3 text-gray-300 shrink-0" />
<FolderPlus className="h-3.5 w-3.5 text-amber-400 shrink-0" />
<input
ref={newFolderInputRef}
autoFocus
className="flex-1 min-w-0 text-xs bg-transparent outline-none border-b border-gray-300 text-gray-800"
placeholder="Folder name"
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void commitNewFolder(parentId);
if (e.key === "Escape") { setCreatingIn(undefined); setNewFolderName(""); }
}}
onBlur={() => void commitNewFolder(parentId)}
/>
</li>
)}
{/* Child folders */}
{childFolders.map((folder) => {
const isExpanded = expandedIds.has(folder.id);
const isRenaming = renamingId === folder.id;
const isDragTarget = dragOverFolderId === folder.id;
return (
<li key={`f-${folder.id}`}>
<div
draggable
onDragStart={(e) => {
e.dataTransfer.setData("application/mike-folder", folder.id);
e.dataTransfer.effectAllowed = "move";
e.stopPropagation();
}}
onDragOver={(e) => {
e.preventDefault();
e.stopPropagation();
setDragOverFolderId(folder.id);
setDragOverRoot(false);
}}
onDragLeave={(e) => {
e.stopPropagation();
setDragOverFolderId(null);
}}
onDrop={async (e) => {
e.preventDefault();
if (isInternalDrag(e)) {
e.stopPropagation();
setDragOverFolderId(null);
setDragOverRoot(false);
await handleDropOnTarget(folder.id, e);
}
}}
className={`flex items-center gap-1.5 py-1.5 pr-2 rounded-sm cursor-pointer select-none transition-colors group ${
isDragTarget
? "bg-blue-50 ring-1 ring-inset ring-blue-200"
: "hover:bg-gray-50"
}`}
style={{ paddingLeft: basePadding }}
onClick={() => toggleFolder(folder.id)}
onContextMenu={(e) =>
openContextMenu(e, folder.id, folder.id)
}
>
{isExpanded
? <ChevronDown className="h-3 w-3 text-gray-400 shrink-0" />
: <ChevronRight className="h-3 w-3 text-gray-400 shrink-0" />
}
{isExpanded
? <FolderOpen className="h-3.5 w-3.5 text-amber-500 shrink-0" />
: <Folder className="h-3.5 w-3.5 text-amber-500 shrink-0" />
}
{isRenaming ? (
<input
autoFocus
className="flex-1 min-w-0 text-xs bg-transparent outline-none border-b border-gray-300 text-gray-800"
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void commitRename(folder.id);
if (e.key === "Escape") setRenamingId(null);
}}
onBlur={() => void commitRename(folder.id)}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span className="text-xs text-gray-600 truncate">{folder.name}</span>
)}
</div>
{isExpanded && (
<ul>{renderLevel(folder.id, depth + 1)}</ul>
)}
</li>
);
})}
{/* Child documents */}
{childDocs.map((doc) => {
const isSelected = doc.id === selectedDocId;
return (
<li
key={`d-${doc.id}`}
draggable
onDragStart={(e) => {
e.dataTransfer.setData("application/mike-doc", doc.id);
e.dataTransfer.effectAllowed = "move";
}}
onDragOver={(e) => e.stopPropagation()} // don't let doc rows affect root drag state
onClick={() => onDocClick(doc)}
onContextMenu={(e) =>
openContextMenu(
e,
doc.folder_id ?? null,
undefined,
doc.id,
)
}
className={`flex items-center gap-2 py-1.5 pr-4 rounded-sm cursor-pointer select-none transition-colors ${
isSelected ? "bg-gray-100 text-gray-900" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"
}`}
style={{ paddingLeft: basePadding }}
>
<DocIcon fileType={doc.file_type} />
<span className="text-xs truncate">{doc.filename}</span>
<VersionChip n={doc.latest_version_number} />
</li>
);
})}
</>
);
}
return (
<ul
className={`p-1 relative h-full ${dragOverRoot && dragOverFolderId === null ? "ring-2 ring-blue-400 ring-inset" : ""}`}
onContextMenu={(e) => {
// Only fires if not stopped by a child
openContextMenu(e, null);
}}
onDragOver={(e) => {
e.preventDefault();
setDragOverRoot(true);
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
setDragOverRoot(false);
}
}}
onDrop={async (e) => {
e.preventDefault();
if (isInternalDrag(e)) {
e.stopPropagation();
setDragOverRoot(false);
setDragOverFolderId(null);
await handleDropOnTarget(null, e);
}
// External file drops bubble up to the parent panel's onDrop (upload handler)
}}
>
{/* Project root row */}
{projectName && (
<li
className="flex items-center gap-2 px-2 py-1.5 select-none"
onContextMenu={(e) => { e.stopPropagation(); openContextMenu(e, null); }}
>
<FolderOpen className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<span className="text-xs text-gray-500 truncate">{projectName}</span>
</li>
)}
{/* Tree (depth 1 = direct children of root).
Root-level new-folder input is rendered here by renderLevel
when creatingIn === null no separate top-level block. */}
{renderLevel(null, 1)}
{/* Empty state */}
{documents.length === 0 && folders.length === 0 && creatingIn === undefined && (
<li className="px-4 py-2 text-xs text-gray-400">No documents in this project.</li>
)}
{/* Context menu */}
{contextMenu && (
<div
ref={contextMenuRef}
className="fixed z-50 w-44 rounded-lg border border-gray-100 bg-white shadow-lg overflow-hidden text-xs"
style={{ top: contextMenu.y, left: contextMenu.x }}
>
{onCreateFolder && (
<button
className="w-full px-3 py-1.5 text-left text-gray-700 hover:bg-gray-50 flex items-center gap-2"
onClick={() => {
setContextMenu(null);
if (contextMenu.parentId) {
setExpandedIds((prev) =>
new Set([...prev, contextMenu.parentId!]),
);
}
setCreatingIn(contextMenu.parentId);
setNewFolderName("");
}}
>
<FolderPlus className="h-3.5 w-3.5 text-gray-400" />
New subfolder
</button>
)}
{contextMenu.folderId && onRenameFolder && (
<button
className="w-full px-3 py-1.5 text-left text-gray-700 hover:bg-gray-50"
onClick={() => {
const f = folders.find((x) => x.id === contextMenu.folderId);
setRenameValue(f?.name ?? "");
setRenamingId(contextMenu.folderId!);
setContextMenu(null);
}}
>
Rename
</button>
)}
{contextMenu.folderId && onDeleteFolder && (
<button
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-red-600 hover:bg-red-50"
onClick={() => {
onDeleteFolder(contextMenu.folderId!);
setContextMenu(null);
}}
>
<Trash2 className="h-3.5 w-3.5 shrink-0" />
Delete folder
</button>
)}
{contextMenu.docId && onDeleteDoc && (
<button
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-red-600 hover:bg-red-50"
onClick={() => {
void onDeleteDoc(contextMenu.docId!);
setContextMenu(null);
}}
>
<Trash2 className="h-3.5 w-3.5 shrink-0" />
Delete file
</button>
)}
</div>
)}
</ul>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,448 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Plus, FolderOpen, ChevronDown } from "lucide-react";
import { HeaderSearchBtn } from "@/app/components/shared/HeaderSearchBtn";
import { listProjects, updateProject, deleteProject } from "@/app/lib/mikeApi";
import { OwnerOnlyModal } from "@/app/components/shared/OwnerOnlyModal";
import { useAuth } from "@/contexts/AuthContext";
import type { MikeProject } from "@/app/components/shared/types";
import { NewProjectModal } from "./NewProjectModal";
import { ToolbarTabs } from "@/app/components/shared/ToolbarTabs";
import { RowActions } from "@/app/components/shared/RowActions";
function formatDate(iso: string) {
return new Date(iso).toLocaleDateString(undefined, {
day: "numeric",
month: "short",
year: "numeric",
});
}
type Tab = "all" | "mine" | "shared-with-me";
const CHECK_W = "w-8 shrink-0";
const NAME_COL_W = "w-[300px] shrink-0";
export function ProjectsOverview() {
const [projects, setProjects] = useState<MikeProject[]>([]);
const [loading, setLoading] = useState(true);
const [modalOpen, setModalOpen] = useState(false);
const [activeTab, setActiveTab] = useState<Tab>("all");
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [cmEditingId, setCmEditingId] = useState<string | null>(null);
const [cmValue, setCmValue] = useState("");
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [actionsOpen, setActionsOpen] = useState(false);
const [search, setSearch] = useState("");
const [ownerOnlyAction, setOwnerOnlyAction] = useState<string | null>(null);
const actionsRef = useRef<HTMLDivElement>(null);
const router = useRouter();
const { user } = useAuth();
useEffect(() => {
listProjects()
.then(setProjects)
.catch(() => setProjects([]))
.finally(() => setLoading(false));
}, []);
useEffect(() => {
setSelectedIds([]);
}, [activeTab]);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (
actionsRef.current &&
!actionsRef.current.contains(e.target as Node)
)
setActionsOpen(false);
}
if (actionsOpen) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [actionsOpen]);
const q = search.toLowerCase();
const filtered = (
activeTab === "all"
? projects
: activeTab === "mine"
? projects.filter((p) => p.is_owner ?? p.user_id === user?.id)
: projects.filter((p) => !(p.is_owner ?? p.user_id === user?.id))
).filter(
(p) =>
!q ||
p.name.toLowerCase().includes(q) ||
(p.cm_number ?? "").toLowerCase().includes(q),
);
const allSelected =
filtered.length > 0 &&
filtered.every((p) => selectedIds.includes(p.id));
const someSelected =
!allSelected && filtered.some((p) => selectedIds.includes(p.id));
function toggleAll() {
if (allSelected) {
setSelectedIds([]);
} else {
setSelectedIds(filtered.map((p) => p.id));
}
}
function toggleOne(id: string) {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
);
}
const tabs: { id: Tab; label: string }[] = [
{ id: "all", label: "All" },
{ id: "mine", label: "Mine" },
{ id: "shared-with-me", label: "Shared with me" },
];
async function handleRenameSubmit(projectId: string) {
const trimmed = renameValue.trim();
setRenamingId(null);
if (!trimmed) return;
setProjects((prev) =>
prev.map((p) => (p.id === projectId ? { ...p, name: trimmed } : p)),
);
await updateProject(projectId, { name: trimmed });
}
async function handleCmSubmit(projectId: string) {
const trimmed = cmValue.trim();
setCmEditingId(null);
setProjects((prev) =>
prev.map((p) =>
p.id === projectId ? { ...p, cm_number: trimmed || null } : p,
),
);
await updateProject(projectId, { cm_number: trimmed || undefined });
}
async function handleDeleteSelected() {
const ids = [...selectedIds];
setActionsOpen(false);
// Only the project owner can delete; the per-row delete is hidden
// for shared projects but the bulk action can still pick them up
// if a user toggled them across tabs. Filter and warn.
const owned = ids.filter((id) => {
const p = projects.find((pp) => pp.id === id);
return !p || (p.is_owner ?? p.user_id === user?.id);
});
const blocked = ids.length - owned.length;
setSelectedIds([]);
await Promise.all(owned.map((id) => deleteProject(id).catch(() => {})));
setProjects((prev) => prev.filter((p) => !owned.includes(p.id)));
if (blocked > 0) {
setOwnerOnlyAction(
`delete ${blocked} of the selected projects — only the project owner can delete a project`,
);
}
}
const toolbarActions = (
<div className="flex items-center gap-2">
{selectedIds.length > 0 && (
<div ref={actionsRef} className="relative">
<button
onClick={() => setActionsOpen((v) => !v)}
className="flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-gray-900 transition-colors"
>
Actions
<ChevronDown className="h-3.5 w-3.5" />
</button>
{actionsOpen && (
<div className="absolute top-full right-0 mt-1 w-36 rounded-lg border border-gray-100 bg-white shadow-lg z-50 overflow-hidden">
<button
onClick={handleDeleteSelected}
className="w-full px-3 py-1.5 text-left text-xs text-red-600 hover:bg-red-50 transition-colors"
>
Delete
</button>
</div>
)}
</div>
)}
</div>
);
return (
<div className="flex-1 overflow-y-auto bg-white">
{/* Page header */}
<div className="flex items-center justify-between px-8 py-4">
<h1 className="text-2xl font-medium font-serif text-gray-900">
Projects
</h1>
<div className="flex items-center gap-2">
<HeaderSearchBtn
value={search}
onChange={setSearch}
placeholder="Search projects…"
/>
<button
onClick={() => setModalOpen(true)}
className="flex items-center justify-center p-1.5 text-gray-500 hover:text-gray-900 transition-colors"
>
<Plus className="h-4 w-4" />
</button>
</div>
</div>
<ToolbarTabs
tabs={tabs}
active={activeTab}
onChange={setActiveTab}
actions={toolbarActions}
/>
{/* Table */}
<div className="w-full overflow-x-auto">
<div className="min-w-max">
{/* Column headers */}
<div className="flex items-center h-8 pr-8 border-b border-gray-200 text-xs text-gray-500 font-medium select-none">
<div className={`sticky left-0 z-[60] ${CHECK_W} relative bg-white flex items-center justify-center self-stretch before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-white`}>
{!loading && (
<input
type="checkbox"
checked={allSelected}
ref={(el) => {
if (el) el.indeterminate = someSelected;
}}
onChange={toggleAll}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
)}
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} bg-white pl-2 text-left`}>
Name
</div>
<div className="ml-auto w-32 shrink-0 text-left">CM</div>
<div className="w-24 shrink-0 text-left">Files</div>
<div className="w-24 shrink-0 text-left">Chats</div>
<div className="w-36 shrink-0 text-left">
Tabular Reviews
</div>
<div className="w-32 shrink-0 text-left">Created</div>
<div className="w-8 shrink-0" />
</div>
{loading ? (
<div>
{[1, 2, 3].map((i) => (
<div
key={i}
className="flex items-center h-10 pr-8 border-b border-gray-50"
>
<div className="w-8 shrink-0" />
<div className="flex-1 min-w-0 pl-3 pr-4">
<div className="h-3.5 w-48 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-32 shrink-0">
<div className="h-3 w-20 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-24 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-24 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-36 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-32 shrink-0">
<div className="h-3 w-20 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-8 shrink-0" />
</div>
))}
</div>
) : filtered.length === 0 ? (
<div className="flex flex-col items-start py-24 w-full max-w-xs mx-auto">
{activeTab === "all" || activeTab === "mine" ? (
<>
<FolderOpen className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Projects
</p>
<p className="mt-1 text-xs text-gray-400 max-w-xs">
Upload documents into projects and to
commence chats and tabular reviews with
them.
</p>
<button
onClick={() => setModalOpen(true)}
className="mt-4 inline-flex items-center gap-1 rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white hover:bg-gray-700 transition-colors shadow-md"
>
+ Create New
</button>
</>
) : (
<p className="text-sm text-gray-400">
No {activeTab} projects
</p>
)}
</div>
) : (
<div>
{filtered.map((project) => {
const rowBg = selectedIds.includes(project.id)
? "bg-gray-50"
: "bg-white";
return (
<div
key={project.id}
onClick={() => {
if (renamingId === project.id) return;
router.push(`/projects/${project.id}`);
}}
className="group flex items-center h-10 pr-8 border-b border-gray-50 hover:bg-gray-50 cursor-pointer transition-colors"
>
<div
className={`sticky left-0 z-[60] ${CHECK_W} p-2 flex items-center justify-center ${rowBg} group-hover:bg-gray-50`}
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={selectedIds.includes(
project.id,
)}
onChange={() => toggleOne(project.id)}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
{/* Project Name */}
<div className={`sticky left-8 z-[60] ${NAME_COL_W} p-2 ${rowBg} group-hover:bg-gray-50`}>
{renamingId === project.id ? (
<input
autoFocus
value={renameValue}
onChange={(e) =>
setRenameValue(e.target.value)
}
onKeyDown={(e) => {
if (e.key === "Enter")
handleRenameSubmit(
project.id,
);
if (e.key === "Escape")
setRenamingId(null);
}}
onBlur={() =>
handleRenameSubmit(project.id)
}
onClick={(e) => e.stopPropagation()}
className="w-full text-sm text-gray-800 bg-transparent outline-none"
/>
) : (
<span className="text-sm text-gray-800 truncate block">
{project.name}
</span>
)}
</div>
<div
className="ml-auto w-32 shrink-0 text-sm text-gray-500 truncate"
onClick={(e) => e.stopPropagation()}
>
{cmEditingId === project.id ? (
<input
autoFocus
value={cmValue}
onChange={(e) =>
setCmValue(e.target.value)
}
onKeyDown={(e) => {
if (e.key === "Enter")
handleCmSubmit(project.id);
if (e.key === "Escape")
setCmEditingId(null);
}}
onBlur={() =>
handleCmSubmit(project.id)
}
placeholder="CM #"
className="w-full text-sm text-gray-800 bg-transparent outline-none"
/>
) : (
(project.cm_number ?? (
<span className="text-gray-300">
</span>
))
)}
</div>
<div className="w-24 shrink-0 text-sm text-gray-500 truncate">
{project.document_count ?? 0}
</div>
<div className="w-24 shrink-0 text-sm text-gray-500 truncate">
{project.chat_count ?? 0}
</div>
<div className="w-36 shrink-0 text-sm text-gray-500 truncate">
{project.review_count ?? 0}
</div>
<div className="w-32 shrink-0 text-sm text-gray-500 truncate">
{formatDate(project.created_at)}
</div>
<div
className="w-8 shrink-0 flex justify-end"
onClick={(e) => e.stopPropagation()}
>
{(project.is_owner ??
project.user_id === user?.id) && (
<RowActions
onRename={() => {
setRenameValue(project.name);
setRenamingId(project.id);
}}
onUpdateCmNumber={() => {
setCmValue(
project.cm_number ?? "",
);
setCmEditingId(project.id);
}}
onDelete={async () => {
await deleteProject(project.id);
setProjects((prev) =>
prev.filter(
(p) =>
p.id !== project.id,
),
);
}}
/>
)}
</div>
</div>
);
})}
</div>
)}
</div>
</div>
<NewProjectModal
open={modalOpen}
onClose={() => setModalOpen(false)}
onCreated={(p) => {
setProjects((prev) => [p, ...prev]);
router.push(`/projects/${p.id}`);
}}
/>
<OwnerOnlyModal
open={!!ownerOnlyAction}
action={ownerOnlyAction ?? undefined}
onClose={() => setOwnerOnlyAction(null)}
/>
</div>
);
}

View file

@ -0,0 +1,315 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { X, Upload, Search, Loader2 } from "lucide-react";
import {
uploadStandaloneDocument,
uploadProjectDocument,
addDocumentToProject,
deleteDocument,
} from "@/app/lib/mikeApi";
import type { MikeDocument } from "./types";
import { FileDirectory } from "./FileDirectory";
import { useDirectoryData, invalidateDirectoryCache } from "./useDirectoryData";
import { OwnerOnlyModal } from "./OwnerOnlyModal";
import { useAuth } from "@/contexts/AuthContext";
export { invalidateDirectoryCache };
interface Props {
open: boolean;
onClose: () => void;
onSelect: (documents: MikeDocument[], projectId?: string) => void;
breadcrumb: string[];
allowMultiple?: boolean;
projectId?: string;
}
export function AddDocumentsModal({
open,
onClose,
onSelect,
breadcrumb,
allowMultiple = true,
projectId,
}: Props) {
const { loading, standaloneDocuments, projects } = useDirectoryData(open);
const { user } = useAuth();
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [uploading, setUploading] = useState(false);
const [search, setSearch] = useState("");
const [extraUploadedDocs, setExtraUploadedDocs] = useState<MikeDocument[]>([]);
// IDs deleted in this session — hidden locally since `useDirectoryData`'s
// cached state won't re-fetch until the modal reopens.
const [deletedIds, setDeletedIds] = useState<Set<string>>(new Set());
const [ownerOnlyAction, setOwnerOnlyAction] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!open) return;
setSearch("");
setSelectedIds(new Set());
setExtraUploadedDocs([]);
setDeletedIds(new Set());
}, [open]);
if (!open) return null;
const q = search.toLowerCase().trim();
const allStandalone = [
...extraUploadedDocs.filter(
(u) => !standaloneDocuments.some((d) => d.id === u.id),
),
...standaloneDocuments,
].filter((d) => !deletedIds.has(d.id));
const filteredStandalone = q
? allStandalone.filter((d) => d.filename.toLowerCase().includes(q))
: allStandalone;
const filteredProjects = projects
.filter((p) => p.id !== projectId)
.map((p) => ({
...p,
documents: (p.documents || []).filter(
(d) =>
!deletedIds.has(d.id) &&
(!q || d.filename.toLowerCase().includes(q)),
),
}))
.filter(
(p) =>
!q ||
p.name.toLowerCase().includes(q) ||
p.documents.length > 0,
);
const allDocs = [
...allStandalone,
...projects.flatMap((p) => p.documents || []),
];
async function handleConfirm() {
const selected = allDocs.filter((d) => selectedIds.has(d.id));
if (projectId) {
const toAssign = selected.filter((d) => d.project_id !== projectId);
const alreadyHere = selected.filter(
(d) => d.project_id === projectId,
);
if (toAssign.length > 0) {
setUploading(true);
try {
const assigned = await Promise.all(
toAssign.map((d) =>
addDocumentToProject(projectId, d.id),
),
);
onSelect([...alreadyHere, ...assigned], projectId);
} catch (err) {
console.error("Failed to assign documents:", err);
} finally {
setUploading(false);
}
} else {
onSelect(alreadyHere, projectId);
}
onClose();
return;
}
const projectIds = new Set(
selected.map((d) => d.project_id).filter(Boolean),
);
const singleProjectId =
projectIds.size === 1 ? [...projectIds][0]! : undefined;
onSelect(selected, singleProjectId);
onClose();
}
async function handleDelete(ids: string[]) {
// Server only allows the doc creator to delete. Filter to owned
// and warn for the rest.
const docsById = new Map<string, MikeDocument>();
for (const d of [
...standaloneDocuments,
...extraUploadedDocs,
...projects.flatMap((p) => p.documents ?? []),
]) {
docsById.set(d.id, d);
}
const owned = ids.filter((id) => {
const d = docsById.get(id);
return !d || !d.user_id || !user?.id || d.user_id === user.id;
});
const blocked = ids.length - owned.length;
if (owned.length === 0 && blocked > 0) {
setOwnerOnlyAction(
"delete these documents — only the document creator can delete a document",
);
return;
}
const idSet = new Set(owned);
try {
await Promise.all(owned.map((id) => deleteDocument(id)));
} catch (err) {
console.error("Delete failed:", err);
return;
}
invalidateDirectoryCache();
setExtraUploadedDocs((prev) => prev.filter((d) => !idSet.has(d.id)));
setDeletedIds((prev) => {
const next = new Set(prev);
owned.forEach((id) => next.add(id));
return next;
});
if (blocked > 0) {
setOwnerOnlyAction(
`delete ${blocked} of the selected documents — only the document creator can delete a document`,
);
}
}
async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files || []);
if (!files.length) return;
setUploading(true);
try {
const uploaded = await Promise.all(
files.map((f) =>
projectId
? uploadProjectDocument(projectId, f)
: uploadStandaloneDocument(f),
),
);
invalidateDirectoryCache();
setExtraUploadedDocs((prev) => [...uploaded, ...prev]);
uploaded.forEach((d) =>
setSelectedIds((prev) => new Set([...prev, d.id])),
);
} catch (err) {
console.error("Upload failed:", err);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{breadcrumb.map((segment, i) => (
<span key={i} className="flex items-center gap-1.5">
{i > 0 && <span></span>}
{segment}
</span>
))}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Search bar */}
<div className="px-4 pt-1 pb-2">
<div className="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2">
<Search className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1 bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus
/>
{search && (
<button
onClick={() => setSearch("")}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
{/* File browser */}
<div className="flex-1 overflow-y-auto px-4 pb-2">
<FileDirectory
standaloneDocs={filteredStandalone}
directoryProjects={filteredProjects}
loading={loading}
selectedIds={selectedIds}
onChange={setSelectedIds}
allowMultiple={allowMultiple}
forceExpanded={!!q}
emptyMessage={
q ? "No matches found" : "No documents yet"
}
onDelete={handleDelete}
/>
</div>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-between gap-3">
<div>
<input
ref={fileInputRef}
type="file"
accept=".pdf,.docx,.doc"
multiple
className="hidden"
onChange={handleUpload}
/>
<button
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50 disabled:opacity-50"
>
{uploading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Upload className="h-3.5 w-3.5" />
)}
{uploading ? "Uploading…" : "Upload"}
</button>
</div>
<div className="flex items-center gap-2">
{selectedIds.size > 0 && (
<span className="text-xs text-gray-400">
{selectedIds.size} selected
</span>
)}
<button
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleConfirm}
disabled={selectedIds.size === 0 || uploading}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40"
>
{uploading ? "Saving…" : "Confirm"}
</button>
</div>
</div>
</div>
<OwnerOnlyModal
open={!!ownerOnlyAction}
action={ownerOnlyAction ?? undefined}
onClose={() => setOwnerOnlyAction(null)}
/>
</div>,
document.body,
);
}

View file

@ -0,0 +1,299 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Check, Loader2, Search, Upload, X } from "lucide-react";
import { getProject, uploadProjectDocument } from "@/app/lib/mikeApi";
import type { MikeDocument } from "./types";
import { DocFileIcon } from "./FileDirectory";
import { VersionChip } from "./VersionChip";
interface Props {
open: boolean;
onClose: () => void;
onSelect: (documents: MikeDocument[]) => void;
breadcrumb: string[];
projectId: string;
/** Docs already in the target list — rendered checked + disabled. */
excludeDocIds?: Set<string>;
allowMultiple?: boolean;
}
function formatDate(iso: string | null) {
if (!iso) return null;
return new Date(iso).toLocaleDateString(undefined, {
day: "numeric",
month: "short",
year: "numeric",
});
}
export function AddProjectDocsModal({
open,
onClose,
onSelect,
breadcrumb,
projectId,
excludeDocIds,
allowMultiple = true,
}: Props) {
const [docs, setDocs] = useState<MikeDocument[]>([]);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState("");
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!open) return;
setSearch("");
setSelectedIds(new Set());
let cancelled = false;
setLoading(true);
getProject(projectId)
.then((p) => {
if (!cancelled) setDocs(p.documents ?? []);
})
.catch(() => {
if (!cancelled) setDocs([]);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [open, projectId]);
if (!open) return null;
const q = search.toLowerCase().trim();
const filtered = q
? docs.filter((d) => d.filename.toLowerCase().includes(q))
: docs;
const isExcluded = (id: string) => !!excludeDocIds?.has(id);
function toggle(id: string) {
if (isExcluded(id)) return;
if (!allowMultiple) {
setSelectedIds(new Set([id]));
return;
}
setSelectedIds((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
}
function handleConfirm() {
const selected = docs.filter((d) => selectedIds.has(d.id));
onSelect(selected);
onClose();
}
async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files || []);
if (!files.length) return;
setUploading(true);
try {
const uploaded = await Promise.all(
files.map((f) => uploadProjectDocument(projectId, f)),
);
setDocs((prev) => [...uploaded, ...prev]);
setSelectedIds((prev) => {
const next = new Set(prev);
uploaded.forEach((d) => next.add(d.id));
return next;
});
} catch (err) {
console.error("Upload failed:", err);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{breadcrumb.map((segment, i) => (
<span
key={i}
className="flex items-center gap-1.5"
>
{i > 0 && <span></span>}
{segment}
</span>
))}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Search */}
<div className="px-4 pt-1 pb-2">
<div className="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2">
<Search className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1 bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus
/>
{search && (
<button
onClick={() => setSearch("")}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
{/* File list */}
<div className="flex-1 overflow-y-auto px-4 pb-2">
{loading ? (
<div className="rounded-sm border border-gray-100 overflow-hidden">
{[60, 45, 75, 55, 40].map((w, i) => (
<div
key={i}
className="flex items-center gap-2 px-2 py-2"
>
<div className="h-3.5 w-3.5 rounded border border-gray-200 shrink-0" />
<div className="h-3.5 w-3.5 rounded bg-gray-200 animate-pulse shrink-0" />
<div
className="h-3 rounded bg-gray-200 animate-pulse"
style={{ width: `${w}%` }}
/>
</div>
))}
</div>
) : filtered.length === 0 ? (
<p className="text-center text-sm text-gray-400 py-8">
{q ? "No matches found" : "No documents in this project"}
</p>
) : (
<div className="rounded-sm border border-gray-100 overflow-hidden">
{filtered.map((doc) => {
const excluded = isExcluded(doc.id);
const checked =
excluded || selectedIds.has(doc.id);
return (
<button
type="button"
key={doc.id}
disabled={excluded}
onClick={() => toggle(doc.id)}
className={`w-full flex items-center gap-2 px-2 py-2 text-xs text-left transition-colors ${
excluded
? "opacity-50 cursor-not-allowed"
: checked
? "bg-gray-100"
: "hover:bg-gray-50"
}`}
>
<span
className={`shrink-0 h-3.5 w-3.5 rounded border flex items-center justify-center ${
checked
? "bg-gray-900 border-gray-900"
: "border-gray-300"
}`}
>
{checked && (
<Check className="h-2.5 w-2.5 text-white" />
)}
</span>
<DocFileIcon
fileType={doc.file_type}
/>
<span
className={`flex-1 truncate ${
checked
? "text-gray-900"
: "text-gray-700"
}`}
>
{doc.filename}
</span>
{excluded && (
<span className="text-[10px] text-gray-400 shrink-0">
Already added
</span>
)}
<VersionChip
n={doc.latest_version_number}
/>
{doc.created_at && (
<span className="shrink-0 text-gray-300">
{formatDate(doc.created_at)}
</span>
)}
</button>
);
})}
</div>
)}
</div>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-between gap-3">
<div>
<input
ref={fileInputRef}
type="file"
accept=".pdf,.docx,.doc"
multiple
className="hidden"
onChange={handleUpload}
/>
<button
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50 disabled:opacity-50"
>
{uploading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Upload className="h-3.5 w-3.5" />
)}
{uploading ? "Uploading…" : "Upload"}
</button>
</div>
<div className="flex items-center gap-2">
{selectedIds.size > 0 && (
<span className="text-xs text-gray-400">
{selectedIds.size} selected
</span>
)}
<button
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleConfirm}
disabled={selectedIds.size === 0 || uploading}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40"
>
Confirm
</button>
</div>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,78 @@
"use client";
import { createPortal } from "react-dom";
import { useRouter } from "next/navigation";
import { AlertTriangle, X } from "lucide-react";
import { providerLabel, type ModelProvider } from "@/app/lib/modelAvailability";
interface Props {
open: boolean;
onClose: () => void;
provider: ModelProvider | null;
/** Optional override for the body sentence. */
message?: string;
}
export function ApiKeyMissingModal({ open, onClose, provider, message }: Props) {
const router = useRouter();
if (!open) return null;
const providerName = provider ? providerLabel(provider) : "this provider";
const body =
message ??
`You haven't added a ${providerName} API key yet. Add one in your account settings to use this model.`;
const handleGoToAccount = () => {
onClose();
router.push("/account/models");
};
return createPortal(
<div
className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs"
onClick={onClose}
>
<div
className="w-full max-w-md rounded-2xl bg-white shadow-2xl flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-start justify-between gap-3 px-5 pt-5 pb-2">
<div className="flex items-center gap-2">
<AlertTriangle className="h-4 w-4 text-amber-600" />
<h2 className="text-base font-medium text-gray-900">
API key required
</h2>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="px-5 pb-2 pt-1">
<p className="text-sm text-gray-600 leading-relaxed">
{body}
</p>
</div>
<div className="flex justify-end gap-2 px-5 pb-5 pt-3">
<button
onClick={onClose}
className="rounded-lg px-4 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleGoToAccount}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700"
>
Go to account settings
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,311 @@
"use client";
import { useState, useEffect } from "react";
import {
PanelLeft,
MessageSquare,
FolderOpen,
Table2,
Library,
User,
ChevronsUpDown,
ChevronDown,
} from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import { MikeIcon } from "@/components/chat/mike-icon";
import { SidebarChatItem } from "@/app/components/shared/SidebarChatItem";
import { listProjects } from "@/app/lib/mikeApi";
const NAV_ITEMS = [
{ href: "/assistant", label: "Assistant", icon: MessageSquare },
{ href: "/projects", label: "Projects", icon: FolderOpen },
{ href: "/tabular-reviews", label: "Tabular Review", icon: Table2 },
{ href: "/workflows", label: "Workflows", icon: Library },
];
interface AppSidebarProps {
isOpen: boolean;
onToggle: () => void;
}
export function AppSidebar({ isOpen, onToggle }: AppSidebarProps) {
const { user } = useAuth();
const { profile } = useUserProfile();
const { chats, currentChatId, setCurrentChatId } = useChatHistoryContext();
const router = useRouter();
const pathname = usePathname();
const [shouldAnimate, setShouldAnimate] = useState(false);
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [historyCollapsed, setHistoryCollapsed] = useState(false);
const [projectNames, setProjectNames] = useState<Record<string, string>>(
{},
);
useEffect(() => {
if (!user) return;
listProjects()
.then((projects) => {
const map: Record<string, string> = {};
for (const p of projects) map[p.id] = p.name;
setProjectNames(map);
})
.catch(() => {});
}, [user]);
useEffect(() => {
if (!isOpen) setShouldAnimate(true);
}, [isOpen]);
useEffect(() => {
const handleClickOutside = () => setIsDropdownOpen(false);
if (isDropdownOpen) {
document.addEventListener("click", handleClickOutside);
return () =>
document.removeEventListener("click", handleClickOutside);
}
}, [isDropdownOpen]);
useEffect(() => {
if (pathname.startsWith("/assistant/chat/")) {
const chatId = pathname.split("/").pop() ?? null;
setCurrentChatId(chatId);
return;
}
const projectChatMatch = pathname.match(
/^\/projects\/[^/]+\/assistant\/chat\/([^/]+)/,
);
if (projectChatMatch) {
setCurrentChatId(projectChatMatch[1]);
return;
}
if (pathname === "/assistant") {
setCurrentChatId(null);
}
}, [pathname, setCurrentChatId]);
const getUserInitials = (email: string) => {
if (profile?.displayName)
return profile.displayName.charAt(0).toUpperCase();
return email.charAt(0).toUpperCase();
};
const getDisplayName = () => {
if (!profile) return "";
return profile.displayName || user?.email?.split("@")[0] || "";
};
const getUserTier = () => {
if (!profile) return "";
return profile.tier || "Free";
};
if (!user) return null;
return (
<div
className={`${
isOpen
? "w-64 h-dvh bg-gray-50 border-r"
: "w-14 md:h-dvh md:bg-gray-50 md:border-r h-auto bg-transparent"
} border-gray-200 flex flex-col transition-all duration-300 absolute md:relative z-99 overflow-visible`}
>
{/* Toggle + Logo */}
<div
className={`mb-3 items-center justify-between px-2.5 py-2 ${
!isOpen ? "hidden md:flex" : "flex"
}`}
>
{isOpen && (
<div className="px-2.5">
<Link
href="/assistant"
className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
>
<MikeIcon size={22} />
<span
className={`text-2xl font-light font-serif ${
shouldAnimate ? "sidebar-fade-in" : ""
}`}
>
Mike
</span>
</Link>
</div>
)}
<button
onClick={onToggle}
className="h-9 w-9 p-2.5 items-center flex hover:bg-gray-100 rounded-md transition-colors"
title={isOpen ? "Close sidebar" : "Open sidebar"}
>
<PanelLeft className="h-4 w-4" />
</button>
</div>
{/* Nav items */}
{NAV_ITEMS.map(({ href, label, icon: Icon }) => {
const isActive =
pathname === href || pathname.startsWith(href + "/");
return (
<div key={href} className="py-1 px-2.5">
<button
onClick={() => router.push(href)}
title={!isOpen ? label : ""}
className={`w-full h-9 flex items-center gap-3 px-2.5 py-2 rounded-md transition-colors text-left ${
isActive
? "bg-gray-100 text-gray-900"
: "hover:bg-gray-100 text-gray-700"
} ${!isOpen ? "hidden md:flex" : "flex"}`}
>
<Icon
className={`h-4 w-4 flex-shrink-0 ${
isActive ? "text-gray-900" : "text-black"
}`}
/>
{isOpen && (
<span
className={`text-sm font-medium ${
shouldAnimate ? "sidebar-fade-in-2" : ""
}`}
>
{label}
</span>
)}
</button>
</div>
);
})}
{/* Assistant History */}
{isOpen && pathname.startsWith("/assistant") && (
<div className="mt-4 flex-1 min-h-0 flex flex-col">
<button
onClick={() => setHistoryCollapsed((v) => !v)}
className={`mb-2 px-5 flex items-center justify-between text-xs font-semibold text-gray-500 hover:text-gray-700 transition-colors ${
shouldAnimate ? "sidebar-fade-in" : ""
}`}
>
<span>Assistant History</span>
<ChevronDown
className={`h-3.5 w-3.5 transition-transform ${historyCollapsed ? "-rotate-90" : ""}`}
/>
</button>
<div
className={`overflow-y-auto flex-1 ${historyCollapsed ? "hidden" : ""}`}
>
{!chats ? (
<div className="space-y-1 px-2.5">
{[40, 60, 50, 70, 45].map((w, i) => (
<div
key={i}
className="h-9 flex items-center px-3 rounded-md"
>
<div
className="h-3 bg-gray-200 rounded animate-pulse"
style={{ width: `${w}%` }}
/>
</div>
))}
</div>
) : chats.length === 0 ? (
<div
className={`text-xs text-gray-500 py-2 px-5 ${
shouldAnimate ? "sidebar-fade-in-2" : ""
}`}
>
No chats yet
</div>
) : (
<div
className={`space-y-1 px-2.5 ${
shouldAnimate ? "sidebar-fade-in-2" : ""
}`}
>
{chats.map((chat) => (
<SidebarChatItem
key={chat.id}
chat={chat}
isActive={currentChatId === chat.id}
projectName={
chat.project_id
? projectNames[chat.project_id]
: undefined
}
onSelect={() => {
setCurrentChatId(chat.id);
router.push(
chat.project_id
? `/projects/${chat.project_id}/assistant/chat/${chat.id}`
: `/assistant/chat/${chat.id}`,
);
}}
/>
))}
</div>
)}
</div>
</div>
)}
{/* User Profile */}
<div className="mt-auto">
{user && (
<div className="relative">
<button
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
className={`flex items-center transition-colors w-full px-3.5 py-4 border-t border-gray-200 ${
!isOpen ? "hidden md:flex" : ""
} ${
pathname === "/account" || isDropdownOpen
? "bg-gray-100"
: "hover:bg-gray-100"
}`}
title={!isOpen ? user.email : undefined}
>
<div className="h-7 w-7 flex-shrink-0 rounded-full bg-gray-700 flex items-center justify-center text-white text-sm font-medium font-serif">
{getUserInitials(user.email)}
</div>
{isOpen && (
<div
className={`text-left flex-1 min-w-0 pl-3 flex items-center justify-between gap-2 ${
shouldAnimate ? "sidebar-fade-in-2" : ""
}`}
>
<div className="flex flex-col gap-0.5 min-w-0">
<div className="text-sm font-medium text-gray-900 leading-none">
{getDisplayName()}
</div>
<div className="text-[12px] text-gray-500 leading-none">
{getUserTier()}
</div>
</div>
<ChevronsUpDown className="h-4 w-4 flex-shrink-0 text-gray-400" />
</div>
)}
</button>
{isDropdownOpen && (
<div className="absolute bottom-full left-0 m-1 bg-white rounded-lg shadow-lg border border-gray-200 p-1 z-50 w-62 whitespace-nowrap">
<button
onClick={() => {
router.push("/account");
setIsDropdownOpen(false);
}}
className="w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 flex items-center gap-2 rounded-md"
>
<User className="h-4 w-4" />
Account Settings
</button>
</div>
)}
</div>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,505 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Download, Loader2 } from "lucide-react";
import { supabase } from "@/lib/supabase";
import { applyOptimisticResolution } from "../assistant/EditCard";
import { DocView } from "./DocView";
import { DocxView } from "./DocxView";
import {
displayCitationQuote,
expandCitationToEntries,
formatCitationPage,
} from "./types";
import type {
CitationQuote,
MikeCitationAnnotation,
MikeEditAnnotation,
} from "./types";
function isDocxFilename(name: string): boolean {
const ext = name.split(".").pop()?.toLowerCase();
return ext === "docx" || ext === "doc";
}
/**
* Discriminated-union describing what the panel is showing above the viewer.
* - "document": no header card, no label just the viewer.
* - "citation": "Citation Quote" card with the quoted text and page ref.
* - "edit": "Tracked Change" card with the diff + Accept/Reject.
*/
export type DocPanelMode =
| { kind: "document" }
| { kind: "citation"; citation: MikeCitationAnnotation }
| {
kind: "edit";
edit: MikeEditAnnotation;
/**
* True while an accept/reject request for this exact edit is in
* flight. Scoped per-edit (not per-document) so sibling edits on
* the same doc stay clickable.
*/
isEditReloading?: boolean;
onResolveStart?: (args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => void;
onResolved?: (args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => void;
onError?: (args: {
editId: string;
documentId: string;
versionId: string | null;
message: string;
}) => void;
};
interface Props {
documentId: string;
filename: string;
versionId: string | null;
versionNumber: number | null;
mode: DocPanelMode;
/** Spinner on the Download button while an accept/reject is in flight. */
isReloading?: boolean;
warning?: string | null;
onWarningDismiss?: () => void;
initialScrollTop?: number | null;
onScrollChange?: (scrollTop: number) => void;
}
/**
* Unified side-panel body for the assistant. Renders a single document
* with optionally a citation quote OR a tracked change highlighted above
* the viewer. No selector UI caller picks the one thing to show; if the
* user wants a different citation/edit, the panel gets a new tab.
*/
export function DocPanel({
documentId,
filename,
versionId,
versionNumber,
mode,
isReloading = false,
warning,
onWarningDismiss,
initialScrollTop,
onScrollChange,
}: Props) {
// Pick the viewer from the filename only, not from mode. Switching
// headers (citation ↔ edit ↔ document) for the same document must
// not unmount and remount the body — otherwise the user sees a full
// re-fetch every time they toggle. Tracked-change rendering still
// only lives in DocxView, which is fine because edits are DOCX-only.
const useDocxView = isDocxFilename(filename);
const quotes: CitationQuote[] | undefined = useMemo(() => {
if (mode.kind !== "citation") return undefined;
return expandCitationToEntries(mode.citation);
}, [mode]);
const highlightEdit = useMemo(() => {
if (mode.kind !== "edit") return null;
return {
key: `${mode.edit.edit_id}`,
inserted_text: mode.edit.inserted_text,
deleted_text: mode.edit.deleted_text,
ins_w_id: mode.edit.ins_w_id ?? null,
del_w_id: mode.edit.del_w_id ?? null,
};
}, [mode]);
return (
<div className="flex h-full flex-col px-3 pb-3">
{mode.kind === "citation" ? (
<CitationHeader
citation={mode.citation}
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
) : mode.kind === "edit" ? (
<TrackedChangeHeader
mode={mode}
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
) : (
<div className="flex items-center justify-end gap-2 py-2">
<div className="mr-auto flex min-w-0 items-center gap-2">
<span className="truncate text-sm text-gray-700">
{filename}
</span>
{versionNumber && versionNumber > 0 && (
<span className="shrink-0 inline-flex items-center rounded-md border border-gray-200 bg-white px-1.5 py-0.5 text-[10px] font-medium text-gray-600">
V{versionNumber}
</span>
)}
</div>
<DownloadButton
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
</div>
)}
{useDocxView ? (
<DocxView
documentId={documentId}
versionId={versionId ?? undefined}
quotes={quotes}
highlightEdit={highlightEdit}
warning={warning ?? null}
onWarningDismiss={onWarningDismiss}
initialScrollTop={initialScrollTop ?? null}
onScrollChange={onScrollChange}
/>
) : (
<DocView
doc={{
document_id: documentId,
version_id: versionId,
}}
quotes={quotes}
/>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Header variants
// ---------------------------------------------------------------------------
function SectionLabel({ children }: { children: React.ReactNode }) {
return <p className="text-xs font-medium text-gray-700">{children}</p>;
}
function CitationHeader({
citation,
documentId,
versionId,
filename,
isReloading,
}: {
citation: MikeCitationAnnotation;
documentId: string;
versionId: string | null;
filename: string;
isReloading: boolean;
}) {
const displayQuote = displayCitationQuote(citation);
const pagesLabel = formatCitationPage(citation);
return (
<div className="pt-2 pb-3">
<div className="flex items-center gap-2 mb-2">
<SectionLabel>Citation</SectionLabel>
<div className="ml-auto shrink-0">
<DownloadButton
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
</div>
</div>
<div className="w-full rounded-md bg-gray-50 border border-gray-200 px-2 py-2">
<p className="text-sm font-serif text-gray-600">
&ldquo;{displayQuote}&rdquo;
{pagesLabel && (
<span className="ml-1 text-gray-400">
({pagesLabel})
</span>
)}
</p>
</div>
</div>
);
}
function TrackedChangeHeader({
mode,
documentId,
versionId,
filename,
isReloading,
}: {
mode: Extract<DocPanelMode, { kind: "edit" }>;
documentId: string;
versionId: string | null;
filename: string;
isReloading: boolean;
}) {
const { edit, isEditReloading, onResolveStart, onResolved, onError } = mode;
return (
<div className="pt-2 pb-3">
<div className="flex items-center gap-2 mb-2">
<SectionLabel>Tracked Change</SectionLabel>
<div className="ml-auto flex items-center gap-2 shrink-0">
<EditResolveButtons
edit={edit}
isReloading={isEditReloading}
onResolveStart={onResolveStart}
onResolved={onResolved}
onError={onError}
/>
<DownloadButton
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
</div>
</div>
{edit.reason && (
<p className="mb-2 text-xs text-gray-500">{edit.reason}</p>
)}
<div className="w-full rounded-md bg-gray-50 border border-gray-200 px-2 py-2">
<div className="text-sm leading-relaxed font-serif">
{edit.inserted_text && (
<span className="text-green-700">
{edit.inserted_text}
</span>
)}
{edit.deleted_text && (
<span className="text-red-600 line-through">
{edit.deleted_text}
</span>
)}
</div>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Accept / Reject controls
// ---------------------------------------------------------------------------
function EditResolveButtons({
edit,
isReloading,
onResolveStart,
onResolved,
onError,
}: {
edit: MikeEditAnnotation;
/**
* True while an accept/reject for any edit on this document is in
* flight (triggered from here, the inline EditCard, the bulk bar, or
* elsewhere). Disables both buttons so the user can't double-submit
* while a resolution is racing to change the status.
*/
isReloading?: boolean;
onResolveStart?: (args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => void;
onResolved?: (args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => void;
onError?: (args: {
editId: string;
documentId: string;
versionId: string | null;
message: string;
}) => void;
}) {
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<"pending" | "accepted" | "rejected">(
edit.status,
);
// Sync with the prop when this edit is resolved elsewhere (bulk
// accept/reject, inline per-edit card, another open panel for the same
// edit). Skips while our own request is in flight so we don't flicker.
useEffect(() => {
if (busy) return;
setStatus(edit.status);
}, [edit.status, edit.edit_id, busy]);
const resolved = status !== "pending";
const handle = useCallback(
async (verb: "accept" | "reject") => {
if (busy || resolved) return;
setBusy(true);
onResolveStart?.({
editId: edit.edit_id,
documentId: edit.document_id,
verb,
});
// Optimistically mutate the DOM in the open viewer so the
// change reflects immediately. Revert if the backend errors.
let revert: (() => void) | null = null;
try {
revert = applyOptimisticResolution(edit, verb);
} catch (e) {
console.error(
"[DocPanel] optimistic update threw",
e,
);
}
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ??
"http://localhost:3001";
const resp = await fetch(
`${apiBase}/single-documents/${edit.document_id}/edits/${edit.edit_id}/${verb}`,
{
method: "POST",
headers: token
? { Authorization: `Bearer ${token}` }
: undefined,
},
);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = (await resp.json()) as {
ok: boolean;
status?: "accepted" | "rejected";
version_id: string | null;
download_url: string | null;
};
const nextStatus =
data.status ??
(verb === "accept" ? "accepted" : "rejected");
setStatus(nextStatus);
onResolved?.({
editId: edit.edit_id,
documentId: edit.document_id,
status: nextStatus,
versionId: data.version_id,
downloadUrl: data.download_url,
});
} catch (e) {
console.error("[DocPanel] resolve failed", e);
try {
revert?.();
} catch (revertErr) {
console.error(
"[DocPanel] revert threw",
revertErr,
);
}
onError?.({
editId: edit.edit_id,
documentId: edit.document_id,
versionId: edit.version_id ?? null,
message:
verb === "accept"
? "Couldn't save accept — please retry."
: "Couldn't save reject — please retry.",
});
} finally {
setBusy(false);
}
},
[busy, resolved, edit, onResolveStart, onResolved, onError],
);
const inFlight = busy || !!isReloading;
return (
<div className="flex items-center gap-2">
<button
onClick={() => handle("accept")}
disabled={inFlight || resolved}
className="inline-flex items-center gap-1 rounded-lg border border-gray-900 bg-gray-900 px-2 py-1.5 text-xs font-medium text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
>
{status === "accepted" ? "Accepted" : "Accept"}
</button>
<button
onClick={() => handle("reject")}
disabled={inFlight || resolved}
className="inline-flex items-center gap-1 rounded-lg border border-gray-200 bg-white px-2 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
>
{status === "rejected" ? "Rejected" : "Reject"}
</button>
</div>
);
}
// ---------------------------------------------------------------------------
// Download button
// ---------------------------------------------------------------------------
function DownloadButton({
documentId,
versionId,
filename,
isReloading,
}: {
documentId: string;
versionId: string | null;
filename: string;
isReloading?: boolean;
}) {
const [busy, setBusy] = useState(false);
const handleClick = async () => {
if (busy || isReloading) return;
setBusy(true);
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3001";
const qs = versionId
? `?version_id=${encodeURIComponent(versionId)}`
: "";
const resp = await fetch(
`${apiBase}/single-documents/${documentId}/docx${qs}`,
{
headers: token ? { Authorization: `Bearer ${token}` } : {},
},
);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const blob = await resp.blob();
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = blobUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
} finally {
setBusy(false);
}
};
const spinning = busy || isReloading;
return (
<button
onClick={handleClick}
disabled={spinning}
className="inline-flex items-center gap-1 rounded-lg border border-gray-200 px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-100 hover:text-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
>
{spinning ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Download className="h-3.5 w-3.5" />
)}
Download
</button>
);
}

View file

@ -0,0 +1,596 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ZoomIn, ZoomOut } from "lucide-react";
import { MikeIcon } from "@/components/chat/mike-icon";
import { useFetchSingleDoc } from "@/app/hooks/useFetchSingleDoc";
import { DocxView } from "./DocxView";
import type { CitationQuote } from "./types";
import {
clearHighlights,
getPdfJs,
highlightQuote,
STANDARD_FONT_DATA_URL,
} from "./highlightQuote";
interface Props {
doc: { document_id: string; version_id?: string | null } | null;
/** Preferred: one or more (page, quote) pairs to highlight. */
quotes?: CitationQuote[];
/** Back-compat single-quote API. Ignored if `quotes` is provided. */
quote?: string;
fallbackPage?: number;
rounded?: boolean;
bordered?: boolean;
}
type QuoteEntry = { page?: number; quote: string };
const SIDE_PADDING = 20;
const ZOOM_MIN = 0.5;
const ZOOM_MAX = 3.0;
const ZOOM_STEP = 0.25;
type RenderedPage = {
page: import("pdfjs-dist").PDFPageProxy;
viewport: import("pdfjs-dist").PageViewport;
wrapper: HTMLDivElement;
canvas: HTMLCanvasElement;
textDivs: HTMLElement[];
};
export function DocView({
doc,
quotes,
quote,
fallbackPage,
rounded = true,
bordered = true,
}: Props) {
const containerRef = useRef<HTMLDivElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
const pdfDocRef = useRef<import("pdfjs-dist").PDFDocumentProxy | null>(
null,
);
const renderedPagesRef = useRef<RenderedPage[]>([]);
const quoteListRef = useRef<QuoteEntry[]>([]);
const zoomRef = useRef(1.0);
const currentPageRef = useRef(1);
const quoteList: QuoteEntry[] = useMemo(() => {
if (quotes?.length)
return quotes.map((q) => ({ page: q.page, quote: q.quote }));
if (quote) return [{ page: fallbackPage, quote }];
return [];
}, [quotes, quote, fallbackPage]);
// Stable string key so effects can depend on quote-list identity
const quoteKey = quoteList
.map((q) => `${q.page ?? ""}:${q.quote}`)
.join("|");
const [containerWidth, setContainerWidth] = useState(0);
const [zoom, setZoom] = useState(1.0);
const [currentPage, setCurrentPage] = useState(1);
const [numPages, setNumPages] = useState(0);
const { result, loading, error } = useFetchSingleDoc(
doc?.document_id ?? null,
doc?.version_id ?? null,
);
// /display returned DOCX bytes — the active version has no PDF
// rendition, so fall back to docx-preview (still applies citation
// highlighting via the same `quotes` API).
const fallbackToDocx = result?.type === "docx";
// Track container width via ResizeObserver so re-renders fire on resize
useEffect(() => {
const el = scrollContainerRef.current;
if (!el) return;
const ro = new ResizeObserver((entries) => {
setContainerWidth(entries[0]?.contentRect.width ?? 0);
});
ro.observe(el);
return () => ro.disconnect();
}, []);
// Track current page via scroll position
useEffect(() => {
const scrollEl = scrollContainerRef.current;
if (!scrollEl) return;
const handleScroll = () => {
const pages = renderedPagesRef.current;
if (!pages.length) return;
const scrollCenter = scrollEl.scrollTop + scrollEl.clientHeight / 2;
let closest = 0;
let closestDist = Infinity;
pages.forEach((p, i) => {
const pageCenter =
p.wrapper.offsetTop + p.wrapper.clientHeight / 2;
const dist = Math.abs(pageCenter - scrollCenter);
if (dist < closestDist) {
closestDist = dist;
closest = i;
}
});
currentPageRef.current = closest + 1;
setCurrentPage(closest + 1);
};
scrollEl.addEventListener("scroll", handleScroll, { passive: true });
return () => scrollEl.removeEventListener("scroll", handleScroll);
}, []);
// Highlights all entries in `list` across the already-rendered pages.
// Returns the 1-based page number of the first successfully highlighted entry, or null.
const applyHighlights = useCallback(
async (list: QuoteEntry[]): Promise<number | null> => {
// Clear any prior highlights across all pages
for (const p of renderedPagesRef.current)
clearHighlights(p.textDivs);
let firstHitPage: number | null = null;
for (const entry of list) {
let hitPage: number | null = null;
if (entry.page) {
const target = renderedPagesRef.current[entry.page - 1];
if (target) {
const found = await highlightQuote(
target.textDivs,
entry.quote,
);
if (found) hitPage = entry.page;
}
}
// Fall back to scanning all pages for this quote
if (hitPage === null) {
console.warn(
`Quote not found on hinted page, scanning all pages: "${entry.quote.slice(0, 60)}..."`,
);
for (let i = 0; i < renderedPagesRef.current.length; i++) {
const p = renderedPagesRef.current[i];
const found = await highlightQuote(
p.textDivs,
entry.quote,
);
if (found) {
hitPage = i + 1;
break;
}
}
}
if (hitPage !== null && firstHitPage === null) {
firstHitPage = hitPage;
}
}
return firstHitPage;
},
[],
);
const renderPDF = useCallback(
async (
doc: import("pdfjs-dist").PDFDocumentProxy,
list: QuoteEntry[],
scrollToPage?: number,
) => {
if (!containerRef.current) return;
containerRef.current.innerHTML = "";
renderedPagesRef.current = [];
const lib = await getPdfJs();
lib.TextLayer.cleanup();
setNumPages(doc.numPages);
setCurrentPage(1);
currentPageRef.current = 1;
const hasCitation = list.length > 0;
if (hasCitation && scrollContainerRef.current) {
scrollContainerRef.current.style.opacity = "0";
}
const reveal = () => {
if (scrollContainerRef.current)
scrollContainerRef.current.style.opacity = "1";
};
const panelW = containerRef.current.clientWidth;
const firstPage = await doc.getPage(1);
const naturalWidth = firstPage.getViewport({ scale: 1 }).width;
const baseScale = Math.max(
0.5,
(panelW - SIDE_PADDING) / naturalWidth,
);
const scale = baseScale * zoomRef.current;
for (let pageNum = 1; pageNum <= doc.numPages; pageNum++) {
const page = await doc.getPage(pageNum);
const viewport = page.getViewport({ scale });
const wrapper = document.createElement("div");
wrapper.style.position = "relative";
wrapper.style.margin = "0 auto 8px";
wrapper.style.width = "fit-content";
wrapper.className = "shadow-md";
const canvas = document.createElement("canvas");
canvas.width = viewport.width;
canvas.height = viewport.height;
canvas.style.display = "block";
wrapper.appendChild(canvas);
containerRef.current?.appendChild(wrapper);
const ctx = canvas.getContext("2d");
if (!ctx) continue;
const task = page.render({ canvasContext: ctx, viewport });
try {
await task.promise;
} catch (e: unknown) {
if (
(e as { name?: string })?.name !==
"RenderingCancelledException"
) {
console.error("PDF render error", e);
}
continue;
}
const textLayerDiv = document.createElement("div");
textLayerDiv.className = "pdf-text-layer";
textLayerDiv.style.position = "absolute";
textLayerDiv.style.left = "0";
textLayerDiv.style.top = "0";
textLayerDiv.style.width = `${viewport.width}px`;
textLayerDiv.style.height = `${viewport.height}px`;
textLayerDiv.style.setProperty("--scale-factor", String(scale));
wrapper.appendChild(textLayerDiv);
const textLayer = new lib.TextLayer({
textContentSource: page.streamTextContent(),
container: textLayerDiv,
viewport,
});
await textLayer.render();
const textDivs = textLayer.textDivs;
renderedPagesRef.current.push({
page,
viewport,
wrapper,
canvas,
textDivs,
});
}
// Apply highlights across all entries, then scroll to the first hit.
let targetPage: number | null = null;
if (list.length) {
targetPage = await applyHighlights(list);
if (targetPage === null) {
// Fallback: scroll to the first entry's page hint, even without a highlight
const hint = list.find((e) => e.page)?.page ?? null;
targetPage = hint;
}
}
if (targetPage && targetPage >= 1) {
scrollToHighlightOnPage(targetPage);
} else if (!hasCitation && scrollToPage && scrollToPage > 1) {
// Restore scroll position after zoom re-render
const pageEntry = renderedPagesRef.current[scrollToPage - 1];
if (pageEntry)
pageEntry.wrapper.scrollIntoView({
behavior: "instant" as ScrollBehavior,
block: "start",
});
}
reveal();
},
[applyHighlights],
);
// Scroll so the first highlight on `pageNum` lands at the vertical center
// of the viewer. We compute the scroll position explicitly on the scroll
// container — calling `scrollIntoView` on a child of the absolutely-
// positioned text layer can scroll just the overlay while leaving the
// canvas untouched, which is why we don't use it here.
function scrollToHighlightOnPage(pageNum: number) {
const pageEntry = renderedPagesRef.current[pageNum - 1];
const scrollEl = scrollContainerRef.current;
if (!pageEntry || !scrollEl) return;
const highlightEl = pageEntry.wrapper.querySelector<HTMLElement>(
".pdf-text-highlight",
);
if (highlightEl) {
const containerRect = scrollEl.getBoundingClientRect();
const highlightRect = highlightEl.getBoundingClientRect();
const offsetWithinContainer = highlightRect.top - containerRect.top;
const targetTop =
scrollEl.scrollTop +
offsetWithinContainer -
scrollEl.clientHeight / 2 +
highlightRect.height / 2;
scrollEl.scrollTo({
top: Math.max(0, targetTop),
behavior: "instant" as ScrollBehavior,
});
} else {
const wrapperRect = pageEntry.wrapper.getBoundingClientRect();
const containerRect = scrollEl.getBoundingClientRect();
const targetTop =
scrollEl.scrollTop + (wrapperRect.top - containerRect.top);
scrollEl.scrollTo({
top: Math.max(0, targetTop),
behavior: "instant" as ScrollBehavior,
});
}
}
const rehighlightQuotes = useCallback(
async (list: QuoteEntry[]) => {
const targetPage = await applyHighlights(list);
const scrollPage =
targetPage ?? list.find((e) => e.page)?.page ?? null;
if (scrollPage && scrollPage >= 1) {
scrollToHighlightOnPage(scrollPage);
}
},
[applyHighlights],
);
// Trackpad pinch-to-zoom (wheel + ctrlKey)
useEffect(() => {
const el = scrollContainerRef.current;
if (!el) return;
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
const handleWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return;
e.preventDefault();
const delta = e.deltaMode === 0 ? e.deltaY / 300 : e.deltaY * 0.1;
const next = Math.min(
ZOOM_MAX,
Math.max(
ZOOM_MIN,
Math.round(zoomRef.current * Math.exp(-delta) * 100) / 100,
),
);
if (next === zoomRef.current) return;
zoomRef.current = next;
setZoom(next);
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
if (pdfDocRef.current) {
renderPDF(
pdfDocRef.current,
quoteListRef.current,
currentPageRef.current,
);
}
}, 150);
};
el.addEventListener("wheel", handleWheel, { passive: false });
return () => {
el.removeEventListener("wheel", handleWheel);
if (debounceTimer) clearTimeout(debounceTimer);
};
}, [renderPDF]);
// Touch pinch-to-zoom
useEffect(() => {
const el = scrollContainerRef.current;
if (!el) return;
let initialDist = 0;
let initialZoom = 1.0;
function getTouchDist(touches: TouchList) {
const dx = touches[0].clientX - touches[1].clientX;
const dy = touches[0].clientY - touches[1].clientY;
return Math.hypot(dx, dy);
}
const handleTouchStart = (e: TouchEvent) => {
if (e.touches.length === 2) {
initialDist = getTouchDist(e.touches);
initialZoom = zoomRef.current;
}
};
const handleTouchMove = (e: TouchEvent) => {
if (e.touches.length !== 2 || initialDist === 0) return;
e.preventDefault();
const next = Math.min(
ZOOM_MAX,
Math.max(
ZOOM_MIN,
Math.round(
initialZoom *
(getTouchDist(e.touches) / initialDist) *
100,
) / 100,
),
);
zoomRef.current = next;
setZoom(next);
};
const handleTouchEnd = (e: TouchEvent) => {
if (e.touches.length < 2 && initialDist > 0) {
initialDist = 0;
if (pdfDocRef.current) {
renderPDF(
pdfDocRef.current,
quoteListRef.current,
currentPageRef.current,
);
}
}
};
el.addEventListener("touchstart", handleTouchStart, { passive: true });
el.addEventListener("touchmove", handleTouchMove, { passive: false });
el.addEventListener("touchend", handleTouchEnd, { passive: true });
return () => {
el.removeEventListener("touchstart", handleTouchStart);
el.removeEventListener("touchmove", handleTouchMove);
el.removeEventListener("touchend", handleTouchEnd);
};
}, [renderPDF]);
// Clean up PDF.js static font-measurement canvases on unmount
useEffect(() => {
return () => {
getPdfJs().then((lib) => lib.TextLayer.cleanup());
};
}, []);
// Render PDF when fetch result arrives
useEffect(() => {
if (!result || result.type !== "pdf") return;
pdfDocRef.current = null;
renderedPagesRef.current = [];
quoteListRef.current = quoteList;
zoomRef.current = 1.0;
setZoom(1.0);
setNumPages(0);
const list = quoteList;
let cancelled = false;
(async () => {
const lib = await getPdfJs();
if (cancelled) return;
const pdfDoc = await lib.getDocument({
data: new Uint8Array(result.buffer),
standardFontDataUrl: STANDARD_FONT_DATA_URL,
}).promise;
if (cancelled) return;
pdfDocRef.current = pdfDoc;
await renderPDF(pdfDoc, list);
})();
return () => {
cancelled = true;
};
}, [result, renderPDF]); // eslint-disable-line react-hooks/exhaustive-deps
// Re-render at new scale when container is resized (debounced 150ms)
useEffect(() => {
if (!pdfDocRef.current) return;
const timer = setTimeout(() => {
if (pdfDocRef.current) {
renderPDF(pdfDocRef.current, quoteListRef.current);
}
}, 150);
return () => clearTimeout(timer);
}, [containerWidth, renderPDF]); // eslint-disable-line react-hooks/exhaustive-deps
// Re-highlight when quotes change without full re-render
useEffect(() => {
if (!pdfDocRef.current) return;
quoteListRef.current = quoteList;
if (quoteList.length === 0) return;
rehighlightQuotes(quoteList);
}, [quoteKey, rehighlightQuotes]); // eslint-disable-line react-hooks/exhaustive-deps
function handleZoomIn() {
const next = Math.min(
ZOOM_MAX,
Math.round((zoomRef.current + ZOOM_STEP) * 100) / 100,
);
zoomRef.current = next;
setZoom(next);
if (pdfDocRef.current) {
renderPDF(
pdfDocRef.current,
quoteListRef.current,
currentPageRef.current,
);
}
}
function handleZoomOut() {
const next = Math.max(
ZOOM_MIN,
Math.round((zoomRef.current - ZOOM_STEP) * 100) / 100,
);
zoomRef.current = next;
setZoom(next);
if (pdfDocRef.current) {
renderPDF(
pdfDocRef.current,
quoteListRef.current,
currentPageRef.current,
);
}
}
if (fallbackToDocx && doc?.document_id) {
return (
<DocxView
documentId={doc.document_id}
quotes={quotes}
/>
);
}
return (
<div
className={`relative flex flex-col flex-1 overflow-hidden ${bordered ? "border border-gray-200" : ""} ${rounded ? "rounded-xl" : ""}`}
>
<div
ref={scrollContainerRef}
className="flex-1 overflow-auto bg-gray-100 px-3 pt-5 pb-3"
>
{loading && (
<div className="flex h-full items-center justify-center">
<MikeIcon spin mike size={28} />
</div>
)}
{error && (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-red-500">{error}</p>
</div>
)}
<div ref={containerRef} />
</div>
{numPages > 0 && (
<>
{/* Page counter — bottom left */}
<div className="absolute bottom-4 left-4 pointer-events-none">
<span className="flex items-center px-3 py-1.5 rounded-full text-xs font-medium tabular-nums text-gray-700 bg-white/25 backdrop-blur-md border border-white/30 shadow-md">
{currentPage}/{numPages}
</span>
</div>
{/* Zoom controls — bottom right */}
<div className="absolute bottom-4 right-4 flex items-center gap-px rounded-full bg-white/25 backdrop-blur-md border border-white/30 shadow-md px-1 py-1">
<button
onClick={handleZoomOut}
disabled={zoom <= ZOOM_MIN}
className="flex items-center justify-center w-7 h-7 rounded-full text-gray-600 hover:bg-white/80 disabled:opacity-30 transition-colors"
>
<ZoomOut className="h-3.5 w-3.5" />
</button>
<span className="text-xs font-medium text-gray-600 tabular-nums w-9 text-center select-none">
{Math.round(zoom * 100)}%
</span>
<button
onClick={handleZoomIn}
disabled={zoom >= ZOOM_MAX}
className="flex items-center justify-center w-7 h-7 rounded-full text-gray-600 hover:bg-white/80 disabled:opacity-30 transition-colors"
>
<ZoomIn className="h-3.5 w-3.5" />
</button>
</div>
</>
)}
</div>
);
}

View file

@ -0,0 +1,101 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { Download, Trash2, X } from "lucide-react";
import { DocView } from "./DocView";
import { getDocumentUrl } from "@/app/lib/mikeApi";
import type { MikeDocument } from "./types";
interface Props {
doc: MikeDocument | null;
/** Optional specific version to display. Only honoured for DOCX. */
versionId?: string | null;
/** Optional label suffix for the header (e.g. "V3"). */
versionLabel?: string | null;
onClose: () => void;
onDelete?: (doc: MikeDocument) => void;
}
export function DocViewModal({
doc,
versionId,
versionLabel,
onClose,
onDelete,
}: Props) {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!doc || !mounted) return null;
async function handleDownload() {
if (!doc) return;
const { url, filename } = await getDocumentUrl(doc.id, versionId ?? null);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
}
return createPortal(
<div
className="fixed inset-0 z-100 flex items-center justify-center bg-black/40"
onClick={onClose}
>
<div
className="relative flex flex-col bg-white rounded-xl shadow-2xl w-[800px] max-w-[90vw] h-[90vh]"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between px-5 py-3 shrink-0">
<span className="text-base font-medium font-serif text-gray-800 truncate pr-4">
{doc.filename}
{versionLabel && (
<span className="ml-2 text-xs font-normal text-gray-500">
{versionLabel}
</span>
)}
</span>
<div className="flex items-center gap-1 shrink-0">
<button
onClick={handleDownload}
className="flex items-center justify-center w-6 h-6 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-700 transition-colors"
>
<Download className="h-4 w-4" />
</button>
{onDelete && (
<button
onClick={() => { onDelete(doc); onClose(); }}
className="flex items-center justify-center w-6 h-6 rounded hover:bg-red-50 text-gray-400 hover:text-red-500 transition-colors"
>
<Trash2 className="h-4 w-4" />
</button>
)}
<button
onClick={onClose}
className="flex items-center justify-center w-6 h-6 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-700 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
{/* DocView serves PDF when available and falls back to
docx-preview internally if the active version has no
PDF rendition. Passing no versionId tells the backend
to resolve the latest tracked-changes version. */}
<div className="flex flex-col flex-1 overflow-hidden px-3 pb-3">
<DocView
key={versionId ?? "current"}
doc={{
document_id: doc.id,
version_id: versionId ?? null,
}}
/>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,86 @@
"use client";
import { FileText, File, X, AlertCircle, Loader2 } from "lucide-react";
import type { MikeDocument } from "./types";
interface Props {
document: MikeDocument;
onRemove?: (id: string) => void;
onClick?: (doc: MikeDocument) => void;
selected?: boolean;
}
function FileIcon({ fileType }: { fileType: string | null }) {
if (fileType === "pdf") {
return <FileText className="h-4 w-4 text-red-600 shrink-0" />;
}
if (fileType === "docx" || fileType === "doc") {
return <File className="h-4 w-4 text-blue-600 shrink-0" />;
}
return <File className="h-4 w-4 text-gray-500 shrink-0" />;
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export function DocumentCard({ document, onRemove, onClick, selected }: Props) {
const isError = document.status === "error";
const isProcessing = document.status === "pending" || document.status === "processing";
return (
<div
onClick={() => onClick?.(document)}
className={[
"flex items-center gap-2.5 rounded-lg border px-3 py-2.5 text-sm transition-colors",
onClick ? "cursor-pointer" : "",
selected
? "border-blue-500 bg-blue-50"
: isError
? "border-red-200 bg-red-50"
: "border-gray-200 bg-white hover:border-gray-300",
].join(" ")}
>
{isProcessing ? (
<Loader2 className="h-4 w-4 animate-spin text-gray-400 shrink-0" />
) : isError ? (
<AlertCircle className="h-4 w-4 text-red-500 shrink-0" />
) : (
<FileIcon fileType={document.file_type} />
)}
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-gray-800" title={document.filename}>
{document.filename}
</p>
<p className="text-xs text-gray-400">
{isProcessing
? "Processing…"
: isError
? "Upload failed"
: [
document.size_bytes != null ? formatBytes(document.size_bytes) : null,
document.page_count ? `${document.page_count}p` : null,
]
.filter(Boolean)
.join(" · ")}
</p>
</div>
{onRemove && !isProcessing && (
<button
onClick={(e) => {
e.stopPropagation();
onRemove(document.id);
}}
className="shrink-0 rounded p-0.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
aria-label="Remove document"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
);
}

View file

@ -0,0 +1,509 @@
"use client";
import { useEffect, useMemo, useRef } from "react";
import { MikeIcon } from "@/components/chat/mike-icon";
import { useFetchDocxBytes } from "@/app/hooks/useFetchDocxBytes";
import { supabase } from "@/lib/supabase";
import {
clearDocxQuoteHighlights,
highlightDocxQuote,
} from "./highlightDocxQuote";
import type { CitationQuote } from "./types";
interface Props {
documentId: string;
versionId?: string | null;
/**
* Called once the document has been rendered to the DOM. Handy for
* scrolling to a particular tracked change after a re-render.
*/
onReady?: () => void;
/**
* Tracked-change to scroll to + briefly flash after each render. The
* `key` is used to re-trigger scrolling when the same edit is clicked
* twice in a row.
*/
highlightEdit?: {
key: string;
inserted_text?: string;
deleted_text?: string;
/**
* Numeric w:id values of the <w:ins>/<w:del> wrappers in
* document.xml. Preferred over text matching uniquely identifies
* the right DOM element even when multiple edits share identical
* inserted/deleted text. `docx-preview` drops these during parsing,
* so we re-tag each rendered <ins>/<del> with data-w-id after load.
*/
ins_w_id?: string | null;
del_w_id?: string | null;
} | null;
/**
* Forces a byte re-fetch when it changes, even if documentId/versionId
* are stable. Used after accept/reject: the backend overwrites bytes at
* the same storage path (no new version row), so the hook has no other
* signal that the file changed.
*/
refetchKey?: number;
/**
* Citation quotes to highlight in the rendered output. The first match
* is scrolled into view. Page numbers are ignored DOCX has no explicit
* pagination the renderer can match against.
*/
quotes?: CitationQuote[];
/**
* Warning banner copy rendered in the top-left of the viewer. Used
* for non-blocking errors (e.g. "Accept failed — reverted").
*/
warning?: string | null;
/**
* Called when the user dismisses the warning banner.
*/
onWarningDismiss?: () => void;
/**
* Scroll position to restore after the first render used by parents
* that track per-tab scroll and want to re-enter at the same spot.
* Null/undefined means "no override" (preserve the pre-render scroll).
*/
initialScrollTop?: number | null;
/**
* Fires on scroll (throttled by rAF) so the parent can persist the
* current scrollTop against its tab state.
*/
onScrollChange?: (scrollTop: number) => void;
rounded?: boolean;
bordered?: boolean;
}
function findEditElement(
root: HTMLElement,
tag: "ins" | "del",
opts: { w_id?: string | null; text?: string },
): HTMLElement | null {
if (opts.w_id) {
const byId = root.querySelector(
`${tag}[data-w-id="${CSS.escape(opts.w_id)}"]`,
) as HTMLElement | null;
if (byId) return byId;
}
const text = opts.text ?? "";
const normalize = (s: string) => s.replace(/\s+/g, " ").trim();
const target = normalize(text);
if (!target) return null;
const candidates = Array.from(root.querySelectorAll(tag)) as HTMLElement[];
return (
candidates.find((el) => normalize(el.textContent ?? "") === target) ??
candidates.find((el) =>
normalize(el.textContent ?? "").includes(target),
) ??
null
);
}
function scrollToHighlight(
container: HTMLElement,
scrollEl: HTMLElement,
edit: {
inserted_text?: string;
deleted_text?: string;
ins_w_id?: string | null;
del_w_id?: string | null;
},
) {
const insEl = findEditElement(container, "ins", {
w_id: edit.ins_w_id,
text: edit.inserted_text,
});
const delEl = findEditElement(container, "del", {
w_id: edit.del_w_id,
text: edit.deleted_text,
});
const anchor = insEl ?? delEl;
if (!anchor) return;
const scrollRect = scrollEl.getBoundingClientRect();
const targetRect = anchor.getBoundingClientRect();
const offset = targetRect.top - scrollRect.top + scrollEl.scrollTop - 80;
scrollEl.scrollTo({ top: Math.max(0, offset), behavior: "smooth" });
const flashed = [insEl, delEl].filter((el): el is HTMLElement => !!el);
flashed.forEach((el) => el.classList.add("docx-edit-flash"));
window.setTimeout(() => {
flashed.forEach((el) => el.classList.remove("docx-edit-flash"));
}, 2000);
}
/**
* Fetch the ordered list of w:ids for every w:ins/w:del in the current
* version and tag each rendered <ins>/<del> with data-w-id. The backend
* returns ids in document order, and docx-preview emits <ins>/<del>
* in the same order, so we can align by index.
*/
async function tagWIdsOnRenderedDom(
container: HTMLElement,
documentId: string,
versionId: string | null | undefined,
): Promise<void> {
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3001";
const qs = versionId
? `?version_id=${encodeURIComponent(versionId)}`
: "";
const resp = await fetch(
`${apiBase}/single-documents/${documentId}/tracked-change-ids${qs}`,
{ headers: token ? { Authorization: `Bearer ${token}` } : {} },
);
if (!resp.ok) {
console.warn(
"[DocxView] tracked-change-ids fetch failed",
resp.status,
);
return;
}
const data = (await resp.json()) as {
ids: { kind: "ins" | "del"; w_id: string }[];
};
const domEls = Array.from(
container.querySelectorAll("ins, del"),
) as HTMLElement[];
const ids = data.ids ?? [];
let tagged = 0;
let mismatched = 0;
for (let i = 0; i < Math.min(domEls.length, ids.length); i++) {
const el = domEls[i];
const info = ids[i];
if (el.tagName.toLowerCase() !== info.kind) {
mismatched++;
continue;
}
el.setAttribute("data-w-id", info.w_id);
tagged++;
}
} catch (e) {
console.warn("[DocxView] tagWIdsOnRenderedDom failed", e);
}
}
/**
* Renders a .docx in the browser using `docx-preview`. Tracked changes
* (`w:ins` / `w:del`) show up automatically with coloured strike/underline
* styling. Scroll position is preserved across re-renders so Accept/Reject
* doesn't jump the user back to the top.
*/
export function DocxView({
documentId,
versionId,
onReady,
highlightEdit,
refetchKey,
quotes,
warning,
onWarningDismiss,
initialScrollTop,
onScrollChange,
rounded = true,
bordered = true,
}: Props) {
const scrollRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const lastScrollTopRef = useRef(0);
const renderKeyRef = useRef(0);
// Ref-stabilize onReady and highlightEdit so the render effect only
// re-fires when `bytes` actually change. Without this, any parent
// re-render (e.g. clicking a new highlight) creates a new onReady
// identity, triggers a full re-render, and snaps scroll back to top.
const onReadyRef = useRef(onReady);
onReadyRef.current = onReady;
const highlightEditRef = useRef(highlightEdit);
highlightEditRef.current = highlightEdit;
const quotesRef = useRef(quotes);
quotesRef.current = quotes;
const initialScrollTopRef = useRef(initialScrollTop ?? null);
initialScrollTopRef.current = initialScrollTop ?? null;
const onScrollChangeRef = useRef(onScrollChange);
onScrollChangeRef.current = onScrollChange;
// Stable key for the quote list so the re-highlight effect re-fires
// only when the actual text/order of quotes changes.
const quoteKey = useMemo(
() => (quotes ?? []).map((q) => q.quote).join("||"),
[quotes],
);
const { bytes, loading, error } = useFetchDocxBytes(
documentId,
versionId,
refetchKey,
);
/**
* Highlight every quote in `list` inside the rendered DOM and scroll
* the first match into view. Returns true if any match was found.
*/
const applyQuoteHighlights = (
containerEl: HTMLElement,
scrollEl: HTMLElement,
list: CitationQuote[] | undefined,
): boolean => {
clearDocxQuoteHighlights(containerEl);
if (!list || list.length === 0) return false;
let firstMatch: HTMLElement | null = null;
for (const q of list) {
const match = highlightDocxQuote(containerEl, q.quote);
if (match && !firstMatch) firstMatch = match;
}
if (!firstMatch) return false;
const scrollRect = scrollEl.getBoundingClientRect();
const targetRect = firstMatch.getBoundingClientRect();
const offset =
targetRect.top -
scrollRect.top +
scrollEl.scrollTop -
scrollEl.clientHeight / 2 +
targetRect.height / 2;
scrollEl.scrollTo({
top: Math.max(0, offset),
behavior: "instant" as ScrollBehavior,
});
return true;
};
/**
* docx-preview renders pages at their natural Word page width (e.g.
* ~816px for US Letter). When the side-panel is narrower than that,
* the page overflows horizontally. Apply CSS `zoom` on each
* section.docx so the document shrinks to fit `zoom` (unlike
* `transform: scale`) also shrinks the layout box, so the scroll
* container's scrollHeight adapts. We zoom each page rather than the
* wrapper because docx-preview injects flex styles on `.docx-wrapper`
* that can interfere with wrapper-level zoom.
*/
const applyDocxScale = () => {
const containerEl = containerRef.current;
const scrollEl = scrollRef.current;
if (!containerEl || !scrollEl) return;
const wrapper = containerEl.querySelector<HTMLElement>(".docx-wrapper");
if (!wrapper) return;
const sections = Array.from(
wrapper.querySelectorAll<HTMLElement>("section.docx"),
);
if (sections.length === 0) return;
// Reset zoom on every page before measuring so offsetWidth reports
// each page's natural width (pages can have different widths — e.g.
// mixed portrait/landscape sections).
sections.forEach((s) => {
s.style.zoom = "1";
});
// Use the scroll container's content box (clientWidth - padding)
// as the available width.
const styles = window.getComputedStyle(scrollEl);
const padX =
(parseFloat(styles.paddingLeft) || 0) +
(parseFloat(styles.paddingRight) || 0);
const available = scrollEl.clientWidth - padX;
if (available <= 0) return;
// Scale each page independently against its own natural width so
// landscape/custom-size pages still fit without distorting the
// page dividers.
sections.forEach((s) => {
const w = s.offsetWidth;
if (!w) return;
const scale = Math.min(1, available / w);
s.style.zoom = String(scale);
});
};
// Observe the scroll container (which tracks the side panel's width)
// and re-scale whenever it resizes. Also observe the docx container so
// we re-scale once docx-preview finishes inserting pages.
useEffect(() => {
const scrollEl = scrollRef.current;
const containerEl = containerRef.current;
if (!scrollEl || !containerEl) return;
let raf = 0;
const schedule = () => {
if (raf) cancelAnimationFrame(raf);
raf = requestAnimationFrame(() => applyDocxScale());
};
const ro = new ResizeObserver(schedule);
ro.observe(scrollEl);
ro.observe(containerEl);
return () => {
if (raf) cancelAnimationFrame(raf);
ro.disconnect();
};
}, []);
useEffect(() => {
let cancelled = false;
if (!bytes || !containerRef.current || !scrollRef.current) return;
const scrollEl = scrollRef.current;
const containerEl = containerRef.current;
console.log("[DocxView] render effect fired", {
documentId,
versionId,
refetchKey,
bytesLen: bytes.byteLength,
});
// Remember scroll position across re-renders so Accept/Reject stays put.
lastScrollTopRef.current = scrollEl.scrollTop;
const thisRender = ++renderKeyRef.current;
(async () => {
try {
const { renderAsync } = await import("docx-preview");
if (cancelled) return;
containerEl.innerHTML = "";
await renderAsync(bytes, containerEl, undefined, {
inWrapper: true,
ignoreWidth: false,
ignoreHeight: false,
renderChanges: true,
experimental: true,
});
if (cancelled) return;
await tagWIdsOnRenderedDom(
containerEl,
documentId,
versionId ?? null,
);
if (cancelled) return;
// Scale to fit before scrolling so offsets are computed
// against the post-zoom layout.
applyDocxScale();
requestAnimationFrame(() => {
if (
!scrollRef.current ||
thisRender !== renderKeyRef.current
)
return;
const pendingHighlight = highlightEditRef.current;
const pendingQuotes = quotesRef.current;
const pendingInitialScroll = initialScrollTopRef.current;
if (pendingHighlight) {
scrollToHighlight(
containerEl,
scrollRef.current,
pendingHighlight,
);
// Highlight quotes too, but don't override the edit scroll
if (pendingQuotes?.length) {
for (const q of pendingQuotes)
highlightDocxQuote(containerEl, q.quote);
}
} else if (
pendingQuotes &&
applyQuoteHighlights(
containerEl,
scrollRef.current,
pendingQuotes,
)
) {
// scrolled inside applyQuoteHighlights
} else if (typeof pendingInitialScroll === "number") {
scrollRef.current.scrollTop = pendingInitialScroll;
} else {
scrollRef.current.scrollTop = lastScrollTopRef.current;
}
onReadyRef.current?.();
});
} catch (e) {
console.error("docx-preview render failed", e);
}
})();
return () => {
cancelled = true;
};
}, [bytes]);
// Re-scroll/highlight if the target edit changes without a re-render
// (e.g. same doc, different edit clicked).
useEffect(() => {
if (!highlightEdit || !containerRef.current || !scrollRef.current)
return;
scrollToHighlight(
containerRef.current,
scrollRef.current,
highlightEdit,
);
}, [highlightEdit?.key]); // eslint-disable-line react-hooks/exhaustive-deps
// Re-apply quote highlights when the quote list changes without a full
// re-render (e.g. clicking a different citation on the same doc).
useEffect(() => {
if (!containerRef.current || !scrollRef.current) return;
applyQuoteHighlights(
containerRef.current,
scrollRef.current,
quotesRef.current,
);
}, [quoteKey]); // eslint-disable-line react-hooks/exhaustive-deps
// Fire onScrollChange (rAF-throttled) so parents can persist scroll
// per-tab. We still maintain lastScrollTopRef locally for same-mount
// re-renders (Accept/Reject preserving scroll within one view).
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
let scheduled = false;
const onScroll = () => {
lastScrollTopRef.current = el.scrollTop;
if (scheduled) return;
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
onScrollChangeRef.current?.(el.scrollTop);
});
};
el.addEventListener("scroll", onScroll, { passive: true });
return () => el.removeEventListener("scroll", onScroll);
}, []);
return (
<div
className={`relative flex flex-col flex-1 overflow-hidden ${bordered ? "border border-gray-200" : ""} ${rounded ? "rounded-xl" : ""}`}
>
{warning && (
<div className="absolute top-2 left-2 z-10 flex items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-2 py-1 text-xs text-amber-800 shadow-sm">
<span>{warning}</span>
<button
type="button"
onClick={() => onWarningDismiss?.()}
className="text-amber-600 hover:text-amber-900"
aria-label="Dismiss warning"
>
×
</button>
</div>
)}
<div
ref={scrollRef}
className="flex-1 overflow-auto bg-gray-100 px-5 pt-5 pb-3 docx-view-scroll"
data-document-id={documentId}
data-version-id={versionId ?? ""}
>
{loading && !bytes && (
<div className="flex h-full items-center justify-center">
<MikeIcon spin mike size={28} />
</div>
)}
{error && (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-red-500">{error}</p>
</div>
)}
<div ref={containerRef} className="docx-view-container" />
</div>
</div>
);
}

View file

@ -0,0 +1,117 @@
"use client";
import { useState } from "react";
import { X } from "lucide-react";
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
interface Props {
emails: string[];
onChange: (emails: string[]) => void;
validate?: (email: string) => Promise<string | null>;
onValidatingChange?: (validating: boolean) => void;
placeholder?: string;
autoFocus?: boolean;
}
export function EmailPillInput({
emails,
onChange,
validate,
onValidatingChange,
placeholder = "Add by email…",
autoFocus = false,
}: Props) {
const [input, setInput] = useState("");
const [validating, setValidating] = useState(false);
const [error, setError] = useState<string | null>(null);
function setValidatingState(v: boolean) {
setValidating(v);
onValidatingChange?.(v);
}
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
addEmail();
} else if (e.key === "Backspace" && !input && emails.length > 0) {
onChange(emails.slice(0, -1));
}
}
async function addEmail() {
const email = input.trim().toLowerCase();
if (!email) return;
if (emails.includes(email)) {
setInput("");
return;
}
if (!EMAIL_RE.test(email)) {
setError("Enter a valid email address.");
return;
}
if (validate) {
setValidatingState(true);
setError(null);
try {
const err = await validate(email);
if (err) {
setError(err);
return;
}
} catch {
setError("Could not verify email. Try again.");
return;
} finally {
setValidatingState(false);
}
}
onChange([...emails, email]);
setInput("");
setError(null);
}
return (
<div>
<div
className={`flex flex-wrap gap-1.5 rounded-lg border bg-gray-50 px-3 py-2 min-h-[40px] transition-colors ${
error
? "border-red-300 focus-within:border-red-400"
: "border-gray-200 focus-within:border-gray-400"
}`}
>
{emails.map((email) => (
<span
key={email}
className="inline-flex items-center gap-1 rounded-full bg-gray-200 px-2.5 py-0.5 text-xs text-gray-700"
>
{email}
<button
type="button"
onClick={() => onChange(emails.filter((e) => e !== email))}
className="text-gray-400 hover:text-gray-700 transition-colors"
>
<X className="h-3 w-3" />
</button>
</span>
))}
<input
type="email"
value={input}
onChange={(e) => {
setInput(e.target.value);
setError(null);
}}
onKeyDown={handleKeyDown}
onBlur={addEmail}
placeholder={emails.length === 0 ? placeholder : ""}
className="flex-1 min-w-[160px] bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus={autoFocus}
/>
</div>
{error && <p className="mt-1.5 text-xs text-red-500">{error}</p>}
{validating && <p className="mt-1.5 text-xs text-gray-400">Checking</p>}
</div>
);
}

View file

@ -0,0 +1,334 @@
"use client";
import { useState } from "react";
import {
Check,
ChevronDown,
ChevronRight,
File,
FileText,
Folder,
Trash2,
} from "lucide-react";
import type { MikeDocument, MikeProject } from "./types";
import { VersionChip } from "./VersionChip";
function formatDate(iso: string | null) {
if (!iso) return null;
return new Date(iso).toLocaleDateString(undefined, {
day: "numeric",
month: "short",
year: "numeric",
});
}
export function DocFileIcon({ fileType }: { fileType: string | null }) {
if (fileType === "pdf")
return <FileText className="h-3.5 w-3.5 text-red-500 shrink-0" />;
return <File className="h-3.5 w-3.5 text-blue-500 shrink-0" />;
}
interface FileDirectoryProps {
standaloneDocs: MikeDocument[];
directoryProjects: MikeProject[];
loading: boolean;
selectedIds: Set<string>;
onChange: (ids: Set<string>) => void;
allowMultiple?: boolean;
forceExpanded?: boolean;
emptyMessage?: string;
heading?: string;
onDelete?: (ids: string[]) => void | Promise<void>;
}
export function FileDirectory({
standaloneDocs,
directoryProjects,
loading,
selectedIds,
onChange,
allowMultiple = true,
forceExpanded = false,
emptyMessage = "No documents yet",
heading = "Documents",
onDelete,
}: FileDirectoryProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(
new Set(),
);
const [deleting, setDeleting] = useState(false);
const selectedCount = selectedIds.size;
async function handleDelete() {
if (!onDelete || selectedCount === 0 || deleting) return;
const ids = Array.from(selectedIds);
setDeleting(true);
try {
await onDelete(ids);
const next = new Set(selectedIds);
ids.forEach((id) => next.delete(id));
onChange(next);
} finally {
setDeleting(false);
}
}
const allDocs = [
...standaloneDocs,
...directoryProjects.flatMap((p) => p.documents ?? []),
];
const allStandaloneSelected =
standaloneDocs.length > 0 &&
standaloneDocs.every((d) => selectedIds.has(d.id));
function toggle(docId: string) {
if (!allowMultiple) {
onChange(new Set([docId]));
return;
}
const next = new Set(selectedIds);
next.has(docId) ? next.delete(docId) : next.add(docId);
onChange(next);
}
function toggleAll() {
if (allStandaloneSelected) {
const next = new Set(selectedIds);
standaloneDocs.forEach((d) => next.delete(d.id));
onChange(next);
} else {
const next = new Set(selectedIds);
standaloneDocs.forEach((d) => next.add(d.id));
onChange(next);
}
}
function toggleFolder(projectId: string) {
if (forceExpanded) return;
setExpandedProjects((prev) => {
const next = new Set(prev);
next.has(projectId) ? next.delete(projectId) : next.add(projectId);
return next;
});
}
if (loading) {
return (
<div className="rounded-sm border border-gray-100 overflow-hidden">
{/* Documents header skeleton */}
<div className="flex items-center justify-between px-2 py-2">
<div className="h-3 w-20 rounded bg-gray-200 animate-pulse" />
<div className="h-3 w-12 rounded bg-gray-200 animate-pulse" />
</div>
{/* File rows skeleton */}
<div>
{[60, 45, 75, 55, 40].map((w, i) => (
<div
key={i}
className="flex items-center gap-2 px-2 py-2"
>
<div className="h-3.5 w-3.5 rounded border border-gray-200 shrink-0" />
<div className="h-3.5 w-3.5 rounded bg-gray-200 animate-pulse shrink-0" />
<div
className="h-3 rounded bg-gray-200 animate-pulse"
style={{ width: `${w}%` }}
/>
</div>
))}
</div>
</div>
);
}
if (allDocs.length === 0 && directoryProjects.length === 0) {
return (
<p className="text-center text-sm text-gray-400 py-8">
{emptyMessage}
</p>
);
}
return (
<div className="rounded-sm border border-gray-100 overflow-hidden">
<div>
{(standaloneDocs.length > 0 ||
(onDelete && selectedCount > 0)) && (
<div className="flex items-center justify-between px-2 py-2">
<p className="text-xs font-medium text-gray-400">
{heading}
</p>
<div className="flex items-center gap-3">
{onDelete && selectedCount > 0 && (
<button
type="button"
onClick={handleDelete}
disabled={deleting}
className="inline-flex items-center gap-1 text-xs text-red-500 hover:text-red-700 transition-colors disabled:opacity-50"
>
<Trash2 className="h-3 w-3" />
Delete
</button>
)}
{standaloneDocs.length > 0 && (
<button
type="button"
onClick={toggleAll}
className="text-xs text-gray-400 hover:text-gray-600 transition-colors"
>
{allStandaloneSelected
? "Deselect all"
: "Select all"}
</button>
)}
</div>
</div>
)}
{standaloneDocs.map((doc) => {
const selected = selectedIds.has(doc.id);
return (
<button
type="button"
key={doc.id}
onClick={() => toggle(doc.id)}
className={`w-full flex items-center gap-2 px-2 py-2 text-xs transition-colors text-left ${
selected ? "bg-gray-100" : "hover:bg-gray-50"
}`}
>
<span
className={`shrink-0 h-3.5 w-3.5 rounded border flex items-center justify-center ${
selected
? "bg-gray-900 border-gray-900"
: "border-gray-300"
}`}
>
{selected && (
<Check className="h-2.5 w-2.5 text-white" />
)}
</span>
<DocFileIcon fileType={doc.file_type} />
<span
className={`flex-1 truncate ${
selected ? "text-gray-900" : "text-gray-700"
}`}
>
{doc.filename}
</span>
<VersionChip n={doc.latest_version_number} />
{doc.created_at && (
<span className="shrink-0 text-gray-300">
{formatDate(doc.created_at)}
</span>
)}
</button>
);
})}
{standaloneDocs.length > 0 && directoryProjects.length > 0 && (
<div className="border-t border-gray-100 py-2 px-2">
<p className="text-xs font-medium text-gray-400">
Projects
</p>
</div>
)}
{directoryProjects.map((project) => {
const isExpanded =
forceExpanded || expandedProjects.has(project.id);
const docs = project.documents ?? [];
return (
<div key={project.id}>
<button
type="button"
onClick={() => toggleFolder(project.id)}
className="w-full flex items-center gap-2 px-2 py-2 text-xs hover:bg-gray-50 transition-colors text-left"
>
{isExpanded ? (
<ChevronDown className="h-3 w-3 text-gray-400 shrink-0" />
) : (
<ChevronRight className="h-3 w-3 text-gray-400 shrink-0" />
)}
<Folder className="h-3.5 w-3.5 shrink-0 text-gray-400" />
<span className="flex-1 truncate font-medium text-gray-700">
{project.name}
{project.cm_number && (
<span className="ml-1 font-normal text-gray-400">
(#{project.cm_number})
</span>
)}
</span>
<span className="text-xs text-gray-400 shrink-0">
{docs.length}
</span>
</button>
{isExpanded && (
<div>
{docs.length === 0 ? (
<p className="pl-7 py-1 text-xs text-gray-400">
Empty
</p>
) : (
docs.map((doc) => {
const selected = selectedIds.has(
doc.id,
);
return (
<button
type="button"
key={doc.id}
onClick={() =>
toggle(doc.id)
}
className={`w-full flex items-center gap-2 pl-7 pr-2 py-2 text-xs transition-colors text-left ${
selected
? "bg-gray-100"
: "hover:bg-gray-50"
}`}
>
<span
className={`shrink-0 h-3.5 w-3.5 rounded border flex items-center justify-center ${
selected
? "bg-gray-900 border-gray-900"
: "border-gray-300"
}`}
>
{selected && (
<Check className="h-2.5 w-2.5 text-white" />
)}
</span>
<DocFileIcon
fileType={doc.file_type}
/>
<span
className={`flex-1 truncate min-w-0 ${
selected
? "text-gray-900 font-medium"
: "text-gray-700"
}`}
>
{doc.filename}
</span>
<VersionChip
n={doc.latest_version_number}
/>
{doc.created_at && (
<span className="shrink-0 text-gray-300">
{formatDate(
doc.created_at,
)}
</span>
)}
</button>
);
})
)}
</div>
)}
</div>
);
})}
</div>
</div>
);
}

View file

@ -0,0 +1,57 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Search, X } from "lucide-react";
interface Props {
value: string;
onChange: (v: string) => void;
placeholder?: string;
}
export function HeaderSearchBtn({ value, onChange, placeholder = "Search…" }: Props) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
onChange("");
}
}
if (open) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [open, onChange]);
return (
<div ref={ref} className="relative flex items-center">
{open ? (
<div className="absolute right-0 top-1/2 -translate-y-1/2 flex items-center gap-2 bg-white border border-gray-200 rounded-lg px-3 py-1.5 shadow-sm z-10 w-72">
<Search className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
autoFocus
type="text"
placeholder={placeholder}
value={value}
onChange={(e) => onChange(e.target.value)}
className="flex-1 text-sm text-gray-700 placeholder:text-gray-400 outline-none bg-transparent"
/>
<button
onClick={() => { setOpen(false); onChange(""); }}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
) : (
<button
onClick={() => setOpen(true)}
className="flex items-center justify-center p-1.5 text-gray-500 hover:text-gray-900 transition-colors"
>
<Search className="h-4 w-4" />
</button>
)}
</div>
);
}

View file

@ -0,0 +1,93 @@
"use client";
import { createPortal } from "react-dom";
import { Lock, X } from "lucide-react";
interface Props {
open: boolean;
onClose: () => void;
/** Short headline above the body, e.g. "Owner-only action". */
title?: string;
/** Sentence describing what the user tried to do. */
action?: string;
/** Email of the project/resource owner, shown so the user knows who to ask. */
ownerEmail?: string | null;
/** Override the default message entirely. */
message?: string;
}
/**
* Lightweight "you don't have permission" modal shown when a non-owner
* attempts an owner-only action (manage people, rename, delete, ) on a
* shared project. Replaces the silent 404 the backend would otherwise
* return so the user understands why the action didn't go through.
*/
export function OwnerOnlyModal({
open,
onClose,
title = "Owner-only action",
action,
ownerEmail,
message,
}: Props) {
if (!open) return null;
const body =
message ??
(action
? `Only the project owner can ${action}.`
: "Only the project owner can perform this action.");
return createPortal(
<div
className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs"
onClick={onClose}
>
<div
className="w-full max-w-md rounded-2xl bg-white shadow-2xl flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-start justify-between gap-3 px-5 pt-5 pb-2">
<div className="flex items-center gap-2">
<Lock className="h-4 w-4 text-amber-600" />
<h2 className="text-base font-medium text-gray-900">
{title}
</h2>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Body */}
<div className="px-5 pb-2 pt-1">
<p className="text-sm text-gray-600 leading-relaxed">
{body}
</p>
{ownerEmail && (
<p className="mt-2 text-xs text-gray-400">
Ask{" "}
<span className="text-gray-600">{ownerEmail}</span>{" "}
if you need access.
</p>
)}
</div>
{/* Footer */}
<div className="flex justify-end gap-2 px-5 pb-5 pt-3">
<button
onClick={onClose}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700"
>
OK
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,364 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { X, User, UserPlus, Loader2, Plus } from "lucide-react";
import type { ProjectPeople } from "@/app/lib/mikeApi";
/**
* Any resource the modal can manage members for projects today, tabular
* reviews now, anything else with a `shared_with` email list later.
*/
export interface SharedResource {
id: string;
shared_with?: string[] | null;
}
interface Props {
open: boolean;
onClose: () => void;
/** The thing being shared (project, review, …). */
resource: SharedResource | null;
/**
* Resolve the owner + members roster for the given resource. Different
* resource types hit different endpoints (`/projects/:id/people`,
* `/tabular-review/:id/people`, ) so the caller passes the appropriate
* fetcher.
*/
fetchPeople: (id: string) => Promise<ProjectPeople>;
/** Currently signed-in user's email — gets the "You" tag if it matches. */
currentUserEmail?: string | null;
breadcrumb: string[];
/**
* Persist a new shared_with list. Parent should PATCH the resource and
* sync its local state on success. Throw to surface an error inline.
*/
onSharedWithChange?: (sharedWith: string[]) => Promise<void> | void;
}
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
type RosterRow = {
email: string;
display_name: string | null;
role: "owner" | "member";
};
/**
* Roster of every Mike member with access to the project, with controls to
* add/remove members. Mirrors AddDocumentsModal's frame.
*/
export function PeopleModal({
open,
onClose,
resource,
fetchPeople,
currentUserEmail,
breadcrumb,
onSharedWithChange,
}: Props) {
const [newEmail, setNewEmail] = useState("");
const [busy, setBusy] = useState<"add" | "remove" | null>(null);
const [removingEmail, setRemovingEmail] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
// Server-resolved roster: owner email/display_name + members'
// display_names. We keep `resource.shared_with` as the source of truth
// for membership and just merge display_names from this fetch.
const [people, setPeople] = useState<ProjectPeople | null>(null);
const [peopleLoading, setPeopleLoading] = useState(false);
const resourceId = resource?.id ?? null;
const sharedWith: string[] = Array.isArray(resource?.shared_with)
? (resource!.shared_with as string[])
: [];
useEffect(() => {
if (!open) return;
setNewEmail("");
setError(null);
setBusy(null);
setRemovingEmail(null);
}, [open]);
// Re-fetch roster whenever the modal opens or membership changes —
// keyed by the joined shared_with list so add/remove triggers a refresh.
const sharedKey = sharedWith
.map((e) => e.toLowerCase())
.sort()
.join(",");
useEffect(() => {
if (!open || !resourceId) return;
let cancelled = false;
setPeopleLoading(true);
fetchPeople(resourceId)
.then((data) => {
if (cancelled) return;
setPeople(data);
})
.catch(() => {
/* keep stale data; modal still works on emails alone */
})
.finally(() => {
if (!cancelled) setPeopleLoading(false);
});
return () => {
cancelled = true;
};
}, [open, resourceId, sharedKey, fetchPeople]);
if (!open || !resource) return null;
const memberDisplayByEmail = new Map<string, string | null>();
for (const m of people?.members ?? []) {
memberDisplayByEmail.set(m.email.toLowerCase(), m.display_name);
}
const ownerEmail = people?.owner.email ?? null;
const ownerDisplayName = people?.owner.display_name ?? null;
const roster: RosterRow[] = [];
if (ownerEmail) {
roster.push({
email: ownerEmail,
display_name: ownerDisplayName,
role: "owner",
});
}
for (const email of sharedWith) {
const lower = email.toLowerCase();
if (ownerEmail && lower === ownerEmail.toLowerCase()) continue;
roster.push({
email,
display_name: memberDisplayByEmail.get(lower) ?? null,
role: "member",
});
}
const trimmedNewEmail = newEmail.trim().toLowerCase();
const isValidEmail = EMAIL_RE.test(trimmedNewEmail);
const sharedLower = sharedWith.map((e) => e.toLowerCase());
const alreadyShared = sharedLower.includes(trimmedNewEmail);
const isOwnerEmail =
!!ownerEmail && trimmedNewEmail === ownerEmail.toLowerCase();
const canAdd =
isValidEmail && !alreadyShared && !isOwnerEmail && busy === null;
async function handleAdd() {
if (!canAdd || !onSharedWithChange) return;
setBusy("add");
setError(null);
try {
const next = [...sharedWith, trimmedNewEmail];
await onSharedWithChange(next);
setNewEmail("");
} catch (e) {
setError(
e instanceof Error
? e.message
: "Couldn't add the member. Try again.",
);
} finally {
setBusy(null);
}
}
async function handleRemove(email: string) {
if (!onSharedWithChange || busy !== null) return;
setBusy("remove");
setRemovingEmail(email);
setError(null);
try {
const next = sharedWith.filter(
(e) => e.toLowerCase() !== email.toLowerCase(),
);
await onSharedWithChange(next);
} catch (e) {
setError(
e instanceof Error
? e.message
: "Couldn't remove the member. Try again.",
);
} finally {
setBusy(null);
setRemovingEmail(null);
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{breadcrumb.map((segment, i) => (
<span key={i} className="flex items-center gap-1.5">
{i > 0 && <span></span>}
{segment}
</span>
))}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Add-member row */}
{onSharedWithChange && (
<div className="px-4 pt-1 pb-2">
<div className="flex items-center gap-2">
<div className="flex flex-1 items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2">
<UserPlus className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
type="email"
placeholder="Add by email…"
value={newEmail}
onChange={(e) =>
setNewEmail(e.target.value)
}
onKeyDown={(e) => {
if (e.key === "Enter") void handleAdd();
}}
className="flex-1 bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus
/>
</div>
<button
onClick={() => void handleAdd()}
disabled={!canAdd}
title="Add member"
className="inline-flex items-center justify-center rounded-lg border border-gray-900 bg-gray-900 p-2 text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
>
{busy === "add" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Plus className="h-3.5 w-3.5" />
)}
</button>
</div>
{alreadyShared && trimmedNewEmail && (
<p className="mt-1.5 text-xs text-gray-400">
{trimmedNewEmail} already has access.
</p>
)}
{isOwnerEmail && trimmedNewEmail && (
<p className="mt-1.5 text-xs text-gray-400">
{trimmedNewEmail} is the owner.
</p>
)}
{trimmedNewEmail &&
!isValidEmail &&
!alreadyShared &&
!isOwnerEmail && (
<p className="mt-1.5 text-xs text-gray-400">
Enter a valid email.
</p>
)}
{error && (
<p className="mt-1.5 text-xs text-red-500">
{error}
</p>
)}
</div>
)}
{/* Section heading */}
<div className="px-4 pt-3 pb-1 flex items-center gap-2">
<h3 className="text-xs font-medium text-gray-500">
People with Access
</h3>
{peopleLoading && (
<Loader2 className="h-3 w-3 animate-spin text-gray-400" />
)}
</div>
{/* Member list */}
<div className="flex-1 overflow-y-auto px-4 pb-2">
{roster.length === 0 ? (
<div className="flex h-full items-center justify-center text-sm text-gray-400">
No one has access yet.
</div>
) : (
<ul className="divide-y divide-gray-100 [&>li:nth-child(2)]:border-t-0">
{roster.map((entry) => {
const isYou =
!!currentUserEmail &&
entry.email.toLowerCase() ===
currentUserEmail.toLowerCase();
const isRemoving =
busy === "remove" &&
removingEmail === entry.email;
const primary =
entry.display_name?.trim() || entry.email;
const showSecondary =
!!entry.display_name?.trim() &&
primary !== entry.email;
return (
<li
key={`${entry.role}-${entry.email}`}
className="flex items-center gap-3 py-3"
>
<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gray-900 text-white">
<User className="h-3 w-3" />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm text-gray-800">
{primary}
{isYou && (
<span className="ml-1.5 text-xs text-gray-400">
(You)
</span>
)}
{entry.role === "owner" && (
<span className="ml-1.5 text-[10px] text-gray-400">
Owner
</span>
)}
</p>
{showSecondary && (
<p className="truncate text-xs text-gray-400">
{entry.email}
</p>
)}
</div>
{entry.role === "member" &&
onSharedWithChange && (
<button
onClick={() =>
void handleRemove(
entry.email,
)
}
disabled={busy !== null}
title="Remove access"
className="self-center inline-flex items-center gap-1 rounded px-2 py-1 text-xs text-gray-500 hover:bg-red-50 hover:text-red-600 disabled:opacity-50"
>
{isRemoving && (
<Loader2 className="h-3 w-3 animate-spin" />
)}
Remove
</button>
)}
</li>
);
})}
</ul>
)}
</div>
{/* Footer */}
<div className="px-5 py-3 text-[11px] text-gray-400">
{roster.length === 0
? "No one has access yet."
: `${roster.length} ${
roster.length === 1 ? "person" : "people"
} with access.`}
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,74 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { ChevronDown } from "lucide-react";
export function PreResponseWrapper({
children,
stepCount,
shouldMinimize,
isStreaming,
compact = false,
}: {
children: React.ReactNode;
stepCount: number;
shouldMinimize: boolean;
isStreaming: boolean;
/** Tighter typography + child gap for narrow side panels (e.g. TR chat). */
compact?: boolean;
}) {
const [userToggled, setUserToggled] = useState(false);
const [isOpen, setIsOpen] = useState(!shouldMinimize);
// Once content has streamed in (shouldMinimize=true even once), stay
// minimized even if a later render briefly evaluates shouldMinimize=false.
// Without this latch, the wrapper visibly pops open when isStreaming
// flips off at the end of the response.
const hasMinimizedRef = useRef(shouldMinimize);
useEffect(() => {
if (shouldMinimize) hasMinimizedRef.current = true;
if (userToggled) return;
setIsOpen(!shouldMinimize && !hasMinimizedRef.current);
}, [shouldMinimize, userToggled]);
const stepWord = `step${stepCount === 1 ? "" : "s"}`;
const label = isStreaming
? "Working"
: `Completed in ${stepCount} ${stepWord}`;
const buttonTextClass = compact ? "text-xs" : "text-sm";
const childrenGapClass = compact ? "gap-2.5" : "gap-4";
return (
<div className="border border-gray-200 rounded-lg px-3 py-2">
<button
type="button"
onClick={() => {
setUserToggled(true);
setIsOpen((v) => !v);
}}
className={`w-full flex items-center justify-between font-serif text-gray-500 hover:text-gray-700 transition-colors ${buttonTextClass}`}
>
<span className="flex items-baseline min-w-0">
<span className="truncate">{label}</span>
{isStreaming && (
<span className="inline-flex ml-1 shrink-0 items-baseline">
<span className="w-0.5 h-0.5 rounded-full bg-gray-400 mr-0.5 animate-[bounce_1.4s_infinite_0s]" />
<span className="w-0.5 h-0.5 rounded-full bg-gray-400 mr-0.5 animate-[bounce_1.4s_infinite_0.2s]" />
<span className="w-0.5 h-0.5 rounded-full bg-gray-400 animate-[bounce_1.4s_infinite_0.4s]" />
</span>
)}
</span>
<ChevronDown
size={12}
className={`shrink-0 ml-2 transition-transform duration-200 ${isOpen ? "" : "-rotate-90"}`}
/>
</button>
{isOpen && (
<div className={`mt-3 flex flex-col ${childrenGapClass}`}>
{children}
</div>
)}
</div>
);
}

View file

@ -0,0 +1,91 @@
"use client";
import { useState } from "react";
import { Folder, Search, X } from "lucide-react";
import type { MikeProject } from "./types";
interface Props {
projects: MikeProject[];
loading: boolean;
selectedId: string | null;
onSelect: (id: string | null) => void;
}
export function ProjectPicker({ projects, loading, selectedId, onSelect }: Props) {
const [search, setSearch] = useState("");
const q = search.toLowerCase().trim();
const filtered = q ? projects.filter((p) => p.name.toLowerCase().includes(q)) : projects;
return (
<>
<div className="px-4 pt-1 pb-2">
<div className="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2">
<Search className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search projects…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1 bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus
/>
{search && (
<button onClick={() => setSearch("")} className="text-gray-400 hover:text-gray-600">
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto px-4 pb-2">
{loading ? (
<div className="rounded-sm border border-gray-100 overflow-hidden">
<div className="flex items-center px-2 py-2">
<div className="h-3 w-14 rounded bg-gray-200 animate-pulse" />
</div>
{[65, 45, 80, 55, 70].map((w, i) => (
<div key={i} className="flex items-center gap-2 px-2 py-2">
<div className="h-3.5 w-3.5 rounded-full border border-gray-200 shrink-0" />
<div className="h-3.5 w-3.5 rounded bg-gray-200 animate-pulse shrink-0" />
<div className="h-3 rounded bg-gray-200 animate-pulse" style={{ width: `${w}%` }} />
</div>
))}
</div>
) : filtered.length === 0 ? (
<p className="text-center text-sm text-gray-400 py-8">
{q ? "No matches found" : "No projects yet"}
</p>
) : (
<div className="rounded-sm border border-gray-100 overflow-hidden">
<div className="flex items-center justify-between px-2 py-2">
<p className="text-xs font-medium text-gray-400">Projects</p>
</div>
<div className="space-y-px">
{filtered.map((project) => {
const isSelected = selectedId === project.id;
return (
<button
key={project.id}
onClick={() => onSelect(isSelected ? null : project.id)}
className={`w-full flex items-center gap-2 px-2 py-2 text-xs transition-colors text-left ${isSelected ? "bg-gray-100" : "hover:bg-gray-50"}`}
>
<span className={`shrink-0 h-3.5 w-3.5 rounded-full border flex items-center justify-center ${isSelected ? "bg-gray-900 border-gray-900" : "border-gray-300"}`}>
{isSelected && <span className="h-1.5 w-1.5 rounded-full bg-white" />}
</span>
<Folder className="h-3.5 w-3.5 shrink-0 text-gray-400" />
<span className={`flex-1 truncate ${isSelected ? "text-gray-900 font-medium" : "text-gray-700"}`}>
{project.name}
{project.cm_number && (
<span className="ml-1 font-normal text-gray-400">(#{project.cm_number})</span>
)}
</span>
<span className="shrink-0 text-gray-400">{project.document_count ?? 0}</span>
</button>
);
})}
</div>
</div>
)}
</div>
</>
);
}

View file

@ -0,0 +1,71 @@
"use client";
import { useRef, useState } from "react";
interface Props {
value: string;
onCommit: (newValue: string) => void;
suffix?: React.ReactNode;
}
export function RenameableTitle({ value, onCommit, suffix }: Props) {
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState("");
const caretPos = useRef<number | null>(null);
const escaped = useRef(false);
function startEditing(e: React.MouseEvent) {
const doc = document as any;
const caret = doc.caretPositionFromPoint?.(e.clientX, e.clientY);
const range = !caret && doc.caretRangeFromPoint?.(e.clientX, e.clientY);
caretPos.current = caret ? caret.offset : range ? range.startOffset : null;
escaped.current = false;
setDraft(value);
setEditing(true);
}
function commit() {
if (escaped.current) {
escaped.current = false;
return;
}
setEditing(false);
onCommit(draft.trim());
}
if (editing) {
return (
<input
ref={(el) => {
if (!el) return;
el.focus();
if (caretPos.current !== null) {
el.setSelectionRange(caretPos.current, caretPos.current);
}
}}
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") commit();
if (e.key === "Escape") {
escaped.current = true;
setEditing(false);
}
}}
onBlur={commit}
className="text-gray-900 bg-transparent outline-none min-w-0"
style={{ width: `${draft.length + 1}ch` }}
/>
);
}
return (
<span
className="text-gray-900 cursor-text hover:text-gray-600 transition-colors"
onClick={startEditing}
>
{value}
{suffix}
</span>
);
}

View file

@ -0,0 +1,147 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Download, Eye, EyeOff, FolderMinus, Hash, History, Pencil, Trash2, Upload } from "lucide-react";
interface Props {
onDelete?: () => void;
onHide?: () => void;
onUnhide?: () => void;
onDownload?: () => void;
onRemoveFromFolder?: () => void;
onShowAllVersions?: () => void;
onUploadNewVersion?: () => void;
deleting?: boolean;
onRename?: () => void;
onUpdateCmNumber?: () => void;
}
export function RowActions({ onDelete, onHide, onUnhide, onDownload, onRemoveFromFolder, onShowAllVersions, onUploadNewVersion, deleting, onRename, onUpdateCmNumber }: Props) {
const [open, setOpen] = useState(false);
const [coords, setCoords] = useState({ top: 0, right: 0 });
const btnRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!open) return;
function handleClick() {
setOpen(false);
}
document.addEventListener("click", handleClick);
return () => document.removeEventListener("click", handleClick);
}, [open]);
function handleToggle(e: React.MouseEvent) {
e.stopPropagation();
if (!open && btnRef.current) {
const rect = btnRef.current.getBoundingClientRect();
setCoords({
top: rect.bottom + 4,
right: window.innerWidth - rect.right,
});
}
setOpen((o) => !o);
}
return (
<>
<button
ref={btnRef}
onClick={handleToggle}
className="flex items-center justify-center w-6 h-6 rounded text-gray-700 hover:text-gray-900 hover:bg-gray-100 transition-colors leading-none"
>
<span className="tracking-widest text-xs">···</span>
</button>
{open && (
<div
style={{ position: "fixed", top: coords.top, right: coords.right }}
className="z-50 w-48 rounded-xl border border-gray-100 bg-white shadow-lg overflow-hidden"
onClick={(e) => e.stopPropagation()}
>
{onRename && (
<button
onClick={() => { setOpen(false); onRename(); }}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<Pencil className="h-3.5 w-3.5" />
Rename
</button>
)}
{onUpdateCmNumber && (
<button
onClick={() => { setOpen(false); onUpdateCmNumber(); }}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<Hash className="h-3.5 w-3.5" />
Edit CM No.
</button>
)}
{onDownload && (
<button
onClick={() => { setOpen(false); onDownload(); }}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<Download className="h-3.5 w-3.5" />
Download
</button>
)}
{onShowAllVersions && (
<button
onClick={() => { setOpen(false); onShowAllVersions(); }}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-left text-gray-600 hover:bg-gray-50 transition-colors"
>
<History className="h-3.5 w-3.5 shrink-0" />
Show all versions
</button>
)}
{onUploadNewVersion && (
<button
onClick={() => { setOpen(false); onUploadNewVersion(); }}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-left text-gray-600 hover:bg-gray-50 transition-colors"
>
<Upload className="h-3.5 w-3.5 shrink-0" />
Upload new version
</button>
)}
{onRemoveFromFolder && (
<button
onClick={() => { setOpen(false); onRemoveFromFolder(); }}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-left text-gray-600 hover:bg-gray-50 transition-colors"
>
<FolderMinus className="h-3.5 w-3.5 shrink-0" />
Remove from subfolder
</button>
)}
{onUnhide && (
<button
onClick={() => { setOpen(false); onUnhide(); }}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<Eye className="h-3.5 w-3.5" />
Unhide
</button>
)}
{onHide && (
<button
onClick={() => { setOpen(false); onHide(); }}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<EyeOff className="h-3.5 w-3.5" />
Hide
</button>
)}
{onDelete && (
<button
onClick={() => { setOpen(false); onDelete(); }}
disabled={deleting}
className="flex items-center gap-2 w-full px-3 py-2 text-xs text-red-500 hover:bg-red-50 transition-colors disabled:opacity-40"
>
<Trash2 className="h-3.5 w-3.5" />
Delete
</button>
)}
</div>
)}
</>
);
}

View file

@ -0,0 +1,154 @@
"use client";
import { useState, useRef, useEffect } from "react";
import { MoreHorizontal, Pencil, Trash2, Check, X } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
import { useAuth } from "@/contexts/AuthContext";
import { OwnerOnlyModal } from "@/app/components/shared/OwnerOnlyModal";
import type { MikeChat } from "@/app/components/shared/types";
interface Props {
chat: MikeChat;
isActive: boolean;
onSelect: () => void;
projectName?: string;
}
export function SidebarChatItem({ chat, isActive, onSelect, projectName }: Props) {
const { renameChat, deleteChat } = useChatHistoryContext();
const { user } = useAuth();
const [isRenaming, setIsRenaming] = useState(false);
const [editTitle, setEditTitle] = useState(chat.title ?? "");
const [ownerOnlyAction, setOwnerOnlyAction] = useState<string | null>(null);
const editInputRef = useRef<HTMLInputElement>(null);
// Sidebar can show collaborator chats from projects the user owns;
// rename/delete are still creator-only on the backend, so guard here.
const isChatOwner = !!user?.id && chat.user_id === user.id;
useEffect(() => {
if (isRenaming) editInputRef.current?.focus();
}, [isRenaming]);
const handleRenameSave = async () => {
const trimmed = editTitle.trim();
if (trimmed) await renameChat(chat.id, trimmed);
setIsRenaming(false);
};
const handleRenameCancel = () => {
setIsRenaming(false);
setEditTitle(chat.title ?? "");
};
return (
<div
className={`group relative flex items-center w-full h-9 rounded-md transition-colors ${
isActive ? "bg-gray-100" : "hover:bg-gray-100"
}`}
>
{isRenaming ? (
<div className="flex items-center w-full px-2 py-1">
<input
ref={editInputRef}
type="text"
value={editTitle}
onChange={(e) => setEditTitle(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void handleRenameSave();
if (e.key === "Escape") handleRenameCancel();
}}
className="flex-1 bg-white shadow-inner rounded px-1 py-0.5 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
<button
onClick={() => void handleRenameSave()}
className="ml-1.5 py-2 hover:bg-gray-200 rounded text-green-600"
>
<Check className="h-3 w-3" />
</button>
<button
onClick={handleRenameCancel}
className="ml-1 py-2 hover:bg-gray-200 rounded text-red-600"
>
<X className="h-3 w-3" />
</button>
</div>
) : (
<>
<button
onClick={onSelect}
onMouseEnter={(e) => {
const el = e.currentTarget;
const overflow = el.scrollWidth - el.clientWidth;
if (overflow > 0) el.scrollTo({ left: overflow, behavior: "smooth" });
}}
onMouseLeave={(e) => {
e.currentTarget.scrollTo({ left: 0, behavior: "smooth" });
}}
className={`flex-1 min-w-0 text-left px-3 py-2 text-xs overflow-x-hidden whitespace-nowrap scrollbar-none ${
isActive ? "text-gray-900" : "text-gray-700"
}`}
title={projectName ? `${projectName}: ${chat.title ?? "Untitled chat"}` : (chat.title ?? "Untitled chat")}
>
{projectName && (
<span className="text-gray-400 font-normal">{projectName}: </span>
)}
{chat.title ?? "Untitled chat"}
</button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className={`p-1 mr-1 text-gray-500 transition-opacity hover:text-gray-900 ${
isActive
? "opacity-100"
: "opacity-0 group-hover:opacity-100"
}`}
>
<MoreHorizontal className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="z-101">
<DropdownMenuItem
onClick={() => {
if (!isChatOwner) {
setOwnerOnlyAction("rename this chat");
return;
}
setEditTitle(chat.title ?? "");
setIsRenaming(true);
}}
>
<Pencil className="mr-2 h-4 w-4" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
if (!isChatOwner) {
setOwnerOnlyAction("delete this chat");
return;
}
void deleteChat(chat.id);
}}
className="text-red-600 focus:text-red-600"
>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
)}
<OwnerOnlyModal
open={!!ownerOnlyAction}
action={ownerOnlyAction ?? undefined}
onClose={() => setOwnerOnlyAction(null)}
/>
</div>
);
}

View file

@ -0,0 +1,44 @@
import React from "react";
interface Tab<T extends string> {
id: T;
label: string;
}
interface Props<T extends string> {
tabs: Tab<T>[];
active: T;
onChange: (id: T) => void;
/** Optional content rendered on the right side of the toolbar */
actions?: React.ReactNode;
}
export function ToolbarTabs<T extends string>({
tabs,
active,
onChange,
actions,
}: Props<T>) {
return (
<div className="flex items-center h-10 px-8 border-b border-gray-200">
<div className="flex-1 flex items-center gap-5">
{tabs.map((tab) => (
<button
key={tab.id}
onClick={() => onChange(tab.id)}
className={`text-xs transition-colors ${
active === tab.id
? "font-medium text-gray-700"
: "font-normal text-gray-500 hover:text-gray-700"
}`}
>
{tab.label}
</button>
))}
</div>
{actions && (
<div className="flex items-center gap-1">{actions}</div>
)}
</div>
);
}

View file

@ -0,0 +1,158 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { X, Upload } from "lucide-react";
import { listDocumentVersions } from "@/app/lib/mikeApi";
import type { MikeDocument } from "./types";
interface Props {
open: boolean;
onClose: () => void;
doc: MikeDocument | null;
onSubmit: (file: File, displayName: string) => Promise<void>;
}
export function UploadNewVersionModal({ open, onClose, doc, onSubmit }: Props) {
const [name, setName] = useState("");
const [stagedFile, setStagedFile] = useState<File | null>(null);
const [submitting, setSubmitting] = useState(false);
const [currentVersion, setCurrentVersion] = useState<number | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!open || !doc) return;
setName(doc.filename);
setStagedFile(null);
setSubmitting(false);
setCurrentVersion(null);
let cancelled = false;
(async () => {
try {
const { current_version_id, versions } =
await listDocumentVersions(doc.id);
const current = versions.find(
(v) => v.id === current_version_id,
);
const initial =
(current?.display_name && current.display_name.trim()) ||
doc.filename;
if (!cancelled) {
setName(initial);
setCurrentVersion(current?.version_number ?? null);
}
} catch {
/* keep fallback */
}
})();
return () => {
cancelled = true;
};
}, [open, doc]);
if (!open || !doc) return null;
const accept = doc.file_type === "pdf" ? ".pdf" : ".docx,.doc";
function handleFilePick(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0] ?? null;
setStagedFile(file);
if (fileInputRef.current) fileInputRef.current.value = "";
}
async function handleSubmit() {
if (!stagedFile || submitting || !doc) return;
const finalName = name.trim() || doc.filename;
setSubmitting(true);
try {
await onSubmit(stagedFile, finalName);
onClose();
} finally {
setSubmitting(false);
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-md rounded-2xl bg-white shadow-2xl flex flex-col">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="text-xs text-gray-400">
Upload new version · {doc.filename}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Name input */}
<div className="px-5 pb-4">
<label className="block text-xs font-medium text-gray-500 mb-1">
New version name
</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Version name"
className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm outline-none focus:border-gray-400"
/>
<div className="mt-2 text-xs text-gray-500">
Current Version:{" "}
<span className="text-gray-700 font-medium">
{currentVersion ?? "—"}
</span>
</div>
{stagedFile && (
<div className="mt-2 text-xs text-gray-500 truncate">
New Version File:{" "}
<span className="text-gray-700">
{stagedFile.name}
</span>
</div>
)}
</div>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-between gap-3">
<div>
<input
ref={fileInputRef}
type="file"
accept={accept}
className="hidden"
onChange={handleFilePick}
/>
<button
onClick={() => fileInputRef.current?.click()}
disabled={submitting}
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50 disabled:opacity-50"
>
<Upload className="h-3.5 w-3.5" />
{stagedFile ? "Change file" : "Upload"}
</button>
</div>
<div className="flex items-center gap-2">
<button
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleSubmit}
disabled={!stagedFile || submitting}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40"
>
{submitting ? "Saving…" : "Save"}
</button>
</div>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,13 @@
/**
* Small "V3" badge for document rows/listings, rendered when the doc has
* at least one assistant-edit version. Matches the chip in the side
* panel's edit-tab header.
*/
export function VersionChip({ n }: { n: number | null | undefined }) {
if (typeof n !== "number" || !Number.isFinite(n) || n < 1) return null;
return (
<span className="shrink-0 inline-flex items-center rounded-md border border-gray-200 bg-white px-1 py-0.5 text-[10px] font-medium text-gray-500">
V{n}
</span>
);
}

View file

@ -0,0 +1,127 @@
const HIGHLIGHT_CLASS = "docx-text-highlight";
function onlyLetters(s: string): string {
return s.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
}
function toOrigPos(text: string, strippedPos: number): number {
let count = 0;
for (let k = 0; k < text.length; k++) {
if (/[a-zA-Z0-9]/.test(text[k])) {
if (count === strippedPos) return k;
count++;
}
}
return text.length;
}
function collectTextNodes(root: HTMLElement): Text[] {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode(node: Node) {
const p = node.parentElement;
if (!p) return NodeFilter.FILTER_REJECT;
const tag = p.tagName;
if (tag === "STYLE" || tag === "SCRIPT")
return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
},
});
const out: Text[] = [];
let cur = walker.nextNode() as Text | null;
while (cur) {
out.push(cur);
cur = walker.nextNode() as Text | null;
}
return out;
}
export function clearDocxQuoteHighlights(root: HTMLElement): void {
root.querySelectorAll(`.${HIGHLIGHT_CLASS}`).forEach((span) => {
const parent = span.parentNode;
if (!parent) return;
while (span.firstChild) parent.insertBefore(span.firstChild, span);
parent.removeChild(span);
});
root.normalize();
}
/**
* Highlight the given quote text inside `root` (a docx-preview output).
* Quote is split on ellipsis variants; each segment is located via
* letters-only substring matching, so whitespace/punctuation differences
* between the LLM's quote and the rendered text don't break matching.
*
* Returns the first highlight span if any match was found, for
* scroll-into-view by the caller.
*/
export function highlightDocxQuote(
root: HTMLElement,
quote: string,
): HTMLElement | null {
clearDocxQuoteHighlights(root);
if (!quote) return null;
const segments = quote
.split(/\.{3}|…/)
.map(onlyLetters)
.filter((s) => s.length > 0);
if (segments.length === 0) return null;
const textNodes = collectTextNodes(root);
const nodeStartInFull: number[] = [];
const nodeStrippedLen: number[] = [];
let fullStripped = "";
for (const node of textNodes) {
const stripped = onlyLetters(node.data);
nodeStartInFull.push(fullStripped.length);
nodeStrippedLen.push(stripped.length);
fullStripped += stripped;
}
type Range = { nodeIdx: number; origStart: number; origEnd: number };
const ranges: Range[] = [];
for (const segment of segments) {
const searchKey = segment.slice(0, 30);
const matchPos = fullStripped.indexOf(searchKey);
if (matchPos < 0) continue;
const matchEnd = matchPos + segment.length;
for (let i = 0; i < textNodes.length; i++) {
const start = nodeStartInFull[i];
const end = start + nodeStrippedLen[i];
if (matchPos >= end || matchEnd <= start) continue;
const localStart = Math.max(0, matchPos - start);
const localEnd = Math.min(nodeStrippedLen[i], matchEnd - start);
const text = textNodes[i].data;
const origStart = toOrigPos(text, localStart);
const origEnd = toOrigPos(text, localEnd);
if (origStart >= origEnd) continue;
ranges.push({ nodeIdx: i, origStart, origEnd });
}
}
if (ranges.length === 0) return null;
// Apply in reverse document order so splits don't shift earlier ranges.
ranges.sort((a, b) => {
if (a.nodeIdx !== b.nodeIdx) return b.nodeIdx - a.nodeIdx;
return b.origStart - a.origStart;
});
const spans: HTMLElement[] = [];
for (const r of ranges) {
const node = textNodes[r.nodeIdx];
const mid = node.splitText(r.origStart);
mid.splitText(r.origEnd - r.origStart);
const span = document.createElement("span");
span.className = HIGHLIGHT_CLASS;
mid.parentNode?.insertBefore(span, mid);
span.appendChild(mid);
spans.push(span);
}
// Because we processed ranges in reverse order, the earliest-in-document
// highlight is the last one we pushed.
return spans[spans.length - 1] ?? null;
}

View file

@ -0,0 +1,124 @@
let pdfjsLib: typeof import("pdfjs-dist") | null = null;
export async function getPdfJs() {
if (pdfjsLib) return pdfjsLib;
pdfjsLib = await import("pdfjs-dist");
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
"pdfjs-dist/build/pdf.worker.min.mjs",
import.meta.url,
).toString();
return pdfjsLib;
}
export const STANDARD_FONT_DATA_URL =
"https://unpkg.com/pdfjs-dist@4.10.38/standard_fonts/";
const HIGHLIGHT_CLASS = "pdf-text-highlight";
const ORIGINAL_TEXT_ATTR = "data-original-text";
// Strip everything except alphanumerics (a-z A-Z 0-9) for robust matching
function onlyLetters(s: string): string {
return s.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
// Given a position in the stripped (letters-only) version of `original`,
// return the corresponding index in `original`.
function strippedPosToOriginal(original: string, strippedPos: number): number {
let count = 0;
for (let i = 0; i < original.length; i++) {
if (/[a-zA-Z0-9]/.test(original[i])) {
if (count === strippedPos) return i;
count++;
}
}
return original.length;
}
export function clearHighlights(textDivs: HTMLElement[]) {
for (const div of textDivs) {
if (div.hasAttribute(ORIGINAL_TEXT_ATTR)) {
div.textContent = div.getAttribute(ORIGINAL_TEXT_ATTR)!;
div.removeAttribute(ORIGINAL_TEXT_ATTR);
}
}
}
export async function highlightQuote(
textDivs: HTMLElement[],
quote: string,
): Promise<boolean> {
clearHighlights(textDivs);
// Split on ellipsis variants to highlight each segment separately
const segments = quote
.split(/\.{3}|…/)
.map((s) => onlyLetters(s))
.filter((s) => s.length > 0);
// Build the stripped full text and track each div's start position within it.
// Also keep original div texts for display.
const divOrigTexts: string[] = []; // original text for innerHTML slicing
const divStripped: string[] = []; // letters-only version for matching
const divStartInFull: number[] = []; // start index in fullStripped
let fullStripped = "";
for (let i = 0; i < textDivs.length; i++) {
const orig = textDivs[i].textContent ?? "";
divOrigTexts.push(orig);
const stripped = onlyLetters(orig);
divStripped.push(stripped);
divStartInFull.push(fullStripped.length);
fullStripped += stripped;
}
// Map: divIndex -> [strippedLocalStart, strippedLocalEnd]
const divHighlightRanges = new Map<number, [number, number]>();
for (const segment of segments) {
const searchKey = segment.slice(0, 30);
const matchPos = fullStripped.indexOf(searchKey);
if (matchPos === -1) {
continue;
}
const matchEnd = matchPos + segment.length;
for (let i = 0; i < textDivs.length; i++) {
const divStart = divStartInFull[i];
const divEnd = divStart + divStripped[i].length;
if (matchPos >= divEnd || matchEnd <= divStart) continue;
const localStart = Math.max(0, matchPos - divStart);
const localEnd = Math.min(
divStripped[i].length,
matchEnd - divStart,
);
divHighlightRanges.set(i, [localStart, localEnd]);
}
}
if (divHighlightRanges.size === 0) return false;
for (const [idx, [strStart, strEnd]] of divHighlightRanges) {
const div = textDivs[idx];
const orig = divOrigTexts[idx];
// Map stripped positions back to original character positions
const origStart = strippedPosToOriginal(orig, strStart);
const origEnd = strippedPosToOriginal(orig, strEnd);
div.setAttribute(ORIGINAL_TEXT_ATTR, orig);
div.innerHTML =
escapeHtml(orig.slice(0, origStart)) +
`<span class="${HIGHLIGHT_CLASS}">${escapeHtml(orig.slice(origStart, origEnd))}</span>` +
escapeHtml(orig.slice(origEnd));
}
return true;
}

View file

@ -0,0 +1,301 @@
// Shared TypeScript types for Mike AI legal assistant
export interface MikeFolder {
id: string;
project_id: string;
user_id: string;
name: string;
parent_folder_id: string | null;
created_at: string;
updated_at: string;
}
export interface MikeProject {
id: string;
user_id: string;
is_owner?: boolean;
name: string;
cm_number: string | null;
shared_with: string[];
created_at: string;
updated_at: string;
documents?: MikeDocument[];
folders?: MikeFolder[];
document_count?: number;
chat_count?: number;
review_count?: number;
}
export interface MikeDocument {
id: string;
user_id?: string;
project_id: string | null;
folder_id?: string | null;
filename: string;
file_type: string | null; // pdf | docx | doc
storage_path: string | null;
pdf_storage_path: string | null;
size_bytes: number | null;
page_count: number | null;
structure_tree: StructureNode[] | null;
status: "pending" | "processing" | "ready" | "error";
created_at: string | null;
updated_at?: string | null;
/** Max version_number across assistant_edit rows, null if doc is unedited. */
latest_version_number?: number | null;
}
export interface StructureNode {
id: string;
title: string;
level: number;
page_number: number | null;
children: StructureNode[];
}
export interface MikeChat {
id: string;
project_id: string | null;
user_id: string;
title: string | null;
created_at: string;
}
export interface MikeEditAnnotation {
type?: "edit_data";
kind?: "edit";
edit_id: string;
document_id: string;
version_id: string;
/** Per-document monotonic Vn for the edit's target version. */
version_number?: number | null;
change_id: string;
del_w_id?: string;
ins_w_id?: string;
deleted_text: string;
inserted_text: string;
context_before?: string;
context_after?: string;
reason?: string;
status: "pending" | "accepted" | "rejected";
}
export type AssistantEvent =
| { type: "reasoning"; text: string; isStreaming?: boolean }
| {
type: "tool_call_start";
name: string;
isStreaming?: boolean;
}
| { type: "thinking"; isStreaming?: boolean }
| {
type: "doc_read";
filename: string;
document_id?: string;
isStreaming?: boolean;
}
| {
type: "doc_find";
filename: string;
query: string;
total_matches: number;
isStreaming?: boolean;
}
| {
type: "doc_created";
filename: string;
download_url: string;
/** Set when the generated doc is persisted as a first-class document. */
document_id?: string;
version_id?: string;
version_number?: number | null;
isStreaming?: boolean;
}
| { type: "doc_download"; filename: string; download_url: string }
| {
type: "doc_replicated";
/** Source document filename. */
filename: string;
/** How many copies were produced in this single tool call. */
count: number;
/** One entry per new copy. Empty while streaming. */
copies?: {
new_filename: string;
document_id: string;
version_id: string;
}[];
error?: string;
isStreaming?: boolean;
}
| { type: "workflow_applied"; workflow_id: string; title: string }
| {
type: "doc_edited";
filename: string;
document_id: string;
version_id: string;
/** Per-document monotonic Vn written at emit time. */
version_number?: number | null;
download_url: string;
annotations: MikeEditAnnotation[];
error?: string;
isStreaming?: boolean;
}
| { type: "content"; text: string; isStreaming?: boolean };
export interface MikeMessage {
role: "user" | "assistant";
content: string;
files?: { filename: string; document_id?: string }[];
workflow?: { id: string; title: string };
model?: string;
annotations?: MikeCitationAnnotation[];
events?: AssistantEvent[];
/** Set when streaming failed; rendered as a red error block. */
error?: string;
}
export interface CitationQuote {
page: number;
quote: string;
}
/**
* A citation emitted by the assistant. Single-page citations have a numeric
* `page` and a plain `quote`. A citation that spans a page break (one
* continuous sentence cut by a page boundary) has `page` as a range string
* like "41-42" and a `quote` containing the `[[PAGE_BREAK]]` sentinel at the
* break point (text before is on page 41, text after is on page 42).
*/
export interface MikeCitationAnnotation {
type: "citation_data";
ref: number;
doc_id: string;
document_id: string;
version_id?: string | null;
version_number?: number | null;
filename: string;
page: number | string;
quote: string;
}
const PAGE_BREAK_SENTINEL = "[[PAGE_BREAK]]";
/**
* Expand a citation into one or more (page, quote) entries suitable for
* highlighting in the PDF viewer. A single-page citation yields one entry; a
* cross-page citation with page "N-M" and a `[[PAGE_BREAK]]` split yields two.
*/
export function expandCitationToEntries(
a: MikeCitationAnnotation,
): CitationQuote[] {
const rangeMatch =
typeof a.page === "string"
? a.page.match(/^(\d+)\s*-\s*(\d+)$/)
: null;
if (rangeMatch && a.quote.includes(PAGE_BREAK_SENTINEL)) {
const startPage = parseInt(rangeMatch[1], 10);
const endPage = parseInt(rangeMatch[2], 10);
const [before, after] = a.quote.split(PAGE_BREAK_SENTINEL);
return [
{ page: startPage, quote: before.trim() },
{ page: endPage, quote: after.trim() },
].filter((e) => e.quote.length > 0);
}
const pageNum =
typeof a.page === "number" ? a.page : parseInt(String(a.page), 10);
if (!Number.isFinite(pageNum)) return [];
return [{ page: pageNum, quote: a.quote }];
}
/** Format the page(s) of a citation for display, e.g. "Page 3" or "Page 41-42". */
export function formatCitationPage(a: MikeCitationAnnotation): string {
if (typeof a.page === "string") return `Page ${a.page}`;
return `Page ${a.page}`;
}
/** Produce a reader-friendly version of the quote (replaces [[PAGE_BREAK]] with "..."). */
export function displayCitationQuote(a: MikeCitationAnnotation): string {
return a.quote.replaceAll(PAGE_BREAK_SENTINEL, "...");
}
// Tabular Review
export type ColumnFormat =
| "text"
| "bulleted_list"
| "number"
| "currency"
| "yes_no"
| "date"
| "tag"
| "percentage"
| "monetary_amount";
export interface ColumnConfig {
index: number;
name: string;
prompt: string;
format?: ColumnFormat;
tags?: string[];
}
export interface TabularReview {
id: string;
project_id: string | null;
user_id: string;
title: string | null;
columns_config: ColumnConfig[] | null;
workflow_id: string | null;
practice?: string | null;
/** Per-review email list. Used so standalone (project_id null) reviews can be shared directly. */
shared_with?: string[];
/** Server-set: true when the requesting user is the review's creator. */
is_owner?: boolean;
created_at: string;
updated_at: string;
document_count?: number;
}
export interface TabularCell {
id: string;
review_id: string;
document_id: string;
column_index: number;
content: {
summary: string;
flag?: "green" | "grey" | "yellow" | "red";
reasoning?: string;
} | null;
status: "pending" | "generating" | "done" | "error";
created_at: string;
}
// Workflows
export interface MikeWorkflow {
id: string;
user_id: string | null;
title: string;
type: "assistant" | "tabular";
prompt_md: string | null;
columns_config: ColumnConfig[] | null;
is_system: boolean;
created_at: string;
practice?: string | null;
shared_by_name?: string | null;
allow_edit?: boolean;
is_owner?: boolean;
}
// API helpers
export interface MikeChatDetailOut {
chat: MikeChat;
messages: MikeMessage[];
}
export interface TabularReviewDetailOut {
review: TabularReview;
cells: TabularCell[];
documents: MikeDocument[];
}

View file

@ -0,0 +1,63 @@
"use client";
import { useEffect, useState } from "react";
import { getProject, listProjects, listStandaloneDocuments } from "@/app/lib/mikeApi";
import type { MikeDocument, MikeProject } from "./types";
const CACHE_TTL_MS = 30_000;
interface DirectoryCache {
standaloneDocuments: MikeDocument[];
projects: MikeProject[];
fetchedAt: number;
}
let cache: DirectoryCache | null = null;
export function invalidateDirectoryCache() {
cache = null;
}
export function useDirectoryData(enabled: boolean) {
const [loading, setLoading] = useState(true);
const [standaloneDocuments, setStandaloneDocuments] = useState<MikeDocument[]>([]);
const [projects, setProjects] = useState<MikeProject[]>([]);
useEffect(() => {
if (!enabled) return;
const now = Date.now();
if (cache && now - cache.fetchedAt < CACHE_TTL_MS) {
setStandaloneDocuments(cache.standaloneDocuments);
setProjects(cache.projects);
setLoading(false);
return;
}
setLoading(true);
Promise.all([listProjects(), listStandaloneDocuments()])
.then(([ps, ds]) => {
const sorted = [...ds].sort((a, b) =>
(b.created_at ?? "").localeCompare(a.created_at ?? ""),
);
return Promise.all(ps.map((p) => getProject(p.id))).then(
(fullProjects) => {
cache = {
standaloneDocuments: sorted,
projects: fullProjects,
fetchedAt: Date.now(),
};
setStandaloneDocuments(sorted);
setProjects(fullProjects);
},
);
})
.catch(() => {
setStandaloneDocuments([]);
setProjects([]);
})
.finally(() => setLoading(false));
}, [enabled]);
return { loading, standaloneDocuments, projects };
}

View file

@ -0,0 +1,522 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { ChevronDown, Plus, X } from "lucide-react";
import type { ColumnConfig, ColumnFormat } from "../shared/types";
import { generateTabularColumnPrompt } from "@/app/lib/mikeApi";
import { FORMAT_OPTIONS, formatLabel, formatIcon } from "./columnFormat";
import { TAG_COLORS } from "./pillUtils";
import { getPresetConfig, PROMPT_PRESETS } from "./columnPresets";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
interface ColumnDraft {
name: string;
prompt: string;
format: ColumnFormat;
tags: string[];
tagInput: string;
}
const EMPTY_DRAFT: ColumnDraft = {
name: "",
prompt: "",
format: "text",
tags: [],
tagInput: "",
};
interface Props {
open: boolean;
existingCount: number;
onClose: () => void;
onAdd: (cols: ColumnConfig[]) => void;
editingColumn?: ColumnConfig;
onSave?: (col: ColumnConfig) => void;
onDelete?: () => void;
}
export function AddColumnModal({ open, existingCount, onClose, onAdd, editingColumn, onSave, onDelete }: Props) {
const isEditing = !!editingColumn;
const [columns, setColumns] = useState<ColumnDraft[]>([{ ...EMPTY_DRAFT }]);
const [generatingIndices, setGeneratingIndices] = useState<number[]>([]);
const [presetsOpenIndex, setPresetsOpenIndex] = useState<number | null>(
null,
);
const presetsRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
if (editingColumn) {
setColumns([{
name: editingColumn.name,
prompt: editingColumn.prompt,
format: editingColumn.format ?? "text",
tags: editingColumn.tags ?? [],
tagInput: "",
}]);
} else {
setColumns([{ ...EMPTY_DRAFT }]);
}
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (presetsOpenIndex === null) return;
function handleClickOutside(e: MouseEvent) {
if (
presetsRef.current &&
!presetsRef.current.contains(e.target as Node)
) {
setPresetsOpenIndex(null);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () =>
document.removeEventListener("mousedown", handleClickOutside);
}, [presetsOpenIndex]);
if (!open) return null;
function resetForm() {
setColumns([{ ...EMPTY_DRAFT }]);
setGeneratingIndices([]);
}
function handleClose() {
resetForm();
onClose();
}
function updateColumn(index: number, patch: Partial<ColumnDraft>) {
setColumns((prev) =>
prev.map((col, i) => (i === index ? { ...col, ...patch } : col)),
);
}
function addAnotherColumn() {
setColumns((prev) => [...prev, { ...EMPTY_DRAFT }]);
}
function removeColumn(index: number) {
setColumns((prev) =>
prev.length === 1
? [{ ...EMPTY_DRAFT }]
: prev.filter((_, i) => i !== index),
);
}
function commitTag(index: number) {
setColumns((prev) => {
const col = prev[index]!;
const tag = col.tagInput.trim();
if (!tag || col.tags.includes(tag)) {
return prev.map((c, i) =>
i === index ? { ...c, tagInput: "" } : c,
);
}
return prev.map((c, i) =>
i === index
? { ...c, tags: [...c.tags, tag], tagInput: "" }
: c,
);
});
}
function handleTagKeyDown(
e: React.KeyboardEvent<HTMLInputElement>,
index: number,
) {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
commitTag(index);
} else if (
e.key === "Backspace" &&
columns[index]!.tagInput === "" &&
columns[index]!.tags.length > 0
) {
updateColumn(index, {
tags: columns[index]!.tags.slice(0, -1),
});
}
}
async function autoGeneratePrompt(index: number) {
const title = columns[index]?.name?.trim() ?? "";
if (!title) return;
setGeneratingIndices((prev) => [...prev, index]);
try {
const col = columns[index]!;
const { prompt } = await generateTabularColumnPrompt(title, {
format: col.format,
tags: col.format === "tag" ? col.tags : undefined,
});
updateColumn(index, { prompt });
} finally {
setGeneratingIndices((prev) => prev.filter((v) => v !== index));
}
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (columns.some((col) => !col.name.trim() || !col.prompt.trim()))
return;
if (isEditing && onSave && editingColumn) {
const col = columns[0]!;
onSave({
index: editingColumn.index,
name: col.name.trim(),
prompt: col.prompt.trim(),
format: col.format,
tags: col.format === "tag" ? col.tags : undefined,
});
} else {
onAdd(
columns.map((col, i) => ({
index: existingCount + i,
name: col.name.trim(),
prompt: col.prompt.trim(),
format: col.format,
tags: col.format === "tag" ? col.tags : undefined,
})),
);
}
resetForm();
onClose();
}
return createPortal(
<div className="fixed inset-0 z-[101] flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-6 pt-5 pb-2">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Tabular Review</span>
<span></span>
<span>{isEditing ? "Edit column" : "New column"}</span>
</div>
<button
onClick={handleClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
<form
onSubmit={handleSubmit}
className="flex flex-col min-h-0 flex-1"
>
{/* Body */}
<div className="px-6 pt-3 pb-5 space-y-5 overflow-y-auto flex-1">
{columns.map((column, index) => (
<div
key={index}
className="rounded-xl border border-gray-200 p-4"
>
{/* Name row */}
<div className="flex items-start gap-2">
{/* Input + preset dropdown anchored to this wrapper */}
<div
className="relative flex flex-1 items-start"
ref={
presetsOpenIndex === index
? presetsRef
: null
}
>
<input
type="text"
value={column.name}
onChange={(e) => {
const name = e.target.value;
const preset =
getPresetConfig(name);
updateColumn(index, {
name,
...(preset
? {
prompt: preset.prompt,
format: preset.format,
tags:
preset.tags ??
[],
tagInput: "",
}
: {}),
});
}}
placeholder="Column name"
className="flex-1 text-2xl font-serif text-gray-800 placeholder-gray-400 focus:outline-none bg-transparent"
autoFocus={index === 0}
/>
<button
type="button"
onClick={() =>
setPresetsOpenIndex(
presetsOpenIndex === index
? null
: index,
)
}
title="Column presets"
className="mt-1.5 rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700"
>
<ChevronDown
className={`h-4 w-4 transition-transform ${presetsOpenIndex === index ? "rotate-180" : ""}`}
/>
</button>
{presetsOpenIndex === index && (
<div className="absolute left-0 right-0 top-full mt-1 z-50 rounded-xl border border-gray-100 bg-white shadow-lg overflow-y-auto max-h-64">
<button
type="button"
onClick={() => {
updateColumn(index, { ...EMPTY_DRAFT });
setPresetsOpenIndex(null);
}}
className="w-full px-3 py-2 text-left text-sm text-gray-400 hover:bg-gray-50 transition-colors border-b border-gray-100"
>
No Preset
</button>
{PROMPT_PRESETS.map(
(preset) => (
<button
key={preset.name}
type="button"
onClick={() => {
updateColumn(
index,
{
name: preset.name,
prompt: preset.prompt,
format: preset.format,
tags:
preset.tags ??
[],
tagInput:
"",
},
);
setPresetsOpenIndex(
null,
);
}}
className="w-full px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-50 transition-colors"
>
{preset.name}
</button>
),
)}
</div>
)}
</div>
{columns.length > 1 && (
<button
type="button"
onClick={() => removeColumn(index)}
className="mt-1.5 rounded-lg p-1.5 text-gray-300 transition-colors hover:bg-gray-100 hover:text-gray-500"
>
<X className="h-4 w-4" />
</button>
)}
</div>
{/* Format */}
<div className="mt-4">
<label className="text-sm font-medium text-gray-500">
Format
</label>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="mt-1 flex items-center justify-between rounded-md border border-gray-200 bg-white px-2 py-1.5 text-sm text-gray-700 hover:border-gray-400 focus:outline-none">
<span className="flex items-center gap-2">
{(() => {
const Icon = formatIcon(
column.format,
);
return (
<Icon className="h-3.5 w-3.5 text-gray-400" />
);
})()}
{formatLabel(column.format)}
</span>
<ChevronDown className="h-3.5 w-3.5 text-gray-400" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="start"
className="z-[200]"
>
<DropdownMenuRadioGroup
value={column.format}
onValueChange={(v) =>
updateColumn(index, {
format: v as ColumnFormat,
tags: [],
tagInput: "",
})
}
>
{FORMAT_OPTIONS.map((o) => (
<DropdownMenuRadioItem
key={o.value}
value={o.value}
>
<o.icon className="h-3.5 w-3.5 text-gray-400" />
{o.label}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Tag input */}
{column.format === "tag" && (
<div className="mt-3">
<label className="text-sm font-medium text-gray-500">
Tags
</label>
<div className="mt-1 flex flex-wrap gap-1.5 rounded-md border border-gray-200 px-2 py-1.5 focus-within:border-gray-400">
{column.tags.map((tag, tagIdx) => (
<span
key={tag}
className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs ${TAG_COLORS[tagIdx % TAG_COLORS.length]}`}
>
{tag}
<button
type="button"
onClick={() =>
updateColumn(
index,
{
tags: column.tags.filter(
(t) =>
t !==
tag,
),
},
)
}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-2.5 w-2.5" />
</button>
</span>
))}
<input
type="text"
value={column.tagInput}
onChange={(e) =>
updateColumn(index, {
tagInput:
e.target.value,
})
}
onKeyDown={(e) =>
handleTagKeyDown(e, index)
}
onBlur={() => commitTag(index)}
placeholder="Add tag…"
className="min-w-[80px] flex-1 bg-transparent text-sm text-gray-700 placeholder-gray-400 focus:outline-none"
/>
</div>
<p className="mt-1 text-xs text-gray-400">
Press Enter or comma to add a tag.
</p>
</div>
)}
{/* Prompt */}
<div className="mt-4 flex items-center justify-between">
<label className="text-sm font-medium text-gray-500">
Prompt
</label>
<button
type="button"
onClick={() =>
autoGeneratePrompt(index)
}
disabled={
!column.name.trim() ||
generatingIndices.includes(index)
}
className="inline-flex items-center gap-1.5 text-sm text-gray-500 transition-colors hover:text-gray-900 disabled:text-gray-300"
>
{generatingIndices.includes(index) ? (
<span className="h-4 w-4 rounded-full border-2 border-gray-300 border-t-gray-600 animate-spin block" />
) : (
<Plus className="h-4 w-4" />
)}
Auto-Generate Prompt
</button>
</div>
<textarea
rows={6}
value={column.prompt}
onChange={(e) =>
updateColumn(index, {
prompt: e.target.value,
})
}
placeholder="Write the analysis prompt — describe what Mike should extract from each document for this column…"
className="mt-2 w-full rounded-md border border-gray-200 px-3 py-2 text-sm text-gray-700 placeholder-gray-400 focus:border-gray-400 focus:outline-none bg-transparent resize-none leading-relaxed"
/>
</div>
))}
{!isEditing && (
<button
type="button"
onClick={addAnotherColumn}
className="inline-flex items-center gap-1.5 text-sm text-gray-500 transition-colors hover:text-gray-900"
>
<Plus className="h-4 w-4" />
Add another column
</button>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between border-t border-gray-100 px-6 py-4">
<div>
{isEditing && onDelete && (
<button
type="button"
onClick={onDelete}
className="rounded-lg px-4 py-2 text-sm text-red-500 hover:bg-red-50 transition-colors"
>
Delete
</button>
)}
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleClose}
className="rounded-lg px-4 py-2 text-sm text-gray-500 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={columns.some(
(col) => !col.name.trim() || !col.prompt.trim(),
)}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
{isEditing ? "Save changes" : "Add columns"}
</button>
</div>
</div>
</form>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,532 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Check, ChevronDown, Loader2, Upload, X } from "lucide-react";
import type { MikeDocument, MikeProject, MikeWorkflow } from "../shared/types";
import {
getProject,
listProjects,
listStandaloneDocuments,
listWorkflows,
uploadProjectDocument,
uploadStandaloneDocument,
} from "@/app/lib/mikeApi";
import { FileDirectory } from "../shared/FileDirectory";
import { BUILT_IN_WORKFLOWS } from "../workflows/builtinWorkflows";
interface Props {
open: boolean;
onClose: () => void;
onAdd: (
title: string,
projectId?: string,
documentIds?: string[],
columnsConfig?: MikeWorkflow["columns_config"],
) => void;
projects?: MikeProject[];
/** When provided, skip the project/directory picker and show only these docs */
projectDocs?: MikeDocument[];
projectName?: string;
projectCmNumber?: string | null;
}
export function AddNewTRModal({
open,
onClose,
onAdd,
projects = [],
projectDocs: fixedProjectDocs,
projectName,
projectCmNumber,
}: Props) {
const isProjectMode = fixedProjectDocs !== undefined;
const [title, setTitle] = useState("");
const [underProject, setUnderProject] = useState(false);
const [selectedProjectId, setSelectedProjectId] = useState("");
const [projectDropdownOpen, setProjectDropdownOpen] = useState(false);
// Project-scoped docs (when underProject is true and no fixedProjectDocs)
const [projectDocs, setProjectDocs] = useState<MikeDocument[]>([]);
const [loadingDocs, setLoadingDocs] = useState(false);
// Full directory (when underProject is false)
const [standaloneDocs, setStandaloneDocs] = useState<MikeDocument[]>([]);
const [directoryProjects, setDirectoryProjects] = useState<MikeProject[]>(
[],
);
const [loadingDirectory, setLoadingDirectory] = useState(false);
const [selectedDocIds, setSelectedDocIds] = useState<Set<string>>(
new Set(),
);
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// Workflow templates
const [workflows, setWorkflows] = useState<MikeWorkflow[]>([]);
const [loadingWorkflows, setLoadingWorkflows] = useState(false);
const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(
null,
);
const [workflowDropdownOpen, setWorkflowDropdownOpen] = useState(false);
useEffect(() => {
if (!open) return;
setLoadingWorkflows(true);
const builtinTabular = BUILT_IN_WORKFLOWS.filter(
(w) => w.type === "tabular",
);
listWorkflows("tabular")
.then((custom) => setWorkflows([...builtinTabular, ...custom]))
.catch(() => setWorkflows(builtinTabular))
.finally(() => setLoadingWorkflows(false));
if (isProjectMode) {
setSelectedDocIds(
new Set((fixedProjectDocs ?? []).map((d) => d.id)),
);
return;
}
setLoadingDirectory(true);
// /projects only returns counts, not the documents array — fetch
// each project in parallel so FileDirectory can render the docs
// when the user expands a folder.
Promise.all([listStandaloneDocuments(), listProjects()])
.then(async ([docs, projs]) => {
setStandaloneDocs(
[...docs].sort((a, b) =>
(b.created_at ?? "").localeCompare(a.created_at ?? ""),
),
);
const fullProjects = await Promise.all(
projs.map((p) => getProject(p.id)),
);
setDirectoryProjects(fullProjects);
})
.catch(() => {
setStandaloneDocs([]);
setDirectoryProjects([]);
})
.finally(() => setLoadingDirectory(false));
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
if (!open) return null;
function handleClose() {
setTitle("");
setUnderProject(false);
setSelectedProjectId("");
setProjectDropdownOpen(false);
setProjectDocs([]);
setStandaloneDocs([]);
setDirectoryProjects([]);
setSelectedDocIds(new Set());
setSelectedWorkflowId(null);
setWorkflowDropdownOpen(false);
onClose();
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!title.trim()) return;
if (underProject && !selectedProjectId) return;
const selectedWorkflow = workflows.find(
(w) => w.id === selectedWorkflowId,
);
onAdd(
title.trim(),
underProject ? selectedProjectId : undefined,
selectedDocIds.size > 0 ? [...selectedDocIds] : undefined,
selectedWorkflow?.columns_config ?? undefined,
);
handleClose();
}
async function handleSelectProject(projectId: string) {
setSelectedProjectId(projectId);
setProjectDropdownOpen(false);
setProjectDocs([]);
setSelectedDocIds(new Set());
setLoadingDocs(true);
try {
const proj = await getProject(projectId);
const docs = (proj.documents ?? []).filter(
(d) => d.status === "ready",
);
setProjectDocs(docs);
setSelectedDocIds(new Set(docs.map((d) => d.id)));
} finally {
setLoadingDocs(false);
}
}
async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files ?? []);
if (!files.length) return;
setUploading(true);
try {
const uploaded = await Promise.all(
files.map((f) =>
underProject && selectedProjectId
? uploadProjectDocument(selectedProjectId, f)
: uploadStandaloneDocument(f),
),
);
if (underProject && selectedProjectId) {
setProjectDocs((prev) => [...uploaded, ...prev]);
} else {
setStandaloneDocs((prev) => [...uploaded, ...prev]);
}
uploaded.forEach((d) =>
setSelectedDocIds((prev) => new Set([...prev, d.id])),
);
} catch (err) {
console.error("Upload failed:", err);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
const selectedProject = projects.find((p) => p.id === selectedProjectId);
const selectedWorkflow = workflows.find((w) => w.id === selectedWorkflowId);
// What to show in the directory depends on mode and toggle state
const directoryStandalone = isProjectMode
? (fixedProjectDocs ?? [])
: underProject
? []
: standaloneDocs;
const directoryFolders = isProjectMode
? []
: underProject
? []
: directoryProjects;
const flatProjectDocs: MikeDocument[] =
!isProjectMode && underProject ? projectDocs : [];
const directoryLoading = isProjectMode
? false
: underProject
? loadingDocs
: loadingDirectory;
const showDirectory = isProjectMode || !underProject || !!selectedProjectId;
return createPortal(
<div className="fixed inset-0 z-[101] flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-6 pt-5 pb-2 shrink-0">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{isProjectMode && projectName ? (
<>
<span>Projects</span>
<span></span>
<span>
{projectName}
{projectCmNumber ? ` (#${projectCmNumber})` : ""}
</span>
<span></span>
<span>Tabular Reviews</span>
<span></span>
<span>New review</span>
</>
) : (
<>
<span>Tabular Reviews</span>
<span></span>
<span>New review</span>
</>
)}
</div>
<button
onClick={handleClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
<form
onSubmit={handleSubmit}
className="flex flex-col min-h-0 flex-1"
>
<div className="px-6 pt-3 pb-4 space-y-5 overflow-y-auto flex-1">
{/* Title */}
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Review name"
className="w-full text-2xl font-serif text-gray-800 placeholder-gray-400 focus:outline-none bg-transparent"
autoFocus
/>
{/* Workflow template */}
<div className="space-y-2">
<p className="text-xs font-medium text-gray-700">
Workflow Template
</p>
<div className="relative">
<button
type="button"
onClick={() =>
setWorkflowDropdownOpen((o) => !o)
}
disabled={loadingWorkflows}
className="flex items-center justify-between w-full rounded-lg border border-gray-200 px-3 py-2 text-sm hover:border-gray-400 focus:outline-none bg-white transition-colors"
>
<div className="flex items-center gap-2 min-w-0">
{loadingWorkflows && (
<Loader2 className="h-3.5 w-3.5 animate-spin text-gray-400 shrink-0" />
)}
<span
className={
selectedWorkflow
? "text-gray-800 truncate"
: "text-gray-400"
}
>
{loadingWorkflows
? "Loading templates…"
: selectedWorkflow
? selectedWorkflow.title
: "No template — start from scratch"}
</span>
</div>
<ChevronDown className="h-3.5 w-3.5 text-gray-400 shrink-0 ml-2" />
</button>
{workflowDropdownOpen && !loadingWorkflows && (
<div className="absolute left-0 top-full z-20 mt-1 w-full rounded-xl border border-gray-100 bg-white shadow-lg overflow-y-auto max-h-52">
<button
type="button"
onClick={() => {
setSelectedWorkflowId(null);
setWorkflowDropdownOpen(false);
}}
className={`w-full text-left flex items-center gap-2 px-3 py-2 text-sm transition-colors hover:bg-gray-50 ${!selectedWorkflowId ? "bg-gray-50 text-gray-900" : "text-gray-500"}`}
>
<span className="flex-1">
No template start from scratch
</span>
{!selectedWorkflowId && (
<Check className="h-3.5 w-3.5 text-gray-500 shrink-0" />
)}
</button>
{workflows.length > 0 && (
<div className="border-t border-gray-100" />
)}
{workflows.map((wf) => (
<button
key={wf.id}
type="button"
onClick={() => {
setSelectedWorkflowId(
wf.id,
);
setWorkflowDropdownOpen(
false,
);
}}
className={`w-full text-left flex items-center gap-2 px-3 py-2 text-sm transition-colors hover:bg-gray-50 ${selectedWorkflowId === wf.id ? "bg-gray-50 text-gray-900" : "text-gray-700"}`}
>
<span className="flex-1 truncate">
{wf.title}
</span>
{selectedWorkflowId ===
wf.id && (
<Check className="h-3.5 w-3.5 text-gray-500 shrink-0" />
)}
</button>
))}
</div>
)}
</div>
</div>
{/* Create under a project toggle */}
{!isProjectMode && <div className="space-y-3">
<button
type="button"
onClick={() => {
const next = !underProject;
setUnderProject(next);
if (!next) {
setSelectedProjectId("");
setProjectDropdownOpen(false);
setProjectDocs([]);
setSelectedDocIds(new Set());
}
}}
className="flex items-center gap-2.5 w-fit"
>
<span
className={`relative inline-flex h-5 w-9 shrink-0 rounded-full transition-colors duration-200 ${underProject ? "bg-gray-900" : "bg-gray-200"}`}
>
<span
className={`absolute top-0.5 left-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition-transform duration-200 ${underProject ? "translate-x-4" : "translate-x-0"}`}
/>
</span>
<span className="text-sm text-gray-600">
Create under a project
</span>
</button>
{underProject && (
<div className="relative">
<button
type="button"
onClick={() =>
setProjectDropdownOpen((o) => !o)
}
className="flex items-center justify-between w-full rounded-lg border border-gray-200 px-3 py-2 text-sm hover:border-gray-400 focus:outline-none bg-white transition-colors"
>
<span
className={
selectedProject
? "text-gray-800"
: "text-gray-400"
}
>
{selectedProject
? selectedProject.name +
(selectedProject.cm_number
? ` (#${selectedProject.cm_number})`
: "")
: "Select project…"}
</span>
<ChevronDown className="h-3.5 w-3.5 text-gray-400 shrink-0" />
</button>
{projectDropdownOpen && (
<div className="absolute left-0 top-full z-20 mt-1 w-full rounded-xl border border-gray-100 bg-white shadow-lg overflow-y-auto max-h-48">
{projects.length === 0 ? (
<p className="px-3 py-2 text-xs text-gray-400">
No projects found
</p>
) : (
projects.map((p) => (
<button
key={p.id}
type="button"
onClick={() =>
handleSelectProject(
p.id,
)
}
className={`w-full text-left flex items-center justify-between px-3 py-2 text-sm transition-colors hover:bg-gray-50 ${selectedProjectId === p.id ? "bg-gray-50 text-gray-900" : "text-gray-700"}`}
>
<span className="truncate">
{p.name}
{p.cm_number && (
<span className="ml-1 text-gray-400">
(#
{
p.cm_number
}
)
</span>
)}
</span>
{selectedProjectId ===
p.id && (
<Check className="h-3.5 w-3.5 text-gray-500 shrink-0" />
)}
</button>
))
)}
</div>
)}
</div>
)}
</div>}
{/* File directory */}
{showDirectory && (
<div className="space-y-2">
<p className="text-xs font-medium text-gray-700">
Select Documents
</p>
<div>
<FileDirectory
standaloneDocs={
isProjectMode
? directoryStandalone
: underProject
? flatProjectDocs
: directoryStandalone
}
directoryProjects={
isProjectMode
? []
: underProject
? []
: directoryFolders
}
loading={directoryLoading}
selectedIds={selectedDocIds}
onChange={setSelectedDocIds}
heading={isProjectMode ? "Project Documents" : "Documents"}
emptyMessage={
isProjectMode || underProject
? "No ready documents in this project"
: "No documents yet"
}
/>
</div>
</div>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between gap-2 border-t border-gray-100 px-6 py-4 shrink-0">
<div>
<input
ref={fileInputRef}
type="file"
accept=".pdf,.docx,.doc"
multiple
className="hidden"
onChange={handleUpload}
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50 disabled:opacity-50 transition-colors"
>
{uploading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Upload className="h-3.5 w-3.5" />
)}
{uploading ? "Uploading…" : "Upload"}
</button>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleClose}
className="rounded-lg px-4 py-2 text-sm text-gray-500 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={
!title.trim() ||
(underProject && !selectedProjectId)
}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
Create
</button>
</div>
</div>
</form>
</div>
</div>,
document.body,
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,307 @@
"use client";
import { useEffect, useState } from "react";
import { ChevronDown, Loader2, MoreHorizontal, Plus, Trash2, X } from "lucide-react";
import type { ColumnConfig, ColumnFormat } from "../shared/types";
import { generateTabularColumnPrompt } from "@/app/lib/mikeApi";
import { FORMAT_OPTIONS, formatLabel, formatIcon } from "./columnFormat";
import { TAG_COLORS } from "./pillUtils";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
export interface TREditColumnMenuProps {
column: ColumnConfig;
disabled?: boolean;
onSave: (column: ColumnConfig) => void | Promise<void>;
onDelete: (columnIndex: number) => void | Promise<void>;
}
export function TREditColumnMenu({
column,
disabled,
onSave,
onDelete,
}: TREditColumnMenuProps) {
const [open, setOpen] = useState(false);
const [name, setName] = useState(column.name);
const [prompt, setPrompt] = useState(column.prompt);
const [format, setFormat] = useState<ColumnFormat>(column.format ?? "text");
const [tags, setTags] = useState<string[]>(column.tags ?? []);
const [tagInput, setTagInput] = useState("");
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState(false);
const [generating, setGenerating] = useState(false);
useEffect(() => {
if (!open) {
setName(column.name);
setPrompt(column.prompt);
setFormat(column.format ?? "text");
setTags(column.tags ?? []);
setTagInput("");
}
}, [column.name, column.prompt, column.format, column.tags, open]);
function commitTag() {
const tag = tagInput.trim();
if (!tag) {
setTagInput("");
return;
}
setTags((prev) => (prev.includes(tag) ? prev : [...prev, tag]));
setTagInput("");
}
function handleTagKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
commitTag();
} else if (
e.key === "Backspace" &&
tagInput === "" &&
tags.length > 0
) {
setTags((prev) => prev.slice(0, -1));
}
}
async function handleSave() {
setSaving(true);
try {
await onSave({
...column,
name: name.trim(),
prompt: prompt.trim(),
format,
tags: format === "tag" ? tags : undefined,
});
setOpen(false);
} finally {
setSaving(false);
}
}
console.log(tags);
async function handleDelete() {
setDeleting(true);
try {
await onDelete(column.index);
setOpen(false);
} finally {
setDeleting(false);
}
}
async function handleAutoGenerate() {
if (!name.trim()) return;
setGenerating(true);
try {
const { prompt } = await generateTabularColumnPrompt(name.trim(), {
format,
tags: format === "tag" ? tags : undefined,
});
setPrompt(prompt);
} finally {
setGenerating(false);
}
}
return (
<div className="relative shrink-0" onClick={(e) => e.stopPropagation()}>
<button
onClick={(e) => {
e.stopPropagation();
if (disabled) return;
setOpen((v) => !v);
}}
disabled={disabled}
className={`flex h-4 w-4 items-center justify-center rounded transition-colors ${
disabled
? "text-gray-300 cursor-default"
: "text-gray-400 hover:bg-gray-100 hover:text-gray-600"
}`}
>
<MoreHorizontal className="h-4 w-4" />
</button>
{open && (
<div
className="absolute right-0 top-full z-20 mt-1.5 w-72 rounded-xl border border-gray-100 bg-white p-3 shadow-lg"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between mb-3">
<p className="text-sm font-medium text-gray-800">
Edit Column
</p>
<button
type="button"
onClick={() => setOpen(false)}
className="rounded p-0.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
<label className="text-xs font-medium text-gray-800">
Label
</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
className="mt-1 w-full rounded-md border border-gray-200 px-2 py-1 text-gray-800 text-xs font-normal focus:border-gray-400 focus:outline-none"
/>
{/* Format */}
<div className="mt-3">
<label className="text-xs font-medium text-gray-800">
Format
</label>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="mt-1 flex w-full items-center justify-between rounded-md border border-gray-200 bg-white px-2 py-1 text-xs text-gray-700 hover:border-gray-400 focus:outline-none">
<span className="flex items-center gap-1.5">
{(() => {
const Icon = formatIcon(format);
return (
<Icon className="h-3 w-3 text-gray-400" />
);
})()}
{formatLabel(format)}
</span>
<ChevronDown className="h-3 w-3 text-gray-400" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="start"
style={{
width: "var(--radix-dropdown-menu-trigger-width)",
}}
>
<DropdownMenuRadioGroup
value={format}
onValueChange={(v) => {
setFormat(v as ColumnFormat);
setTags([]);
setTagInput("");
}}
>
{FORMAT_OPTIONS.map((o) => (
<DropdownMenuRadioItem
key={o.value}
value={o.value}
className="text-xs"
>
<o.icon className="h-3 w-3 text-gray-400" />
{o.label}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Tag input */}
{format === "tag" && (
<div className="mt-2">
<div className="flex flex-wrap gap-1 rounded-md border border-gray-200 px-2 py-1 focus-within:border-gray-400 min-h-[28px]">
{tags.map((tag, tagIdx) => (
<span
key={tag}
className={`inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-[10px] ${TAG_COLORS[tagIdx % TAG_COLORS.length]}`}
>
{tag}
<button
type="button"
onClick={() =>
setTags((prev) =>
prev.filter(
(t) => t !== tag,
),
)
}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-2 w-2" />
</button>
</span>
))}
<input
type="text"
value={tagInput}
onChange={(e) =>
setTagInput(e.target.value)
}
onKeyDown={handleTagKeyDown}
onBlur={commitTag}
placeholder={
tags.length === 0 ? "Add tags…" : ""
}
className="min-w-[60px] flex-1 bg-transparent text-xs text-gray-700 placeholder-gray-300 focus:outline-none"
/>
</div>
</div>
)}
{/* Prompt */}
<div className="mt-3">
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-gray-800">
Prompt
</label>
<button
type="button"
onClick={handleAutoGenerate}
disabled={!name.trim() || generating}
className="inline-flex items-center gap-1 text-xs text-gray-600 transition-colors hover:text-gray-700 disabled:text-gray-300"
>
{generating ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Plus className="h-3 w-3" />
)}
Auto-generate
</button>
</div>
<textarea
rows={6}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
className="mt-2 w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-xs font-normal text-gray-800 placeholder-gray-300 focus:border-gray-400 focus:outline-none resize-none leading-relaxed"
/>
</div>
<div className="mt-3 flex items-center justify-between gap-2">
<button
type="button"
onClick={handleDelete}
disabled={deleting || saving}
className="inline-flex items-center gap-1.5 text-xs text-red-500 transition-colors hover:text-red-600 disabled:text-red-300"
>
<Trash2 className="h-3.5 w-3.5" />
Delete
</button>
<button
type="button"
onClick={handleSave}
disabled={
saving ||
deleting ||
generating ||
!name.trim() ||
!prompt.trim()
}
className="rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white transition-colors hover:bg-gray-700 disabled:opacity-40"
>
{saving ? "Saving…" : "Save"}
</button>
</div>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,457 @@
"use client";
import { useEffect, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
ChevronDown,
ChevronLeft,
ChevronRight,
Loader2,
RefreshCw,
X,
} from "lucide-react";
import type { ColumnConfig, MikeDocument, TabularCell } from "../shared/types";
import { preprocessCitations, type ParsedCitation } from "./citation-utils";
import { getPillClass } from "./pillUtils";
import { DocView } from "../shared/DocView";
import { DocxView } from "../shared/DocxView";
function isDocxDocument(d: {
file_type?: string | null;
filename?: string;
}): boolean {
const ft = (d.file_type ?? "").toLowerCase();
if (ft === "docx" || ft === "doc") return true;
const ext = d.filename?.split(".").pop()?.toLowerCase();
return ext === "docx" || ext === "doc";
}
interface Props {
cell: TabularCell;
document: MikeDocument;
column: ColumnConfig;
columns: ColumnConfig[];
onClose: () => void;
onNavigate: (columnIndex: number) => void;
onRegenerate?: () => Promise<void>;
/** If true, open the document panel immediately */
displayDocument?: boolean;
/** Quote to highlight when opening document panel */
citationQuote?: string;
/** Page to scroll to when opening document panel */
citationPage?: number;
}
const FLAG_BADGE: Record<string, string> = {
green: "bg-emerald-600 backdrop-blur-md border border-emerald-300/20 text-white shadow-md",
grey: "bg-slate-500 backdrop-blur-md border border-slate-300/20 text-white shadow-md",
yellow: "bg-amber-500 backdrop-blur-md border border-amber-300/20 text-white shadow-md",
red: "bg-red-600 backdrop-blur-md border border-red-300/20 text-white shadow-md",
};
// ---------------------------------------------------------------------------
// TRSidePanel
// ---------------------------------------------------------------------------
export function TRSidePanel({
cell,
document: doc,
column,
columns,
onClose,
onNavigate,
onRegenerate,
displayDocument = false,
citationQuote,
citationPage,
}: Props) {
const sortedColumns = [...columns].sort((a, b) => a.index - b.index);
const currentPos = sortedColumns.findIndex((c) => c.index === column.index);
const prevColumn = currentPos > 0 ? sortedColumns[currentPos - 1] : null;
const nextColumn =
currentPos < sortedColumns.length - 1
? sortedColumns[currentPos + 1]
: null;
const [regenerating, setRegenerating] = useState(false);
const [quoteExpanded, setQuoteExpanded] = useState(false);
const [isTruncated, setIsTruncated] = useState(false);
const quoteParagraphRef = useRef<HTMLParagraphElement>(null);
// Internal state — initialised from props, also toggled by badge clicks inside the panel
const [docCitation, setDocCitation] = useState<
{ quote: string; page: number } | undefined
>(
displayDocument && citationQuote
? { quote: citationQuote, page: citationPage ?? 1 }
: undefined,
);
// Re-sync when the panel opens for a different cell or citation
useEffect(() => {
setDocCitation(
displayDocument && citationQuote
? { quote: citationQuote, page: citationPage ?? 1 }
: undefined,
);
setQuoteExpanded(false);
}, [cell.id, displayDocument, citationQuote, citationPage]);
useEffect(() => {
const el = quoteParagraphRef.current;
if (!el || quoteExpanded) return;
setIsTruncated(el.scrollWidth > el.clientWidth);
}, [docCitation?.quote, quoteExpanded]);
const { processed: summaryText, citations: summaryCitations } =
preprocessCitations(cell.content?.summary ?? "");
const { processed: reasoningText, citations: reasoningCitations } =
preprocessCitations(cell.content?.reasoning ?? "");
useEffect(() => {
console.log("[TRSidePanel] summary:", cell.content?.summary ?? "");
}, [cell.id, cell.content?.summary]);
return (
<div
className="fixed right-0 top-0 bottom-0 z-100 flex flex-row shadow-md border-l border-gray-200"
style={{
background: "rgba(255,255,255,0.08)",
backdropFilter: "blur(10px) saturate(50%)",
WebkitBackdropFilter: "blur(10px) saturate(50%)",
}}
>
{/* Document panel — left, 600px */}
{docCitation !== undefined && (
<div className="relative flex w-[600px] shrink-0 flex-col border-r border-white/30 px-3">
{/* Doc header */}
<div className="flex items-center gap-2 pt-3 shrink-0 border-b border-white/30">
<p
className="flex-1 truncate text-sm font-semibold font-sans text-slate-700 font-serif"
title={doc.filename}
>
{doc.filename}
</p>
<button
onClick={() => setDocCitation(undefined)}
className="shrink-0 rounded-lg p-1.5 text-slate-400 transition-colors hover:bg-white/40 hover:text-slate-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Quote row */}
{docCitation.quote && (
<div className="py-2 shrink-0">
<div className="w-full rounded-md bg-gray-50 border border-gray-200 px-2 py-2">
<button
onClick={() =>
isTruncated || quoteExpanded
? setQuoteExpanded((v) => !v)
: undefined
}
className={`flex w-full items-start gap-1 text-left ${!(isTruncated || quoteExpanded) ? "cursor-default" : ""}`}
>
<p
ref={quoteParagraphRef}
className={`flex-1 text-sm text-gray-600 ${quoteExpanded ? "" : "truncate"}`}
>
"{docCitation.quote}"
</p>
{(isTruncated || quoteExpanded) && (
<ChevronDown
className={`mt-0.5 h-3 w-3 shrink-0 text-gray-500 transition-transform ${quoteExpanded ? "rotate-180" : ""}`}
/>
)}
</button>
</div>
</div>
)}
{isDocxDocument(doc) && !doc.pdf_storage_path ? (
<DocxView
documentId={doc.id}
quotes={[
{
page: docCitation.page,
quote: docCitation.quote,
},
]}
/>
) : (
<DocView
doc={{ document_id: doc.id }}
quote={docCitation.quote}
fallbackPage={docCitation.page}
/>
)}
</div>
)}
{/* Info column — right, 300px fixed */}
<div className="flex w-[300px] shrink-0 flex-col overflow-hidden">
{/* Header */}
<div className="flex items-center justify-end gap-3 px-5 pt-3 pb-1 shrink-0 border-b border-white/30">
<div className="flex items-center gap-1 mr-auto">
<button
onClick={() =>
prevColumn && onNavigate(prevColumn.index)
}
disabled={!prevColumn}
title={prevColumn ? prevColumn.name : undefined}
className="rounded-lg p-0.5 text-slate-600 transition-colors hover:bg-slate-200 hover:text-slate-900 disabled:opacity-30 disabled:cursor-default"
>
<ChevronLeft className="h-4 w-4" />
</button>
<span className="text-xs text-slate-600 font-sans tabular-nums">
{currentPos + 1} / {sortedColumns.length}
</span>
<button
onClick={() =>
nextColumn && onNavigate(nextColumn.index)
}
disabled={!nextColumn}
title={nextColumn ? nextColumn.name : undefined}
className="rounded-lg p-0.5 text-slate-600 transition-colors hover:bg-slate-200 hover:text-slate-900 disabled:opacity-30 disabled:cursor-default"
>
<ChevronRight className="h-4 w-4" />
</button>
</div>
{onRegenerate && (
<button
onClick={async () => {
setRegenerating(true);
try {
await onRegenerate();
} finally {
setRegenerating(false);
}
}}
disabled={regenerating}
title="Regenerate"
className="rounded-lg p-1.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600 disabled:opacity-40"
>
{regenerating ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<RefreshCw className="h-4 w-4" />
)}
</button>
)}
<button
onClick={onClose}
className="rounded-lg p-1.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Analysis panel */}
<div className="flex-1 overflow-y-auto">
<div className="pb-2 px-5">
{/* Column name */}
<div className="mb-1">
<span className="text-lg font-semibold text-slate-900">
{column.name}
</span>
</div>
{/* Document name */}
<p className="text-xs mb-4">{doc.filename}</p>
{/* Flag section */}
{cell.content?.flag && (
<div className="mb-5">
<h4 className="mb-2 text-sm font-semibold tracking-wider font-sans">
Flag
</h4>
<span
className={`inline-flex rounded-full px-3 py-1 text-xs font-semibold ${FLAG_BADGE[cell.content.flag] ?? FLAG_BADGE.grey}`}
>
{cell.content.flag.charAt(0).toUpperCase() +
cell.content.flag.slice(1)}
</span>
</div>
)}
{/* Results */}
<div className="mb-6">
<h4 className="mb-2 text-sm font-semibold tracking-wider font-sans">
Results
</h4>
<div className="text-xs leading-relaxed text-slate-600">
<MarkdownContent
citations={summaryCitations}
onCitationClick={setDocCitation}
column={column}
>
{summaryText || "—"}
</MarkdownContent>
</div>
</div>
{/* Reasoning */}
{cell.content?.reasoning && (
<div>
<h4 className="mb-2 text-sm font-semibold tracking-wider font-sans">
Reasoning
</h4>
<div className="text-xs leading-relaxed text-slate-600">
<MarkdownContent
citations={reasoningCitations}
onCitationClick={setDocCitation}
citationOffset={summaryCitations.length}
column={column}
inline
>
{reasoningText}
</MarkdownContent>
</div>
</div>
)}
</div>
</div>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Markdown renderer
// ---------------------------------------------------------------------------
function CitationBadge({
index,
citation,
onClick,
}: {
index: number;
citation: ParsedCitation;
onClick: (c: { quote: string; page: number }) => void;
}) {
return (
<button
type="button"
data-page={citation.page}
data-quote={citation.quote}
title={`Page ${citation.page}: "${citation.quote}"`}
onClick={() =>
onClick({ quote: citation.quote, page: citation.page })
}
className="inline-flex items-center justify-center rounded-full bg-gray-200 w-3.5 h-3.5 text-[9px] font-medium text-gray-700 align-super cursor-pointer hover:bg-gray-300 transition-colors"
>
{index + 1}
</button>
);
}
function MarkdownContent({
children,
citations,
onCitationClick,
citationOffset = 0,
column,
inline,
}: {
children: string;
citations: ParsedCitation[];
onCitationClick: (c: { quote: string; page: number }) => void;
inline?: boolean;
citationOffset?: number;
column?: ColumnConfig;
}) {
if (!children) return null;
const pills: string[] = [];
let processed = children.replace(/\[\[([^\]]+)\]\]/g, (_, content) => {
const idx = pills.length;
pills.push(content);
return `\`§p${idx}§\``;
});
processed = processed.replace(/§(\d+)§/g, (_, idx) => `\`§c${idx}§\``);
return (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
p: ({ node, ...props }) =>
inline ? (
<span {...props} />
) : (
<p
className="mb-1.5 last:mb-0 leading-relaxed"
{...props}
/>
),
ul: ({ node, ...props }) => (
<ul
className="list-disc pl-4 space-y-0.5 mb-1.5 last:mb-0"
{...props}
/>
),
ol: ({ node, ...props }) => (
<ol
className="list-decimal pl-4 space-y-0.5 mb-1.5 last:mb-0"
{...props}
/>
),
li: ({ node, ...props }) => <li {...props} />,
strong: ({ node, ...props }) => (
<strong className="font-semibold" {...props} />
),
em: ({ node, ...props }) => (
<em className="italic" {...props} />
),
a: ({ node, href, children, ...props }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:text-blue-700 underline"
{...props}
>
{children}
</a>
),
code: ({ node, children: codeChildren, ...props }) => {
const t = String(codeChildren);
const citMatch = t.match(/^§c(\d+)§$/);
if (citMatch) {
const idx = parseInt(citMatch[1]);
const citation = citations[idx];
if (citation) {
return (
<CitationBadge
index={citationOffset + idx}
citation={citation}
onClick={onCitationClick}
/>
);
}
}
const pillMatch = t.match(/^§p(\d+)§$/);
if (pillMatch) {
const content = pills[parseInt(pillMatch[1])];
if (content !== undefined) {
return (
<span
className={`inline-block rounded-full px-1.5 py-0.5 text-[11px] font-medium leading-none ${getPillClass(content, column)}`}
>
{content}
</span>
);
}
}
return (
<code
className="bg-gray-100 px-1 py-0.5 rounded text-[11px] font-mono"
{...props}
>
{codeChildren}
</code>
);
},
}}
>
{processed}
</ReactMarkdown>
);
}

View file

@ -0,0 +1,326 @@
"use client";
import { forwardRef, useImperativeHandle, useRef } from "react";
import { Plus, Table2 } from "lucide-react";
import type { ColumnConfig, MikeDocument, TabularCell } from "../shared/types";
import { TabularCell as TabularCellComponent } from "./TabularCell";
import { TREditColumnMenu } from "./TREditColumnMenu";
const SKELETON_COLS = 4;
const SKELETON_ROWS = 5;
const COL_W = "w-[300px] shrink-0";
const CHECK_W = "w-8 shrink-0";
// Pixel widths matching the CSS constants above
const CHECK_W_PX = 32; // w-8 = 2rem = 32px
const DOC_COL_W_PX = 300;
const DATA_COL_W_PX = 300;
const STICKY_LEFT_PX = CHECK_W_PX + DOC_COL_W_PX; // 332px
export interface TRTableHandle {
scrollToCell: (colIdx: number, rowIdx: number) => void;
}
interface Props {
loading: boolean;
columns: ColumnConfig[];
documents: MikeDocument[];
cells: TabularCell[];
savingColumn: boolean;
savingColumnsConfig: boolean;
selectedDocIds: string[];
highlightedCell?: { colIdx: number; rowIdx: number } | null;
onSelectionChange: (ids: string[]) => void;
onExpand: (cell: TabularCell) => void;
onCitationClick: (cell: TabularCell, page: number, quote: string) => void;
onUpdateColumn: (col: ColumnConfig) => void;
onDeleteColumn: (colIndex: number) => void;
onAddColumn: () => void;
onAddDocuments: () => void;
}
export const TRTable = forwardRef<TRTableHandle, Props>(function TRTable(
{
loading,
columns,
documents,
cells,
savingColumn,
savingColumnsConfig,
selectedDocIds,
highlightedCell,
onSelectionChange,
onExpand,
onCitationClick,
onUpdateColumn,
onDeleteColumn,
onAddColumn,
onAddDocuments,
},
ref,
) {
const scrollContainerRef = useRef<HTMLDivElement>(null);
const sortedColumns = [...columns].sort((a, b) => a.index - b.index);
const totalContentWidth =
CHECK_W_PX + DOC_COL_W_PX + sortedColumns.length * DATA_COL_W_PX + 32;
useImperativeHandle(ref, () => ({
scrollToCell(colIdx: number, rowIdx: number) {
const container = scrollContainerRef.current;
if (!container) return;
// Vertical: find actual row via DOM (handles variable row heights)
const allRows = container.querySelectorAll<HTMLElement>(
":scope > div.flex.min-w-full",
);
const targetRow = allRows[rowIdx];
if (targetRow) {
container.scrollTo({
top: Math.max(0, targetRow.offsetTop - 40),
behavior: "smooth",
});
}
// Horizontal: fixed column widths — center the target column in view
const targetScrollLeft =
STICKY_LEFT_PX +
colIdx * DATA_COL_W_PX -
container.clientWidth / 2 +
DATA_COL_W_PX / 2;
container.scrollLeft = Math.max(0, targetScrollLeft);
},
}));
function getCell(docId: string, colIdx: number) {
return cells.find(
(c) => c.document_id === docId && c.column_index === colIdx,
);
}
const allSelected =
documents.length > 0 &&
documents.every((d) => selectedDocIds.includes(d.id));
const someSelected =
!allSelected && documents.some((d) => selectedDocIds.includes(d.id));
function toggleAll() {
if (allSelected) {
onSelectionChange([]);
} else {
onSelectionChange(documents.map((d) => d.id));
}
}
function toggleDoc(id: string) {
if (selectedDocIds.includes(id)) {
onSelectionChange(selectedDocIds.filter((x) => x !== id));
} else {
onSelectionChange([...selectedDocIds, id]);
}
}
if (loading) {
return (
<div className="flex-1 overflow-hidden">
{/* Header */}
<div className="flex border-b border-gray-200">
<div
className={`${CHECK_W} border-r border-gray-200 p-2`}
/>
<div
className={`${COL_W} border-r border-gray-200 p-2 text-xs font-medium text-gray-500`}
>
Document
</div>
{Array.from({ length: SKELETON_COLS }).map((_, i) => (
<div
key={i}
className={`${COL_W} border-r border-gray-200 p-2`}
>
<div className="h-4 w-28 rounded bg-gray-100 animate-pulse" />
</div>
))}
<div className="flex-1" />
</div>
{/* Rows */}
{Array.from({ length: SKELETON_ROWS }).map((_, row) => (
<div
key={row}
className={`flex border-b border-gray-50 ${row % 2 === 0 ? "bg-white" : "bg-gray-50/50"}`}
>
<div className={`${CHECK_W} p-2`} />
<div className={`${COL_W} p-2`}>
<div className="h-4 w-32 rounded bg-gray-100 animate-pulse" />
</div>
{Array.from({ length: SKELETON_COLS }).map((_, col) => (
<div key={col} className={`${COL_W} p-2`}>
<div className="h-4 rounded bg-gray-100 animate-pulse" />
</div>
))}
<div className="flex-1" />
</div>
))}
</div>
);
}
if (columns.length === 0 && documents.length === 0) {
return (
<div className="flex flex-1 flex-col overflow-hidden">
<div className="flex items-center border-b border-gray-200">
<div className={`${CHECK_W} border-r border-gray-200`} />
<div
className={`${COL_W} border-r border-gray-200 p-2 text-xs font-medium text-gray-500 select-none`}
>
Document
</div>
<div className="flex-1" />
</div>
<div className="flex flex-1 flex-col items-start justify-center w-full max-w-xs mx-auto">
<Table2 className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Tabular Review
</p>
<p className="mt-1 text-xs text-gray-400 text-left">
Add columns and documents to get started.
</p>
<div className="mt-4 flex items-center gap-2">
<button
onClick={onAddColumn}
className="inline-flex items-center gap-1 rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white transition-colors hover:bg-gray-700 shadow-md"
>
+ Add Columns
</button>
<button
onClick={onAddDocuments}
className="inline-flex items-center gap-1.5 rounded-full border border-gray-200 bg-white px-3 py-1 text-xs font-medium text-gray-600 hover:bg-gray-50 transition-colors shadow-sm"
>
<Plus className="h-3.5 w-3.5" />
Add Documents
</button>
</div>
</div>
</div>
);
}
return (
<div className="flex-1 overflow-auto" ref={scrollContainerRef}>
{/* Header */}
<div
className="sticky top-0 z-20 flex bg-white h-8"
style={{ minWidth: totalContentWidth }}
>
<div
className={`sticky left-0 z-30 ${CHECK_W} bg-white border-b border-r border-gray-200 flex justify-center items-center select-none`}
>
<input
type="checkbox"
checked={allSelected}
ref={(el) => {
if (el) el.indeterminate = someSelected;
}}
onChange={toggleAll}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
<div
className={`sticky left-8 z-30 ${COL_W} bg-white border-b border-r border-gray-200 p-2 text-left text-xs font-medium text-gray-500 select-none`}
>
Document
</div>
{columns.map((col) => (
<div
key={col.index}
className={`${COL_W} border-b border-r border-gray-200 p-2 text-left text-xs font-medium text-gray-500 select-none`}
>
<div className="flex items-center justify-between gap-3">
<span className="truncate">{col.name}</span>
<TREditColumnMenu
column={col}
disabled={savingColumn || savingColumnsConfig}
onSave={onUpdateColumn}
onDelete={onDeleteColumn}
/>
</div>
</div>
))}
<div className="flex-1 border-b border-gray-200 flex items-center justify-start p-2 min-w-8">
<button
onClick={onAddColumn}
disabled={savingColumn || savingColumnsConfig}
className="flex items-center justify-center text-gray-400 hover:text-gray-700 transition-colors disabled:text-gray-200"
>
<Plus className="h-4 w-4" />
</button>
</div>
</div>
{/* Rows */}
{documents.map((doc, docIdx) => {
const rowBg = selectedDocIds.includes(doc.id)
? "bg-gray-100"
: docIdx % 2 === 0
? "bg-white"
: "bg-gray-50";
return (
<div
key={doc.id}
className={`flex ${rowBg}`}
style={{ minWidth: totalContentWidth }}
>
<div
className={`sticky left-0 z-[60] ${CHECK_W} border-b border-r border-gray-200 p-2 flex items-center justify-center ${rowBg}`}
>
<input
type="checkbox"
checked={selectedDocIds.includes(doc.id)}
onChange={() => toggleDoc(doc.id)}
className="h-2.5 w-2.5 shrink-0 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
<div
className={`sticky left-8 z-[60] ${COL_W} border-b border-r border-gray-200 p-2 text-xs text-gray-800 flex items-center ${rowBg}`}
>
<span className="line-clamp-1" title={doc.filename}>
{doc.filename}
</span>
</div>
{columns.map((col) => {
const cell = getCell(doc.id, col.index);
const colPos = sortedColumns.findIndex(
(c) => c.index === col.index,
);
const isHighlighted =
highlightedCell?.colIdx === colPos &&
highlightedCell?.rowIdx === docIdx;
return (
<div
key={col.index}
className={`${COL_W} border-b border-r border-gray-200 transition-colors ${isHighlighted ? "bg-blue-200" : ""}`}
>
{cell && (
<TabularCellComponent
cell={cell}
column={col}
onExpand={() => onExpand(cell)}
onCitationClick={(page, quote) =>
onCitationClick(
cell,
page,
quote,
)
}
/>
)}
</div>
);
})}
<div className="flex-1 border-b border-gray-200 min-h-8 min-w-8" />
</div>
);
})}
</div>
);
});

View file

@ -0,0 +1,268 @@
"use client";
import { useEffect, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { AlertCircle, Expand } from "lucide-react";
import type { ColumnConfig, TabularCell as TCell } from "../shared/types";
import { preprocessCitations, type ParsedCitation } from "./citation-utils";
import { getPillClass } from "./pillUtils";
interface Props {
cell: TCell;
column?: ColumnConfig;
onExpand: () => void;
onCitationClick?: (page: number, quote: string) => void;
}
const FLAG_STYLES = {
green: "bg-green-500",
grey: "bg-gray-400",
yellow: "bg-amber-400",
red: "bg-red-500",
} as const;
// Replace citations and pills with inline-code tokens so ReactMarkdown passes
// them through its `code` component, where we render the final UI.
function preprocessCellMarkdown(text: string): {
processed: string;
citations: ParsedCitation[];
pills: string[];
} {
const { processed: withCits, citations } = preprocessCitations(text);
const pills: string[] = [];
let out = withCits.replace(/\[\[([^\]]+)\]\]/g, (_, content) => {
const idx = pills.length;
pills.push(content);
return `\`§p${idx}§\`\u200B`;
});
out = out.replace(/§(\d+)§/g, (_, idx) => `\`§c${idx}§\`\u200B`);
return { processed: out, citations, pills };
}
function CellMarkdown({
text,
citations,
pills,
column,
onCitationClick,
onExpand,
inline,
}: {
text: string;
citations: ParsedCitation[];
pills: string[];
column?: ColumnConfig;
onCitationClick?: (page: number, quote: string) => void;
onExpand: () => void;
inline?: boolean;
}) {
return (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
p: ({ node, ...props }) =>
inline ? (
<span {...props} />
) : (
<p className="mb-1 last:mb-0 leading-relaxed" {...props} />
),
ul: ({ node, ...props }) => (
<ul className="list-disc pl-4 space-y-0.5" {...props} />
),
ol: ({ node, ...props }) => (
<ol className="list-decimal pl-4 space-y-0.5" {...props} />
),
li: ({ node, ...props }) => <li {...props} />,
strong: ({ node, ...props }) => (
<strong className="font-semibold" {...props} />
),
em: ({ node, ...props }) => <em className="italic" {...props} />,
a: ({ node, href, children, ...props }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:text-blue-700 underline"
{...props}
>
{children}
</a>
),
code: ({ node, children, ...props }) => {
const t = String(children);
const citMatch = t.match(/^§c(\d+)§$/);
if (citMatch) {
const idx = parseInt(citMatch[1]);
const citation = citations[idx];
if (citation) {
return (
<span
title={`Page ${citation.page}: "${citation.quote}"`}
onClick={(e) => {
e.stopPropagation();
if (onCitationClick) {
onCitationClick(
citation.page,
citation.quote,
);
} else {
onExpand();
}
}}
className="mx-0.5 inline-flex items-center justify-center rounded-full bg-gray-200 w-3.5 h-3.5 text-[9px] font-medium text-gray-700 align-super cursor-pointer hover:bg-gray-300 transition-colors"
>
{idx + 1}
</span>
);
}
}
const pillMatch = t.match(/^§p(\d+)§$/);
if (pillMatch) {
const content = pills[parseInt(pillMatch[1])];
if (content !== undefined) {
return (
<span
className={`inline-block rounded-full px-1.5 py-0.5 text-[10px] font-medium leading-none ${getPillClass(content, column)}`}
>
{content}
</span>
);
}
}
return (
<code
className="bg-gray-100 px-1 py-0.5 rounded text-[11px] font-mono"
{...props}
>
{children}
</code>
);
},
}}
>
{text}
</ReactMarkdown>
);
}
export function TabularCell({
cell,
column,
onExpand,
onCitationClick,
}: Props) {
const [inlineExpanded, setInlineExpanded] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!inlineExpanded) return;
function handleClickOutside(e: MouseEvent) {
if (
containerRef.current &&
!containerRef.current.contains(e.target as Node)
) {
setInlineExpanded(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () =>
document.removeEventListener("mousedown", handleClickOutside);
}, [inlineExpanded]);
if (cell.status === "generating") {
return (
<div className="h-10 px-2 flex items-center">
<div className="h-4 w-full rounded bg-gray-100 animate-pulse" />
</div>
);
}
if (cell.status === "error") {
return (
<div className="h-10 flex items-center justify-center text-gray-300">
<AlertCircle className="h-4 w-4 text-red-300" />
</div>
);
}
if (!cell.content?.summary) {
return <div className="h-10" />;
}
const { processed, citations, pills } = preprocessCellMarkdown(
cell.content.summary,
);
const firstLine = processed.split("\n").find((l) => l.trim()) ?? processed;
const collapsedDisplay = firstLine.replace(/^[-*•]\s+/, "");
function handleCitationClickInOverlay(page: number, quote: string) {
setInlineExpanded(false);
onCitationClick?.(page, quote);
}
function handleSeeDetails() {
setInlineExpanded(false);
onExpand();
}
return (
<div ref={containerRef} className="relative">
{/* Normal cell row — always visible, preserves table layout */}
<div
className="group relative h-10 px-2 flex items-center text-xs text-gray-800 leading-relaxed cursor-pointer hover:bg-gray-50 transition-colors"
onClick={() => setInlineExpanded((v) => !v)}
>
{cell.content.flag && (
<span
className={`absolute right-1.5 top-1.5 h-1.5 w-1.5 rounded-full ${FLAG_STYLES[cell.content.flag]}`}
title={cell.content.flag}
/>
)}
<div className="line-clamp-1 w-full min-w-0">
<CellMarkdown
text={collapsedDisplay}
citations={citations}
pills={pills}
column={column}
onCitationClick={onCitationClick}
onExpand={onExpand}
inline
/>
</div>
</div>
{/* Inline expanded overlay — absolutely positioned so it overlays without disrupting table layout */}
{inlineExpanded && (
<div className="absolute left-0 top-0 z-50 w-full bg-white border border-gray-200 shadow-lg rounded-sm">
<div className="relative p-2 pr-4 text-xs text-gray-800 leading-relaxed">
{cell.content.flag && (
<span
className={`absolute right-1.5 top-1.5 h-1.5 w-1.5 rounded-full ${FLAG_STYLES[cell.content.flag]}`}
title={cell.content.flag}
/>
)}
<CellMarkdown
text={processed}
citations={citations}
pills={pills}
column={column}
onCitationClick={handleCitationClickInOverlay}
onExpand={handleSeeDetails}
/>
</div>
<div className="px-2 py-1.5 flex items-center justify-end">
<button
onClick={handleSeeDetails}
className="flex items-center gap-1 text-xs text-gray-400 hover:text-gray-700 transition-colors"
>
<Expand className="h-3 w-3" />
See details
</button>
</div>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,853 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Plus, Loader2, Play, ChevronDown, MessageSquare, Download, Users } from "lucide-react";
import { HeaderSearchBtn } from "../shared/HeaderSearchBtn";
import {
clearTabularCells,
getTabularReview,
getProject,
getTabularReviewPeople,
regenerateTabularCell,
streamTabularGeneration,
updateTabularReview,
} from "@/app/lib/mikeApi";
import type {
ColumnConfig,
MikeDocument,
MikeProject,
TabularCell,
TabularReview,
} from "../shared/types";
import { AddColumnModal } from "./AddColumnModal";
import { AddDocumentsModal } from "../shared/AddDocumentsModal";
import { AddProjectDocsModal } from "../shared/AddProjectDocsModal";
import { PeopleModal } from "../shared/PeopleModal";
import { OwnerOnlyModal } from "../shared/OwnerOnlyModal";
import { ApiKeyMissingModal } from "../shared/ApiKeyMissingModal";
import { RenameableTitle } from "../shared/RenameableTitle";
import { useAuth } from "@/contexts/AuthContext";
import { useUserProfile } from "@/contexts/UserProfileContext";
import {
getModelProvider,
isModelAvailable,
type ModelProvider,
} from "@/app/lib/modelAvailability";
import { TRSidePanel } from "./TRSidePanel";
import { TRTable } from "./TRTable";
import type { TRTableHandle } from "./TRTable";
import { TRChatPanel } from "./TRChatPanel";
import { exportTabularReviewToExcel } from "./exportToExcel";
import { useSidebar } from "@/app/contexts/SidebarContext";
interface Props {
reviewId: string;
projectId?: string;
}
export function TRView({ reviewId, projectId }: Props) {
const { setSidebarOpen } = useSidebar();
const [review, setReview] = useState<TabularReview | null>(null);
const [project, setProject] = useState<MikeProject | null>(null);
const [cells, setCells] = useState<TabularCell[]>([]);
const [documents, setDocuments] = useState<MikeDocument[]>([]);
const [columns, setColumns] = useState<ColumnConfig[]>([]);
const [loading, setLoading] = useState(true);
const [generating, setGenerating] = useState(false);
const [savingColumn, setSavingColumn] = useState(false);
const [savingColumnsConfig, setSavingColumnsConfig] = useState(false);
const [addColOpen, setAddColOpen] = useState(false);
const [addDocsOpen, setAddDocsOpen] = useState(false);
const [peopleModalOpen, setPeopleModalOpen] = useState(false);
const [ownerOnlyAction, setOwnerOnlyAction] = useState<string | null>(null);
const { user } = useAuth();
const [expandedCell, setExpandedCell] = useState<TabularCell | null>(null);
const [expandedCellCitation, setExpandedCellCitation] = useState<
{ quote: string; page: number } | undefined
>(undefined);
const [selectedDocIds, setSelectedDocIds] = useState<string[]>([]);
const [actionsOpen, setActionsOpen] = useState(false);
const [search, setSearch] = useState("");
const searchParams = useSearchParams();
const initialChatParamRef = useRef<string | null>(
searchParams.get("chat"),
);
const [chatOpen, setChatOpen] = useState(!!initialChatParamRef.current);
const [selectedChatId, setSelectedChatId] = useState<string | null>(
initialChatParamRef.current && initialChatParamRef.current !== "new"
? initialChatParamRef.current
: null,
);
const [highlightedCell, setHighlightedCell] = useState<{ colIdx: number; rowIdx: number } | null>(null);
const [apiKeyModalProvider, setApiKeyModalProvider] =
useState<ModelProvider | null>(null);
const actionsRef = useRef<HTMLDivElement>(null);
const tableRef = useRef<TRTableHandle>(null);
const router = useRouter();
const { profile } = useUserProfile();
const apiKeys = {
claudeApiKey: profile?.claudeApiKey ?? null,
geminiApiKey: profile?.geminiApiKey ?? null,
};
const tabularModel = profile?.tabularModel ?? "gemini-3-flash-preview";
useEffect(() => {
const params = new URLSearchParams(window.location.search);
if (chatOpen) {
params.set("chat", selectedChatId ?? "new");
} else {
params.delete("chat");
}
const query = params.toString();
const newUrl = `${window.location.pathname}${query ? `?${query}` : ""}`;
window.history.replaceState(null, "", newUrl);
}, [chatOpen, selectedChatId]);
useEffect(() => {
if (!actionsOpen) return;
function handleClickOutside(e: MouseEvent) {
if (
actionsRef.current &&
!actionsRef.current.contains(e.target as Node)
)
setActionsOpen(false);
}
document.addEventListener("mousedown", handleClickOutside);
return () =>
document.removeEventListener("mousedown", handleClickOutside);
}, [actionsOpen]);
useEffect(() => {
const fetches: Promise<unknown>[] = [
getTabularReview(reviewId).then(({ review, cells, documents }) => {
setReview(review);
setCells(cells);
setDocuments(documents);
setColumns(review.columns_config || []);
}),
];
if (projectId) {
fetches.push(
getProject(projectId)
.then(setProject)
.catch(() => {}),
);
}
Promise.all(fetches).finally(() => setLoading(false));
}, [reviewId, projectId]);
function getNextColumnIndex() {
return (
columns.reduce((max, column) => Math.max(max, column.index), -1) + 1
);
}
async function saveColumnsConfig(nextColumns: ColumnConfig[]) {
setSavingColumnsConfig(true);
try {
const updated = await updateTabularReview(reviewId, {
columns_config: nextColumns,
document_ids: documents.map((document) => document.id),
});
setReview(updated);
setColumns(updated.columns_config || nextColumns);
} finally {
setSavingColumnsConfig(false);
}
}
async function handleAddDocuments(newDocs: MikeDocument[]) {
const toAdd = newDocs.filter(
(d) => !documents.some((existing) => existing.id === d.id),
);
if (!toAdd.length) return;
const allIds = [
...documents.map((d) => d.id),
...toAdd.map((d) => d.id),
];
await updateTabularReview(reviewId, {
document_ids: allIds,
columns_config: columns,
});
setDocuments((prev) => [...prev, ...toAdd]);
if (columns.length > 0) {
setCells((prev) => [
...prev,
...toAdd.flatMap((doc) =>
columns.map((col) => ({
id: `new-${doc.id}-${col.index}`,
review_id: reviewId,
document_id: doc.id,
column_index: col.index,
content: null,
status: "pending" as const,
created_at: new Date().toISOString(),
})),
),
]);
}
}
async function handleRegenerateCell(docId: string, colIndex: number) {
setCells((prev) =>
prev.map((c) =>
c.document_id === docId && c.column_index === colIndex
? { ...c, status: "generating" as const, content: null }
: c,
),
);
setExpandedCell((prev) =>
prev
? { ...prev, status: "generating" as const, content: null }
: null,
);
try {
const result = await regenerateTabularCell(
reviewId,
docId,
colIndex,
);
setCells((prev) =>
prev.map((c) =>
c.document_id === docId && c.column_index === colIndex
? { ...c, status: "done" as const, content: result }
: c,
),
);
setExpandedCell((prev) =>
prev
? { ...prev, status: "done" as const, content: result }
: null,
);
} catch (err) {
console.error("Regeneration failed", err);
setCells((prev) =>
prev.map((c) =>
c.document_id === docId && c.column_index === colIndex
? { ...c, status: "error" as const }
: c,
),
);
setExpandedCell((prev) =>
prev ? { ...prev, status: "error" as const } : null,
);
}
}
async function handleGenerate() {
if (!review || generating) return;
// If columns changed since last save, update the review first
if (columns.length === 0) return;
if (!isModelAvailable(tabularModel, apiKeys)) {
setApiKeyModalProvider(getModelProvider(tabularModel));
return;
}
setGenerating(true);
// Optimistically set empty/pending/error cells to generating (skip done cells)
setCells((prev) =>
documents.flatMap((doc) =>
columns.map((col) => {
const existing = prev.find(
(c) =>
c.document_id === doc.id &&
c.column_index === col.index,
);
if (existing?.status === "done" && existing?.content) {
return existing;
}
return existing
? {
...existing,
status: "generating" as const,
content: null,
}
: {
id: `${doc.id}-${col.index}`,
review_id: reviewId,
document_id: doc.id,
column_index: col.index,
content: null,
status: "generating" as const,
created_at: new Date().toISOString(),
};
}),
),
);
try {
const response = await streamTabularGeneration(reviewId);
if (!response.body) throw new Error("No body");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.startsWith("data:")) continue;
const dataStr = line.slice(5).trim();
if (dataStr === "[DONE]") break;
try {
const data = JSON.parse(dataStr);
if (data.type === "cell_update") {
setCells((prev) =>
prev.map((c) =>
c.document_id === data.document_id &&
c.column_index === data.column_index
? {
...c,
content: data.content,
status: data.status,
}
: c,
),
);
}
} catch {}
}
}
} catch (err) {
console.error("Generation failed", err);
} finally {
setGenerating(false);
}
}
async function handleAddColumn(newColumns: ColumnConfig[]) {
const startIndex = getNextColumnIndex();
const normalizedColumns = newColumns.map((column, index) => ({
...column,
index: startIndex + index,
}));
const newCols = [...columns, ...normalizedColumns];
setSavingColumn(true);
setColumns(newCols);
setCells((prev) => [
...prev,
...documents
.filter((doc) =>
normalizedColumns.some(
(column) =>
!prev.some(
(cell) =>
cell.document_id === doc.id &&
cell.column_index === column.index,
),
),
)
.flatMap((doc) =>
normalizedColumns
.filter(
(column) =>
!prev.some(
(cell) =>
cell.document_id === doc.id &&
cell.column_index === column.index,
),
)
.map((column) => ({
id: `new-${doc.id}-${column.index}`,
review_id: reviewId,
document_id: doc.id,
column_index: column.index,
content: null,
status: "pending" as const,
created_at: new Date().toISOString(),
})),
),
]);
try {
await saveColumnsConfig(newCols);
} catch (err) {
setColumns(columns);
setCells((prev) =>
prev.filter(
(cell) =>
!normalizedColumns.some(
(column) => column.index === cell.column_index,
),
),
);
console.error("Failed to save column", err);
} finally {
setSavingColumn(false);
}
}
async function handleUpdateColumn(nextColumn: ColumnConfig) {
const nextColumns = columns.map((column) =>
column.index === nextColumn.index ? nextColumn : column,
);
const previousColumns = columns;
setColumns(nextColumns);
try {
await saveColumnsConfig(nextColumns);
} catch (err) {
setColumns(previousColumns);
console.error("Failed to update column", err);
}
}
async function handleDeleteColumn(columnIndex: number) {
const previousColumns = columns;
const nextColumns = columns.filter(
(column) => column.index !== columnIndex,
);
setColumns(nextColumns);
try {
await saveColumnsConfig(nextColumns);
} catch (err) {
setColumns(previousColumns);
console.error("Failed to delete column", err);
}
}
function handleTabularCitationClick(colIdx: number, rowIdx: number) {
setSearch("");
setHighlightedCell({ colIdx, rowIdx });
setTimeout(() => {
tableRef.current?.scrollToCell(colIdx, rowIdx);
}, 50);
setTimeout(() => setHighlightedCell(null), 3000);
}
async function handleDeleteDocuments() {
const remaining = documents.filter(
(d) => !selectedDocIds.includes(d.id),
);
setDocuments(remaining);
setCells((prev) =>
prev.filter((c) => !selectedDocIds.includes(c.document_id)),
);
setSelectedDocIds([]);
setActionsOpen(false);
await updateTabularReview(reviewId, {
document_ids: remaining.map((d) => d.id),
columns_config: columns,
});
}
async function handleClearResults() {
const docIds = [...selectedDocIds];
if (docIds.length === 0) return;
setCells((prev) =>
prev.map((c) =>
docIds.includes(c.document_id)
? { ...c, content: null, status: "pending" }
: c,
),
);
setSelectedDocIds([]);
setActionsOpen(false);
await clearTabularCells(reviewId, docIds);
}
async function handleTitleCommit(newTitle: string) {
if (!newTitle || newTitle === review?.title) return;
setReview((prev) => (prev ? { ...prev, title: newTitle } : prev));
await updateTabularReview(reviewId, { title: newTitle });
}
const q = search.toLowerCase();
const filteredDocuments = q
? documents.filter((d) => d.filename.toLowerCase().includes(q))
: documents;
return (
<div className="flex h-full overflow-hidden bg-white">
<div className="flex flex-1 flex-col overflow-hidden">
{/* Header */}
<div className="bg-white px-8 py-4 flex items-start justify-between shrink-0 gap-4">
<div className="flex items-center gap-1.5 text-2xl font-medium font-serif">
{projectId && (
<>
<button
onClick={() => router.push("/projects")}
className="text-gray-500 hover:text-gray-700 transition-colors"
>
Projects
</button>
<span className="text-gray-300"></span>
<button
onClick={() =>
router.push(`/projects/${projectId}`)
}
className="text-gray-500 hover:text-gray-700 transition-colors"
>
{loading ? (
<div className="h-6 w-32 rounded bg-gray-100 animate-pulse" />
) : (
<>
{project?.name ?? ""}
{project?.cm_number && (
<span className="ml-1 text-gray-400">
(#{project.cm_number})
</span>
)}
</>
)}
</button>
<span className="text-gray-300"></span>
<button
onClick={() =>
router.push(
`/projects/${projectId}?tab=reviews`,
)
}
className="text-gray-500 hover:text-gray-700 transition-colors"
>
Tabular Reviews
</button>
</>
)}
{!projectId && (
<button
onClick={() => router.push("/tabular-reviews")}
className="text-gray-500 hover:text-gray-700 transition-colors"
>
Tabular Reviews
</button>
)}
<span className="text-gray-300"></span>
{loading ? (
<div className="h-6 w-40 rounded bg-gray-100 animate-pulse" />
) : (
<RenameableTitle
value={review?.title || "Untitled Review"}
onCommit={handleTitleCommit}
/>
)}
</div>
{!loading && (
<div className="flex items-center gap-2">
<HeaderSearchBtn value={search} onChange={setSearch} placeholder="Search documents…" />
{!projectId && (
<button
onClick={() => setPeopleModalOpen(true)}
disabled={loading}
className={`flex h-8 w-8 items-center justify-center text-sm transition-colors ${
loading
? "text-gray-300 cursor-default"
: "text-gray-500 hover:text-gray-900 cursor-pointer"
}`}
title="People with access"
aria-label="People with access"
>
<Users className="h-4 w-4" />
</button>
)}
<button
onClick={() =>
exportTabularReviewToExcel({
reviewTitle: review?.title || "Tabular Review",
columns,
documents,
cells,
})
}
disabled={columns.length === 0 || documents.length === 0}
title="Export to Excel"
className={`flex h-8 items-center justify-center gap-1.5 px-3 text-sm transition-colors ${
columns.length === 0 || documents.length === 0
? "text-gray-300 cursor-default"
: "text-gray-700 hover:text-gray-900 cursor-pointer"
}`}
>
<Download className="h-4 w-4" />
Export
</button>
<button
onClick={handleGenerate}
disabled={
generating ||
columns.length === 0 ||
documents.length === 0 ||
savingColumnsConfig
}
className={`flex h-8 items-center justify-center gap-1.5 px-3 text-sm transition-colors ${
generating ||
columns.length === 0 ||
documents.length === 0 ||
savingColumnsConfig
? "text-gray-300 cursor-default"
: "text-gray-700 hover:text-gray-900 cursor-pointer"
}`}
>
{generating ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
{generating ? "Running…" : "Run"}
</button>
</div>
)}
</div>
{/* Toolbar */}
<div className="flex items-center h-10 px-8 border-b border-gray-200 gap-4">
<button
onClick={() => {
if (!chatOpen) setSidebarOpen(false);
if (chatOpen) setSelectedChatId(null);
setChatOpen((v) => !v);
}}
disabled={loading || columns.length === 0 || documents.length === 0}
className={`flex items-center gap-1 text-xs font-medium transition-colors ${
loading || columns.length === 0 || documents.length === 0
? "text-gray-300 cursor-default"
: "text-gray-700 hover:text-gray-900"
}`}
>
<MessageSquare className="h-3.5 w-3.5" />
Assistant in Tabular Review
</button>
<div className="ml-auto flex items-center gap-4">
{selectedDocIds.length > 0 && (
<div ref={actionsRef} className="relative">
<button
onClick={() => setActionsOpen((v) => !v)}
className="flex items-center gap-1 text-xs font-medium text-gray-600 hover:text-gray-900 transition-colors"
>
Actions
<ChevronDown className="h-3.5 w-3.5" />
</button>
{actionsOpen && (
<div className="absolute top-full right-0 mt-1 w-36 rounded-lg border border-gray-100 bg-white shadow-lg z-50 overflow-hidden">
<button
onClick={handleClearResults}
className="w-full px-3 py-1.5 text-left text-xs text-gray-700 hover:bg-gray-50 transition-colors"
>
Clear results
</button>
<button
onClick={handleDeleteDocuments}
className="w-full px-3 py-1.5 text-left text-xs text-red-600 hover:bg-red-50 transition-colors"
>
Delete
</button>
</div>
)}
</div>
)}
<button
onClick={() => setAddDocsOpen(true)}
disabled={loading || savingColumnsConfig}
className={`flex items-center gap-1 text-xs font-medium transition-colors ${
loading || savingColumnsConfig
? "text-gray-300 cursor-default"
: "text-gray-700 hover:text-gray-900"
}`}
>
<Plus className="h-3.5 w-3.5" />
Add Documents
</button>
<button
onClick={() => setAddColOpen(true)}
disabled={
loading || savingColumn || savingColumnsConfig
}
className={`flex items-center gap-1 text-xs font-medium transition-colors ${
loading || savingColumn || savingColumnsConfig
? "text-gray-300 cursor-default"
: "text-gray-700 hover:text-gray-900"
}`}
>
<Plus className="h-3.5 w-3.5" />
Add Columns
</button>
</div>
</div>
{/* Table area */}
<div className="flex flex-1 overflow-hidden">
{chatOpen && (
<TRChatPanel
reviewId={reviewId}
reviewTitle={review?.title ?? null}
projectName={project?.name ?? null}
columns={columns}
documents={documents}
onCitationClick={handleTabularCitationClick}
onClose={() => {
setSelectedChatId(null);
setChatOpen(false);
}}
initialChatId={selectedChatId}
onChatIdChange={setSelectedChatId}
/>
)}
<TRTable
ref={tableRef}
loading={loading}
columns={columns}
documents={filteredDocuments}
cells={cells}
highlightedCell={highlightedCell}
savingColumn={savingColumn}
savingColumnsConfig={savingColumnsConfig}
selectedDocIds={selectedDocIds}
onSelectionChange={setSelectedDocIds}
onExpand={(cell) => {
setExpandedCell(cell);
setExpandedCellCitation(undefined);
}}
onCitationClick={(cell, page, quote) => {
setExpandedCell(cell);
setExpandedCellCitation({ quote, page });
}}
onUpdateColumn={handleUpdateColumn}
onDeleteColumn={handleDeleteColumn}
onAddColumn={() => setAddColOpen(true)}
onAddDocuments={() => setAddDocsOpen(true)}
/>
</div>
</div>
{/* Cell detail side panel */}
{expandedCell &&
(() => {
const expandedDoc = documents.find(
(d) => d.id === expandedCell.document_id,
);
const expandedCol = columns.find(
(c) => c.index === expandedCell.column_index,
);
if (!expandedDoc || !expandedCol) return null;
return (
<TRSidePanel
cell={expandedCell}
document={expandedDoc}
column={expandedCol}
columns={columns}
onClose={() => {
setExpandedCell(null);
setExpandedCellCitation(undefined);
}}
onNavigate={(columnIndex) => {
const nextCell = cells.find(
(c) =>
c.document_id ===
expandedCell.document_id &&
c.column_index === columnIndex,
);
if (nextCell) {
setExpandedCell(nextCell);
setExpandedCellCitation(undefined);
}
}}
onRegenerate={() =>
handleRegenerateCell(
expandedCell.document_id,
expandedCell.column_index,
)
}
displayDocument={expandedCellCitation !== undefined}
citationQuote={expandedCellCitation?.quote}
citationPage={expandedCellCitation?.page}
/>
);
})()}
<AddColumnModal
open={addColOpen}
existingCount={columns.length}
onClose={() => setAddColOpen(false)}
onAdd={handleAddColumn}
/>
{project ? (
<AddProjectDocsModal
open={addDocsOpen}
onClose={() => setAddDocsOpen(false)}
onSelect={(docs: MikeDocument[]) =>
handleAddDocuments(docs)
}
breadcrumb={[
"Projects",
project.name +
(project.cm_number
? ` (#${project.cm_number})`
: ""),
"Tabular Reviews",
...(review ? [review.title || "Untitled Review"] : []),
"Add Documents",
]}
projectId={project.id}
excludeDocIds={new Set(documents.map((d) => d.id))}
/>
) : (
<AddDocumentsModal
open={addDocsOpen}
onClose={() => setAddDocsOpen(false)}
onSelect={(docs: MikeDocument[]) =>
handleAddDocuments(docs)
}
breadcrumb={[
"Tabular Reviews",
...(review ? [review.title || "Untitled Review"] : []),
"Add Documents",
]}
/>
)}
<PeopleModal
open={peopleModalOpen}
onClose={() => setPeopleModalOpen(false)}
resource={review}
fetchPeople={getTabularReviewPeople}
currentUserEmail={user?.email ?? null}
breadcrumb={[
"Tabular Reviews",
review?.title || "Untitled Review",
"People",
]}
// Only the review owner may modify the member list. PeopleModal
// hides the add/remove controls when this prop is undefined.
onSharedWithChange={
review?.is_owner === false
? undefined
: async (next) => {
const updated = await updateTabularReview(
reviewId,
{ shared_with: next },
);
setReview((prev) =>
prev
? {
...prev,
shared_with: updated.shared_with,
}
: prev,
);
}
}
/>
<OwnerOnlyModal
open={!!ownerOnlyAction}
action={ownerOnlyAction ?? undefined}
onClose={() => setOwnerOnlyAction(null)}
/>
<ApiKeyMissingModal
open={apiKeyModalProvider !== null}
provider={apiKeyModalProvider}
onClose={() => setApiKeyModalProvider(null)}
/>
</div>
);
}

View file

@ -0,0 +1,26 @@
"use client";
const PAGE_CITATION_RE = /\[\[page:(\d+)\|\|(?:quote:)?((?:[^\[\]]|\[[^\]]*\])+)\]\]/gi;
export interface ParsedCitation {
page: number;
quote: string;
}
/**
* Replaces [[page:n||quote:...]] markers with `§idx§` placeholders.
* Returns the processed string and an ordered array of extracted citation data.
*/
export function preprocessCitations(text: string): {
processed: string;
citations: ParsedCitation[];
} {
const citations: ParsedCitation[] = [];
PAGE_CITATION_RE.lastIndex = 0;
const processed = text.replace(PAGE_CITATION_RE, (_, page, quote) => {
const idx = citations.length;
citations.push({ page: parseInt(page, 10), quote: quote.trim() });
return `§${idx}§`;
});
return { processed, citations };
}

View file

@ -0,0 +1,23 @@
import type { LucideIcon } from "lucide-react";
import { AlignLeft, List, Hash, DollarSign, ToggleLeft, Calendar, Tag, Percent, Banknote } from "lucide-react";
import type { ColumnFormat } from "../shared/types";
export const FORMAT_OPTIONS: Array<{ value: ColumnFormat; label: string; icon: LucideIcon }> = [
{ value: "text", label: "Free Text", icon: AlignLeft },
{ value: "bulleted_list", label: "Bulleted list", icon: List },
{ value: "number", label: "Number", icon: Hash },
{ value: "percentage", label: "Percentage", icon: Percent },
{ value: "monetary_amount", label: "Monetary Amount", icon: Banknote },
{ value: "currency", label: "Currency", icon: DollarSign },
{ value: "yes_no", label: "Yes / No", icon: ToggleLeft },
{ value: "date", label: "Date", icon: Calendar },
{ value: "tag", label: "Tags", icon: Tag },
];
export function formatLabel(format: ColumnFormat): string {
return FORMAT_OPTIONS.find((o) => o.value === format)?.label ?? "Text";
}
export function formatIcon(format: ColumnFormat): LucideIcon {
return FORMAT_OPTIONS.find((o) => o.value === format)?.icon ?? AlignLeft;
}

View file

@ -0,0 +1,104 @@
import type { ColumnFormat } from "../shared/types";
export interface ColumnPreset {
name: string;
matches: RegExp;
prompt: string;
format: ColumnFormat;
tags?: string[];
}
export const PROMPT_PRESETS: ColumnPreset[] = [
{
name: "Parties",
matches: /\bpart(y|ies)\b/i,
format: "bulleted_list",
prompt: 'List all parties to this agreement. For each party, state their full legal name, entity type, and defined role, e.g.:\n• ABC Corp, a Delaware corporation ("Company")\n• John Smith ("Shareholder")\nOne party per bullet. No additional commentary.',
},
{
name: "Governing Law",
matches: /\bgoverning law\b|\bjurisdiction\b/i,
format: "text",
prompt: 'State only the governing law of this agreement using the short-form jurisdiction name, e.g. "New York Law", "English Law", "Indian Law", "PRC Law". No other text.',
},
{
name: "Effective Date",
matches: /\beffective date\b/i,
format: "date",
prompt: 'State only the effective date of this agreement in DD Mon YYYY format, e.g. "2 Jan 2026". If not explicitly stated, write "Not specified".',
},
{
name: "Term",
matches: /\bterm\b|\bduration\b/i,
format: "text",
prompt: 'State only the duration or term of this agreement in a concise form, e.g. "3 years", "24 months", "perpetual". No other text.',
},
{
name: "Termination",
matches: /\bterminat(e|ion|ing)\b/i,
format: "text",
prompt: "Extract the termination provisions. State who may terminate, the trigger events, required notice period, any cure period, and the key consequences of termination. Be concise.",
},
{
name: "Change of Control",
matches: /\bchange of control\b/i,
format: "text",
prompt: "Identify any change of control provisions. Summarize the trigger events, consequences, consent requirements, and any related termination or acceleration rights. Be concise.",
},
{
name: "Confidentiality",
matches: /\bconfidential(ity)?\b|\bnon-?disclosure\b/i,
format: "text",
prompt: "Summarize the confidentiality obligations: scope of confidential information, permitted disclosures, use restrictions, duration, and key carve-outs or exceptions.",
},
{
name: "Assignment",
matches: /\bassign(ment|ability)?\b/i,
format: "yes_no",
prompt: "Is assignment of this agreement permitted without the other party's consent?",
},
{
name: "Payment & Fees",
matches: /\bpayment\b|\bfees?\b/i,
format: "text",
prompt: 'State the key payment obligations concisely: amount, timing, and currency, e.g. "USD 10,000 payable within 30 days of invoice". Note any late payment consequences.',
},
{
name: "Amendment",
matches: /\bamendment\b|\bvariation\b/i,
format: "text",
prompt: "Summarize the amendment provisions: how amendments may be made, who must consent, and any formality requirements such as writing or signature.",
},
{
name: "Indemnity",
matches: /\bindemni(ty|ties|fication)\b/i,
format: "text",
prompt: "Summarize the indemnity provisions: who indemnifies whom, the scope of indemnified losses, any liability caps or exclusions, and key claims procedures.",
},
{
name: "Warranties",
matches: /\bwarrant(y|ies|ing)\b|\brepresentations?\b/i,
format: "text",
prompt: "Identify and describe key representations and warranties provided by any party, including the scope of such assurances and any specific time periods or conditions applicable to them. In particular highlight any non-standard warranties.",
},
{
name: "Force Majeure",
matches: /\bforce majeure\b/i,
format: "yes_no",
prompt: "Does this agreement contain a force majeure clause?",
},
];
export function getPresetConfig(
title: string,
): Pick<ColumnPreset, "prompt" | "format" | "tags"> | null {
const trimmed = title.trim();
if (!trimmed) return null;
const preset = PROMPT_PRESETS.find(({ matches }) => matches.test(trimmed));
if (!preset) return null;
return { prompt: preset.prompt, format: preset.format, tags: preset.tags };
}
export function getPresetPrompt(title: string): string | null {
return getPresetConfig(title)?.prompt ?? null;
}

View file

@ -0,0 +1,81 @@
"use client";
import ExcelJS from "exceljs";
import type { ColumnConfig, MikeDocument, TabularCell } from "../shared/types";
import { preprocessCitations } from "./citation-utils";
function formatCellForExport(cell: TabularCell | undefined): string {
if (!cell) return "";
if (cell.status === "pending" || cell.status === "generating") return "";
if (cell.status === "error") return "Error";
const summary = cell.content?.summary;
if (!summary) return "";
const { processed } = preprocessCitations(summary);
return processed
.replace(/§\d+§/g, "")
.replace(/\[\[([^\]]+)\]\]/g, "$1")
.replace(/[ \t]+/g, " ")
.trim();
}
function sanitizeFilename(name: string): string {
return (
name
.replace(/[\\/:*?"<>|]/g, "")
.replace(/\s+/g, " ")
.trim()
.slice(0, 80) || "Tabular Review"
);
}
export async function exportTabularReviewToExcel(params: {
reviewTitle: string;
columns: ColumnConfig[];
documents: MikeDocument[];
cells: TabularCell[];
}) {
const { reviewTitle, columns, documents, cells } = params;
const sortedCols = [...columns].sort((a, b) => a.index - b.index);
const cellMap = new Map<string, TabularCell>();
for (const c of cells) cellMap.set(`${c.document_id}:${c.column_index}`, c);
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet("Review");
ws.columns = [
{ header: "Document", width: 40 },
...sortedCols.map((c) => ({ header: c.name, width: 40 })),
];
const headerRow = ws.getRow(1);
headerRow.font = { bold: true };
headerRow.alignment = { vertical: "middle" };
headerRow.fill = {
type: "pattern",
pattern: "solid",
fgColor: { argb: "FFF3F4F6" },
};
for (const doc of documents) {
const row: string[] = [doc.filename];
for (const col of sortedCols) {
row.push(formatCellForExport(cellMap.get(`${doc.id}:${col.index}`)));
}
const excelRow = ws.addRow(row);
excelRow.alignment = { vertical: "top", wrapText: true };
}
const buf = await wb.xlsx.writeBuffer();
const blob = new Blob([buf], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${sanitizeFilename(reviewTitle)}.xlsx`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}

View file

@ -0,0 +1,72 @@
import type { ColumnConfig } from "../shared/types";
export type PillSegment =
| { type: "text"; content: string }
| { type: "pill"; content: string };
/** Sequential colors assigned to tags by their position in the tags array. */
export const TAG_COLORS = [
"bg-blue-100 text-blue-700",
"bg-violet-100 text-violet-700",
"bg-pink-100 text-pink-700",
"bg-orange-100 text-orange-700",
"bg-teal-100 text-teal-700",
"bg-amber-100 text-amber-700",
"bg-indigo-100 text-indigo-700",
"bg-rose-100 text-rose-700",
];
const CURRENCY_COLORS: Record<string, string> = {
USD: "bg-green-100 text-green-700",
EUR: "bg-blue-100 text-blue-700",
GBP: "bg-purple-100 text-purple-700",
JPY: "bg-red-100 text-red-700",
CHF: "bg-orange-100 text-orange-700",
AUD: "bg-cyan-100 text-cyan-700",
CAD: "bg-teal-100 text-teal-700",
SGD: "bg-pink-100 text-pink-700",
HKD: "bg-rose-100 text-rose-700",
NZD: "bg-lime-100 text-lime-700",
CNY: "bg-amber-100 text-amber-700",
};
export function getPillClass(content: string, column?: ColumnConfig): string {
if (column?.format === "yes_no") {
const lower = content.toLowerCase();
if (lower === "yes") return "bg-green-100 text-green-700";
if (lower === "no") return "bg-red-100 text-red-700";
return "bg-gray-100 text-gray-700";
}
if (column?.format === "currency") {
return (
CURRENCY_COLORS[content.toUpperCase()] ??
"bg-slate-100 text-slate-700"
);
}
if (column?.format === "tag" && column.tags?.length) {
const idx = column.tags.findIndex(
(t) => t.toLowerCase() === content.toLowerCase(),
);
if (idx >= 0) return TAG_COLORS[idx % TAG_COLORS.length]!;
}
return "bg-gray-100 text-gray-700";
}
/** Split text on [[...]] pill markers, preserving surrounding text. */
export function parsePills(text: string): PillSegment[] {
const segments: PillSegment[] = [];
const regex = /\[\[([^\]]+)\]\]/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = regex.exec(text)) !== null) {
if (match.index > lastIndex) {
segments.push({ type: "text", content: text.slice(lastIndex, match.index) });
}
segments.push({ type: "pill", content: match[1] });
lastIndex = regex.lastIndex;
}
if (lastIndex < text.length) {
segments.push({ type: "text", content: text.slice(lastIndex) });
}
return segments;
}

View file

@ -0,0 +1,60 @@
const PROMPT_PRESETS: Array<{
matches: RegExp;
prompt: (title: string) => string;
}> = [
{
matches: /\bpart(y|ies)\b/i,
prompt: () =>
'Identify all parties referenced in the document. List their full names and describe each party\'s role or capacity in the agreement. If a party is not clearly identified, state "Not addressed".',
},
{
matches: /\bchange of control\b/i,
prompt: () =>
'Identify any change of control provisions in the document. Summarize the trigger, the consequences, any consent requirements, and any related termination, acceleration, or notice obligations. If not addressed, state "Not addressed".',
},
{
matches: /\bterminat(e|ion|ing)\b/i,
prompt: () =>
'Extract the termination provisions in the document. Summarize who may terminate, the termination triggers, any notice requirements, cure periods, and the consequences of termination. If not addressed, state "Not addressed".',
},
{
matches: /\bgoverning law\b|\bjurisdiction\b/i,
prompt: () =>
'Identify the governing law and jurisdiction provisions in the document. State the governing law, the forum for disputes, and any submission to jurisdiction or venue requirements. If not addressed, state "Not addressed".',
},
{
matches: /\bconfidential(ity)?\b|\bnon-?disclosure\b/i,
prompt: () =>
'Extract the confidentiality provisions in the document. Summarize the scope of confidential information, permitted disclosures, use restrictions, duration, and any carve-outs or exceptions. If not addressed, state "Not addressed".',
},
{
matches: /\bassign(ment|ability)?\b/i,
prompt: () =>
'Identify any assignment provisions in the document. Summarize whether assignment is permitted, restricted, or requires consent, and note any exceptions or deemed assignments. If not addressed, state "Not addressed".',
},
{
matches: /\bpayment\b|\bfees?\b/i,
prompt: () =>
'Extract the payment and fee terms in the document. Summarize payment obligations, amounts, timing, currencies, fee types, and any consequences for late or missed payment. If not addressed, state "Not addressed".',
},
];
export function getPresetTabularPrompt(title: string): string | null {
const trimmedTitle = title.trim();
if (!trimmedTitle) return null;
const preset = PROMPT_PRESETS.find(({ matches }) => matches.test(trimmedTitle));
return preset ? preset.prompt(trimmedTitle) : null;
}
export function buildFallbackTabularPrompt(title: string): string {
const trimmedTitle = title.trim();
if (!trimmedTitle) return "";
return (
`Review each document and extract the information relevant to "${trimmedTitle}". ` +
`Provide a concise, document-specific summary for this column. ` +
`Include the key facts, dates, thresholds, parties, and conditions where applicable. ` +
`If the document does not contain relevant information, return "Not addressed".`
);
}

View file

@ -0,0 +1,832 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import {
ChevronDown,
Folder,
MessageSquare,
Search,
Table2,
X,
} from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { MikeDocument, MikeWorkflow } from "../shared/types";
import { createTabularReview } from "@/app/lib/mikeApi";
import { useRouter } from "next/navigation";
import { formatIcon, formatLabel } from "../tabular/columnFormat";
import { useDirectoryData } from "../shared/useDirectoryData";
import { FileDirectory } from "../shared/FileDirectory";
import type { MikeProject } from "../shared/types";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
interface Props {
workflows: MikeWorkflow[];
workflow: MikeWorkflow | null;
onClose: () => void;
}
// ---------------------------------------------------------------------------
// Toggle switch
// ---------------------------------------------------------------------------
function Toggle({ on, onToggle }: { on: boolean; onToggle: () => void }) {
return (
<button
type="button"
onClick={onToggle}
className={`relative inline-flex h-5 w-9 shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ${on ? "bg-gray-900" : "bg-gray-200"}`}
>
<span
className={`pointer-events-none inline-block h-4 w-4 rounded-full bg-white shadow transition-transform duration-200 ${on ? "translate-x-4" : "translate-x-0"}`}
/>
</button>
);
}
// ---------------------------------------------------------------------------
// Simple project picker (input + dropdown)
// ---------------------------------------------------------------------------
function SimpleProjectPicker({
projects,
selectedId,
onSelect,
}: {
projects: MikeProject[];
selectedId: string | null;
onSelect: (id: string | null) => void;
}) {
const [search, setSearch] = useState("");
const [open, setOpen] = useState(false);
const selected = projects.find((p) => p.id === selectedId);
const filtered = search
? projects.filter((p) =>
p.name.toLowerCase().includes(search.toLowerCase()),
)
: projects;
return (
<div className="relative">
<input
type="text"
value={selectedId ? (selected?.name ?? "") : search}
onChange={(e) => {
setSearch(e.target.value);
setOpen(true);
onSelect(null);
}}
onFocus={() => setOpen(true)}
onBlur={() => setTimeout(() => setOpen(false), 150)}
placeholder="Select a project…"
className="w-full text-xs text-gray-700 placeholder:text-gray-400 bg-gray-50 border border-gray-200 rounded-md px-3 py-2 outline-none"
/>
{selectedId && (
<button
onMouseDown={() => {
onSelect(null);
setSearch("");
}}
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
<X className="h-3 w-3" />
</button>
)}
{open && !selectedId && (
<div className="absolute z-10 top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-md shadow-sm overflow-y-auto max-h-40">
{filtered.length === 0 ? (
<p className="px-3 py-3 text-xs text-gray-400 text-center">
No projects found
</p>
) : (
filtered.map((p) => (
<button
key={p.id}
onMouseDown={() => {
onSelect(p.id);
setSearch("");
setOpen(false);
}}
className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-left hover:bg-gray-50 text-gray-700"
>
<Folder className="h-3.5 w-3.5 shrink-0 text-gray-400" />
{p.name}
</button>
))
)}
</div>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Shared markdown renderer
// ---------------------------------------------------------------------------
function MarkdownBody({ content }: { content: string }) {
return (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
h1: ({ children }) => (
<h1 className="text-base font-semibold text-gray-900 mt-4 mb-1 first:mt-0">
{children}
</h1>
),
h2: ({ children }) => (
<h2 className="text-sm font-semibold text-gray-900 mt-3 mb-1 first:mt-0">
{children}
</h2>
),
h3: ({ children }) => (
<h3 className="text-xs font-semibold text-gray-900 mt-2 mb-0.5 first:mt-0">
{children}
</h3>
),
p: ({ children }) => (
<p className="mb-2 last:mb-0">{children}</p>
),
ul: ({ children }) => (
<ul className="list-disc pl-4 mb-2 space-y-0.5">
{children}
</ul>
),
ol: ({ children }) => (
<ol className="list-decimal pl-4 mb-2 space-y-0.5">
{children}
</ol>
),
li: ({ children }) => <li>{children}</li>,
strong: ({ children }) => (
<strong className="font-semibold text-gray-800">
{children}
</strong>
),
em: ({ children }) => <em className="italic">{children}</em>,
}}
>
{content}
</ReactMarkdown>
);
}
// ---------------------------------------------------------------------------
// Right panel for assistant workflows (select screen)
// ---------------------------------------------------------------------------
function AssistantPanel({ workflow }: { workflow: MikeWorkflow }) {
return (
<div className="flex-1 border-l border-t border-gray-200 flex flex-col overflow-hidden px-3 pb-3">
<div className="py-3 shrink-0">
<p className="text-xs font-medium text-gray-700">
Workflow Prompt
</p>
</div>
<div className="flex-1 overflow-y-auto px-4 py-3 text-sm border border-gray-200 rounded-md text-gray-600 leading-relaxed font-serif bg-gray-50">
<MarkdownBody
content={workflow.prompt_md ?? "_No prompt defined._"}
/>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Right panel for tabular workflows — accordion column list (select screen)
// ---------------------------------------------------------------------------
function TabularPanel({ workflow }: { workflow: MikeWorkflow }) {
const [expandedIndex, setExpandedIndex] = useState<number | null>(null);
const columns = (workflow.columns_config ?? []).sort(
(a, b) => a.index - b.index,
);
return (
<div className="flex-1 border-l border-t border-gray-200 flex flex-col overflow-hidden px-3 pb-3">
<div className="py-3 shrink-0">
<p className="text-xs font-medium text-gray-700">Columns</p>
</div>
<div className="flex-1 overflow-y-auto border border-gray-200 rounded-md bg-gray-50">
{columns.length === 0 ? (
<p className="px-4 py-6 text-xs text-center text-gray-400">
No columns defined
</p>
) : (
columns.map((col) => {
const isExpanded = expandedIndex === col.index;
const FormatIcon = formatIcon(col.format ?? "text");
return (
<div
key={col.index}
className="border-b border-gray-200"
>
<button
type="button"
onClick={() =>
setExpandedIndex(
isExpanded ? null : col.index,
)
}
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-xs text-left hover:bg-white transition-colors"
>
<FormatIcon className="h-3.5 w-3.5 shrink-0 text-gray-400" />
<span className="flex-1 truncate text-gray-800">
{col.name}
</span>
<span className="shrink-0 text-gray-400">
{formatLabel(col.format ?? "text")}
</span>
<ChevronDown
className={`h-3 w-3 shrink-0 text-gray-300 transition-transform duration-150 ${isExpanded ? "rotate-180" : ""}`}
/>
</button>
{isExpanded && (
<div className="px-4 py-3 bg-white border-t border-gray-200 text-sm text-gray-600 leading-relaxed font-serif space-y-3">
{col.tags && col.tags.length > 0 && (
<div>
<p className="text-xs font-medium text-gray-400 mb-1.5 font-sans">
Tags
</p>
<div className="flex flex-wrap gap-1.5">
{col.tags.map((tag) => (
<span
key={tag}
className="inline-block rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600 font-sans"
>
{tag}
</span>
))}
</div>
</div>
)}
<div>
<p className="text-xs font-medium text-gray-400 mb-1 font-sans">
Prompt
</p>
<MarkdownBody
content={
col.prompt ||
"_No prompt defined._"
}
/>
</div>
</div>
)}
</div>
);
})
)}
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// DisplayWorkflowModal
// ---------------------------------------------------------------------------
export function DisplayWorkflowModal({ workflows, workflow, onClose }: Props) {
const [screen, setScreen] = useState<"select" | "configure">("select");
const [selected, setSelected] = useState<MikeWorkflow | null>(workflow);
const [listSearch, setListSearch] = useState("");
const selectedRowRef = useRef<HTMLButtonElement>(null);
// Configure screen state
const [inProject, setInProject] = useState(false);
const [selectedProjectId, setSelectedProjectId] = useState<string | null>(
null,
);
const [selectedDocIds, setSelectedDocIds] = useState<Set<string>>(
new Set(),
);
const [docSearch, setDocSearch] = useState("");
const [assistantPrompt, setAssistantPrompt] = useState("");
const [saving, setSaving] = useState(false);
const router = useRouter();
const { saveChat, setNewChatMessages } = useChatHistoryContext();
const {
loading: dirLoading,
projects,
standaloneDocuments,
} = useDirectoryData(screen === "configure");
useEffect(() => {
if (workflow) {
setSelected(workflow);
setScreen("select");
setListSearch("");
} else {
setSelected(null);
}
}, [workflow?.id]);
useEffect(() => {
if (selected && selectedRowRef.current) {
selectedRowRef.current.scrollIntoView({ block: "nearest" });
}
}, [selected?.id]);
// Reset configure state on back
useEffect(() => {
if (screen === "select") {
setInProject(false);
setSelectedProjectId(null);
setSelectedDocIds(new Set());
setDocSearch("");
setAssistantPrompt("");
}
}, [screen]);
function handleClose() {
setSelected(null);
setScreen("select");
onClose();
}
if (!workflow) return null;
const wf = selected ?? workflow;
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
async function handleStartChat() {
setSaving(true);
try {
const projectId = inProject ? selectedProjectId! : undefined;
const chatId = await saveChat(projectId);
if (!chatId) return;
const allDocs: MikeDocument[] = [
...standaloneDocuments,
...projects.flatMap((p) => p.documents || []),
];
const files = allDocs
.filter((d) => selectedDocIds.has(d.id))
.map((d) => ({ filename: d.filename, document_id: d.id }));
const content = assistantPrompt.trim()
? `implement workflow\n\n${assistantPrompt.trim()}`
: "implement workflow";
setNewChatMessages([
{
role: "user",
content,
files: files.length > 0 ? files : undefined,
},
]);
handleClose();
router.push(
projectId
? `/projects/${projectId}/assistant/chat/${chatId}`
: `/assistant/chat/${chatId}`,
);
} finally {
setSaving(false);
}
}
async function handleCreateReview() {
const allDocs: MikeDocument[] = [
...standaloneDocuments,
...projects.flatMap((p) => p.documents || []),
];
const docIds = allDocs
.filter((d) => selectedDocIds.has(d.id))
.map((d) => d.id);
const projectId = inProject ? selectedProjectId! : undefined;
setSaving(true);
try {
const review = await createTabularReview({
title: wf.title,
document_ids: docIds,
columns_config: wf.columns_config || [],
workflow_id: wf.is_system ? undefined : wf.id,
project_id: projectId,
});
handleClose();
router.push(
projectId
? `/projects/${projectId}/tabular-reviews/${review.id}`
: `/tabular-reviews/${review.id}`,
);
} finally {
setSaving(false);
}
}
// ---------------------------------------------------------------------------
// Tabular doc browser helpers
// ---------------------------------------------------------------------------
const q = docSearch.toLowerCase().trim();
const selectedProject = projects.find((p) => p.id === selectedProjectId);
const projectDocs = selectedProject?.documents ?? [];
const filteredProjectDocs = q
? projectDocs.filter((d) => d.filename.toLowerCase().includes(q))
: projectDocs;
const filteredStandalone = q
? standaloneDocuments.filter((d) =>
d.filename.toLowerCase().includes(q),
)
: standaloneDocuments;
const filteredAllProjects = projects
.map((p) => ({
...p,
documents: (p.documents || []).filter(
(d) => !q || d.filename.toLowerCase().includes(q),
),
}))
.filter(
(p) =>
!q ||
p.name.toLowerCase().includes(q) ||
p.documents.length > 0,
);
// ---------------------------------------------------------------------------
// Render
// ---------------------------------------------------------------------------
return createPortal(
<div className="fixed inset-0 z-[101] flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div
className={`w-full rounded-2xl bg-white shadow-2xl flex flex-col h-[600px] transition-all duration-200 ${screen === "select" ? "max-w-4xl" : "max-w-2xl"}`}
>
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 shrink-0">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{screen === "select" ? (
<>
<span>Workflows</span>
<span></span>
<span>Select workflow</span>
</>
) : (
<>
<button
onClick={() => setScreen("select")}
className="hover:text-gray-700 transition-colors"
>
Workflows
</button>
<span></span>
<span className="truncate max-w-[160px]">
{wf.title}
</span>
<span></span>
<span>
{wf.type === "assistant"
? "New Chat"
: "New Review"}
</span>
</>
)}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* ── SELECT SCREEN ── */}
{screen === "select" && (
<>
<div className="flex flex-row flex-1 min-h-0 overflow-hidden">
{/* Left: workflow list */}
<div className="w-80 shrink-0 flex flex-col border-t border-gray-200">
{/* Search */}
<div className="px-3 py-2 shrink-0 border-b border-gray-100">
<div className="flex items-center gap-1.5 rounded-md border border-gray-200 bg-gray-50 px-2.5 py-1">
<Search className="h-3 w-3 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search…"
value={listSearch}
onChange={(e) => setListSearch(e.target.value)}
className="flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 outline-none"
/>
{listSearch && (
<button onClick={() => setListSearch("")} className="text-gray-400 hover:text-gray-600">
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
{/* List */}
<div className="overflow-y-auto flex-1">
{workflows
.filter((wfItem) => !listSearch || wfItem.title.toLowerCase().includes(listSearch.toLowerCase()))
.map((wfItem) => {
const isSelected = selected?.id === wfItem.id;
const Icon = wfItem.type === "tabular" ? Table2 : MessageSquare;
return (
<button
key={wfItem.id}
ref={isSelected ? selectedRowRef : null}
type="button"
onClick={() => setSelected(wfItem)}
className={`w-full flex items-center gap-3 px-4 py-3 text-xs text-left border-b border-gray-200 transition-colors ${isSelected ? "bg-gray-100" : "hover:bg-gray-50"}`}
>
<span className={`flex-1 truncate ${isSelected ? "text-gray-900 font-medium" : "text-gray-700"}`}>
{wfItem.title}
</span>
<Icon className="h-3.5 w-3.5 shrink-0 text-gray-400" />
</button>
);
})}
</div>
</div>
{/* Right: workflow detail */}
{wf.type === "assistant" ? (
<AssistantPanel key={wf.id} workflow={wf} />
) : (
<TabularPanel key={wf.id} workflow={wf} />
)}
</div>
<div className="border-t border-gray-200 px-5 py-3 flex items-center justify-between shrink-0">
{wf.is_system ? (
<button
onClick={() => {
router.push(`/workflows/${wf.id}`);
handleClose();
}}
className="rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-50 transition-colors"
>
View Page
</button>
) : (
<button
onClick={() => {
router.push(`/workflows/${wf.id}`);
handleClose();
}}
className="rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-50 transition-colors"
>
Edit
</button>
)}
<button
onClick={() => setScreen("configure")}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700"
>
Use
</button>
</div>
</>
)}
{/* ── ASSISTANT CONFIGURE SCREEN ── */}
{screen === "configure" && wf.type === "assistant" && (
<>
<div className="flex-1 min-h-0 flex flex-col overflow-hidden">
{/* Add-on prompt */}
<div className="px-5 pb-3 shrink-0">
<p className="text-xs font-medium text-gray-700 mb-2">
Message (optional)
</p>
<textarea
rows={3}
value={assistantPrompt}
onChange={(e) =>
setAssistantPrompt(e.target.value)
}
placeholder="Add any additional instructions to the workflow prompt…"
className="w-full text-sm text-gray-700 placeholder:text-gray-400 bg-gray-50 border border-gray-200 rounded-md px-3 py-2 resize-none outline-none leading-relaxed"
/>
</div>
{/* Toggle row */}
<div className="px-5 py-3 flex flex-col gap-2 shrink-0">
<span className="text-xs font-medium text-gray-700">
Create in a project
</span>
<Toggle
on={inProject}
onToggle={() => {
setInProject(!inProject);
setSelectedProjectId(null);
setSelectedDocIds(new Set());
setDocSearch("");
}}
/>
</div>
{inProject ? (
<>
<div className="px-5 pt-1 pb-1 shrink-0">
<p className="text-xs font-medium text-gray-700">
Select project
</p>
</div>
<div className="px-5 pb-2 shrink-0">
<SimpleProjectPicker
projects={projects}
selectedId={selectedProjectId}
onSelect={setSelectedProjectId}
/>
</div>
</>
) : (
<>
<div className="px-5 pt-1 pb-1 shrink-0">
<p className="text-xs font-medium text-gray-700">
Select documents
</p>
</div>
{/* Search */}
<div className="px-4 pt-1.5 pb-1 shrink-0">
<div className="flex items-center gap-1.5 rounded-md border border-gray-200 bg-gray-50 px-2.5 py-1">
<Search className="h-3 w-3 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search…"
value={docSearch}
onChange={(e) =>
setDocSearch(e.target.value)
}
className="flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 outline-none"
/>
{docSearch && (
<button
onClick={() =>
setDocSearch("")
}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
{/* File browser */}
<div className="flex-1 overflow-y-auto px-4 pb-2">
<FileDirectory
standaloneDocs={filteredStandalone}
directoryProjects={
filteredAllProjects
}
loading={dirLoading}
selectedIds={selectedDocIds}
onChange={setSelectedDocIds}
allowMultiple
forceExpanded={!!q}
emptyMessage={
q
? "No matches found"
: "No documents yet"
}
/>
</div>
</>
)}
</div>
<div className="border-t border-gray-200 px-5 py-3 flex items-center justify-between shrink-0">
<span className="text-xs text-gray-400">
{!inProject && selectedDocIds.size > 0
? `${selectedDocIds.size} selected`
: ""}
</span>
<button
onClick={handleStartChat}
disabled={
saving || (inProject && !selectedProjectId)
}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-50"
>
{saving ? "Starting…" : "Start Chat"}
</button>
</div>
</>
)}
{/* ── TABULAR CONFIGURE SCREEN ── */}
{screen === "configure" && wf.type === "tabular" && (
<>
<div className="flex-1 min-h-0 flex flex-col overflow-hidden">
{/* Toggle stacked */}
<div className="px-5 pb-3 flex flex-col gap-2 shrink-0">
<span className="text-xs font-medium text-gray-700">
Create in a project
</span>
<Toggle
on={inProject}
onToggle={() => {
setInProject(!inProject);
setSelectedProjectId(null);
setDocSearch("");
setSelectedDocIds(new Set());
}}
/>
</div>
{/* Project section */}
{inProject && (
<>
<div className="px-5 pt-1 pb-1 shrink-0">
<p className="text-xs font-medium text-gray-700">
Select Project
</p>
</div>
<div className="px-5 pb-2 shrink-0">
<SimpleProjectPicker
projects={projects}
selectedId={selectedProjectId}
onSelect={(id) => {
setSelectedProjectId(id);
if (!id)
setSelectedDocIds(
new Set(),
);
}}
/>
</div>
</>
)}
{/* Documents section */}
<div className="px-5 pt-3 pb-1 shrink-0">
<p className="text-xs font-medium text-gray-700">
Select Documents
</p>
</div>
{/* Search */}
<div className="px-4 pt-1.5 pb-1 shrink-0">
<div className="flex items-center gap-1.5 rounded-md border border-gray-200 bg-gray-50 px-2.5 py-1">
<Search className="h-3 w-3 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search…"
value={docSearch}
onChange={(e) =>
setDocSearch(e.target.value)
}
className="flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 outline-none"
/>
{docSearch && (
<button
onClick={() => setDocSearch("")}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
{/* File browser */}
<div className="flex-1 overflow-y-auto px-4 pb-2">
<FileDirectory
standaloneDocs={
inProject
? filteredProjectDocs
: filteredStandalone
}
directoryProjects={
inProject ? [] : filteredAllProjects
}
loading={dirLoading}
selectedIds={selectedDocIds}
onChange={setSelectedDocIds}
allowMultiple
forceExpanded={!!q || inProject}
emptyMessage={
q
? "No matches found"
: inProject
? "No documents in this project"
: "No documents yet"
}
/>
</div>
</div>
<div className="border-t border-gray-200 px-5 py-3 flex items-center justify-between shrink-0">
<span className="text-xs text-gray-400">
{selectedDocIds.size > 0
? `${selectedDocIds.size} selected`
: ""}
</span>
<button
onClick={handleCreateReview}
disabled={
saving ||
selectedDocIds.size === 0 ||
(inProject && !selectedProjectId)
}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-50"
>
{saving ? "Creating…" : "Create Review"}
</button>
</div>
</>
)}
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,218 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { X, MessageSquare, Table2 } from "lucide-react";
import { createWorkflow, updateWorkflow } from "@/app/lib/mikeApi";
import type { MikeWorkflow } from "../shared/types";
import { PRACTICE_OPTIONS } from "./practices";
interface Props {
open: boolean;
onClose: () => void;
onCreated: (workflow: MikeWorkflow) => void;
editWorkflow?: MikeWorkflow;
onUpdated?: (workflow: MikeWorkflow) => void;
}
export function NewWorkflowModal({ open, onClose, onCreated, editWorkflow, onUpdated }: Props) {
const [title, setTitle] = useState("");
const [type, setType] = useState<"assistant" | "tabular">("assistant");
const [practice, setPractice] = useState<string>("");
const [customPractice, setCustomPractice] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const customInputRef = useRef<HTMLInputElement>(null);
const isEditing = !!editWorkflow;
const isOthers = practice === "Others";
const effectivePractice = isOthers ? (customPractice.trim() || null) : (practice || null);
useEffect(() => {
if (open && editWorkflow) {
setTitle(editWorkflow.title);
setType(editWorkflow.type);
const saved = editWorkflow.practice ?? "";
const isKnown = (PRACTICE_OPTIONS as readonly string[]).includes(saved);
if (!isKnown && saved) {
setPractice("Others");
setCustomPractice(saved);
} else {
setPractice(saved);
setCustomPractice("");
}
setError("");
}
}, [open, editWorkflow?.id]);
useEffect(() => {
if (isOthers) {
customInputRef.current?.focus();
}
}, [isOthers]);
if (!open) return null;
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!title.trim()) return;
setLoading(true);
setError("");
try {
if (isEditing && editWorkflow) {
const updated = await updateWorkflow(editWorkflow.id, {
title: title.trim(),
practice: effectivePractice,
});
onUpdated?.(updated);
} else {
const workflow = await createWorkflow({
title: title.trim(),
type,
practice: effectivePractice,
});
onCreated(workflow);
}
resetForm();
onClose();
} catch (err: unknown) {
setError((err as Error).message || `Failed to ${isEditing ? "update" : "create"} workflow`);
} finally {
setLoading(false);
}
}
function resetForm() {
setTitle("");
setType("assistant");
setPractice("");
setCustomPractice("");
setError("");
}
function handleClose() {
resetForm();
onClose();
}
return (
<div className="fixed inset-0 z-101 flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl overflow-hidden flex flex-col" style={{ height: 600 }}>
{/* Header */}
<div className="flex items-center justify-between px-6 pt-5 pb-2 shrink-0">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Workflows</span>
<span></span>
<span>{isEditing ? "Edit workflow" : "New workflow"}</span>
</div>
<button
onClick={handleClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
<form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0">
{/* Body */}
<div className="px-6 pt-3 pb-5 flex-1 overflow-y-auto">
{/* Title */}
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Workflow name"
className="w-full text-2xl font-serif text-gray-800 placeholder-gray-300 focus:outline-none bg-transparent"
autoFocus
/>
{/* Type pills — only shown when creating */}
{!isEditing && (
<div className="mt-5">
<p className="mb-2 text-sm font-medium text-gray-500">Type</p>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setType("assistant")}
className={`flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs transition-colors ${
type === "assistant"
? "border-gray-900 bg-gray-900 text-white"
: "border-gray-200 text-gray-600 hover:bg-gray-50"
}`}
>
<MessageSquare className="h-3 w-3" />
Assistant
</button>
<button
type="button"
onClick={() => setType("tabular")}
className={`flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs transition-colors ${
type === "tabular"
? "border-gray-900 bg-gray-900 text-white"
: "border-gray-200 text-gray-600 hover:bg-gray-50"
}`}
>
<Table2 className="h-3 w-3" />
Tabular
</button>
</div>
</div>
)}
{/* Practice */}
<div className="mt-5">
<p className="mb-2 text-sm font-medium text-gray-500">Practice Area</p>
<div className="flex flex-wrap gap-2">
{PRACTICE_OPTIONS.map((p) => (
<button
key={p}
type="button"
onClick={() => setPractice(practice === p ? "" : p)}
className={`rounded-full border px-3 py-1 text-xs transition-colors ${
practice === p
? "border-gray-900 bg-gray-900 text-white"
: "border-gray-200 text-gray-600 hover:bg-gray-50"
}`}
>
{p}
</button>
))}
</div>
{isOthers && (
<input
ref={customInputRef}
type="text"
value={customPractice}
onChange={(e) => setCustomPractice(e.target.value)}
placeholder="Enter practice area…"
className="mt-3 w-full rounded-md border border-gray-200 px-3 py-1.5 text-sm text-gray-700 placeholder-gray-400 focus:border-gray-400 focus:outline-none"
/>
)}
</div>
{error && (
<p className="mt-4 text-sm text-red-500">{error}</p>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-2 border-t border-gray-100 px-6 py-4 shrink-0">
<button
type="button"
onClick={handleClose}
className="rounded-lg px-4 py-2 text-sm text-gray-500 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={!title.trim() || loading}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
{loading ? (isEditing ? "Saving…" : "Creating…") : (isEditing ? "Save changes" : "Create workflow")}
</button>
</div>
</form>
</div>
</div>
);
}

View file

@ -0,0 +1,158 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import {
deleteWorkflowShare,
listWorkflowShares,
shareWorkflow,
} from "@/app/lib/mikeApi";
import { EmailPillInput } from "../shared/EmailPillInput";
interface Share {
id: string;
shared_with_email: string;
allow_edit: boolean;
created_at: string;
}
interface Props {
workflowId: string;
workflowName: string;
onClose: () => void;
}
export function ShareWorkflowModal({
workflowId,
workflowName,
onClose,
}: Props) {
const [pendingEmails, setPendingEmails] = useState<string[]>([]);
const [allowEdit, setAllowEdit] = useState(false);
const [existingShares, setExistingShares] = useState<Share[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
listWorkflowShares(workflowId)
.then(setExistingShares)
.catch(() => {})
.finally(() => setLoading(false));
}, [workflowId]);
async function handleRemoveShare(shareId: string) {
await deleteWorkflowShare(workflowId, shareId).catch(() => {});
setExistingShares((prev) => prev.filter((s) => s.id !== shareId));
}
async function handleConfirm() {
if (pendingEmails.length === 0) return;
setSaving(true);
try {
await shareWorkflow(workflowId, { emails: pendingEmails, allow_edit: allowEdit });
const updated = await listWorkflowShares(workflowId);
setExistingShares(updated);
setPendingEmails([]);
} catch {
// ignore
} finally {
setSaving(false);
}
}
return createPortal(
<div className="fixed inset-0 z-[101] flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Workflows</span>
<span></span>
<span className="truncate max-w-[220px]">
{workflowName}
</span>
<span></span>
<span>People</span>
</div>
<button onClick={onClose} className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600">
<X className="h-4 w-4" />
</button>
</div>
<div className="px-5 py-4 flex flex-col gap-4 flex-1 overflow-y-auto">
<EmailPillInput
emails={pendingEmails}
onChange={setPendingEmails}
placeholder="Add people by email…"
autoFocus
/>
{/* Permission toggle */}
<div className="flex flex-col gap-2">
<span className="text-xs font-medium text-gray-700">Allow editing by share recipients</span>
<button
type="button"
onClick={() => setAllowEdit((v) => !v)}
className={`relative inline-flex h-5 w-9 shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ${allowEdit ? "bg-gray-900" : "bg-gray-200"}`}
>
<span className={`pointer-events-none inline-block h-4 w-4 rounded-full bg-white shadow transition-transform duration-200 ${allowEdit ? "translate-x-4" : "translate-x-0"}`} />
</button>
</div>
{/* Existing access */}
<div>
<p className="text-xs font-medium text-gray-700 mb-2">People with access</p>
{loading ? (
<div className="space-y-2">
{[1, 2].map((i) => (
<div key={i} className="flex items-center justify-between">
<div className="h-3 w-40 rounded bg-gray-100 animate-pulse" />
<div className="h-3 w-16 rounded bg-gray-100 animate-pulse" />
</div>
))}
</div>
) : existingShares.length === 0 ? (
<p className="text-sm text-gray-400">None</p>
) : (
<div className="space-y-1">
{existingShares.map((share) => (
<div key={share.id} className="flex items-center justify-between py-1">
<span className="text-sm text-gray-700 truncate">{share.shared_with_email}</span>
<div className="flex items-center gap-3 shrink-0">
<span className="text-xs text-gray-400">{share.allow_edit ? "Can edit" : "Read-only"}</span>
<button
onClick={() => handleRemoveShare(share.id)}
className="text-gray-300 hover:text-red-500 transition-colors"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
{/* Footer */}
<div className="border-t border-gray-100 px-5 py-3 flex justify-end gap-2 mt-auto shrink-0">
<button
onClick={onClose}
className="rounded-lg px-5 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
onClick={handleConfirm}
disabled={saving || pendingEmails.length === 0}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
{saving ? "Sharing…" : "Share"}
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,68 @@
"use client";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { ColumnConfig } from "../shared/types";
import { formatIcon, formatLabel } from "../tabular/columnFormat";
interface Props {
col: ColumnConfig;
onClose: () => void;
}
export function WFColumnViewModal({ col, onClose }: Props) {
const FormatIcon = formatIcon(col.format ?? "text");
return createPortal(
<div className="fixed inset-0 z-[101] flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
<div className="flex items-center justify-between px-6 pt-5 pb-2">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Workflows</span>
<span></span>
<span className="truncate max-w-[200px] text-gray-600">{col.name}</span>
</div>
<button onClick={onClose} className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600">
<X className="h-4 w-4" />
</button>
</div>
<div className="px-6 pt-3 pb-5 flex flex-col gap-4 overflow-y-auto flex-1">
<div>
<p className="text-sm font-medium text-gray-500 mb-2">Column Title</p>
<p className="text-sm text-gray-800">{col.name}</p>
</div>
<div>
<p className="text-sm font-medium text-gray-500 mb-2">Format</p>
<span className="inline-flex items-center gap-1.5 text-sm text-gray-700">
<FormatIcon className="h-3.5 w-3.5 text-gray-400" />
{formatLabel(col.format ?? "text")}
</span>
</div>
{col.tags && col.tags.length > 0 && (
<div>
<p className="text-sm font-medium text-gray-500 mb-2.5">Tags</p>
<div className="flex flex-wrap gap-1.5">
{col.tags.map((tag) => (
<span key={tag} className="inline-block rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600">{tag}</span>
))}
</div>
</div>
)}
<div>
<p className="text-sm font-medium text-gray-500 mb-2">Prompt</p>
<div className="text-base text-gray-700 leading-relaxed font-serif prose prose-base max-w-none">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{col.prompt || "_No prompt defined._"}</ReactMarkdown>
</div>
</div>
</div>
<div className="border-t border-gray-100 px-6 py-4 flex justify-end shrink-0">
<button onClick={onClose} className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700">
Close
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,318 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { ChevronDown, Plus, X } from "lucide-react";
import type { ColumnConfig, ColumnFormat } from "../shared/types";
import { generateTabularColumnPrompt } from "@/app/lib/mikeApi";
import { FORMAT_OPTIONS, formatLabel, formatIcon } from "../tabular/columnFormat";
import { TAG_COLORS } from "../tabular/pillUtils";
import { getPresetConfig, PROMPT_PRESETS } from "../tabular/columnPresets";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
interface ColumnDraft {
name: string;
prompt: string;
format: ColumnFormat;
tags: string[];
tagInput: string;
}
interface Props {
column: ColumnConfig;
onClose: () => void;
onSave: (col: ColumnConfig) => void;
onDelete: () => void;
}
export function WFEditColumnModal({ column, onClose, onSave, onDelete }: Props) {
const [draft, setDraft] = useState<ColumnDraft>({
name: column.name,
prompt: column.prompt,
format: column.format ?? "text",
tags: column.tags ?? [],
tagInput: "",
});
const [generating, setGenerating] = useState(false);
const [presetsOpen, setPresetsOpen] = useState(false);
const presetsRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setDraft({
name: column.name,
prompt: column.prompt,
format: column.format ?? "text",
tags: column.tags ?? [],
tagInput: "",
});
setPresetsOpen(false);
}, [column]);
useEffect(() => {
if (!presetsOpen) return;
function handleClickOutside(e: MouseEvent) {
if (presetsRef.current && !presetsRef.current.contains(e.target as Node)) {
setPresetsOpen(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, [presetsOpen]);
function update(patch: Partial<ColumnDraft>) {
setDraft((prev) => ({ ...prev, ...patch }));
}
function commitTag() {
const tag = draft.tagInput.trim();
if (!tag || draft.tags.includes(tag)) {
update({ tagInput: "" });
return;
}
update({ tags: [...draft.tags, tag], tagInput: "" });
}
function handleTagKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
commitTag();
} else if (e.key === "Backspace" && draft.tagInput === "" && draft.tags.length > 0) {
update({ tags: draft.tags.slice(0, -1) });
}
}
async function autoGeneratePrompt() {
const title = draft.name.trim();
if (!title) return;
setGenerating(true);
try {
const { prompt } = await generateTabularColumnPrompt(title, {
format: draft.format,
tags: draft.format === "tag" ? draft.tags : undefined,
});
update({ prompt });
} finally {
setGenerating(false);
}
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!draft.name.trim() || !draft.prompt.trim()) return;
onSave({
index: column.index,
name: draft.name.trim(),
prompt: draft.prompt.trim(),
format: draft.format,
tags: draft.format === "tag" ? draft.tags : undefined,
});
}
const FormatIcon = formatIcon(draft.format);
return createPortal(
<div className="fixed inset-0 z-[101] flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-6 pt-5 pb-2">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Workflows</span>
<span></span>
<span>Edit column</span>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
<form onSubmit={handleSubmit} className="flex flex-col min-h-0 flex-1">
{/* Body */}
<div className="px-6 pt-3 pb-5 overflow-y-auto flex-1">
{/* Name row */}
<div className="flex items-start gap-2">
<div className="relative flex flex-1 items-start" ref={presetsRef}>
<input
type="text"
value={draft.name}
onChange={(e) => {
const name = e.target.value;
const preset = getPresetConfig(name);
update({
name,
...(preset ? {
prompt: preset.prompt,
format: preset.format,
tags: preset.tags ?? [],
tagInput: "",
} : {}),
});
}}
placeholder="Column name"
className="flex-1 text-2xl font-serif text-gray-800 placeholder-gray-400 focus:outline-none bg-transparent"
autoFocus
/>
<button
type="button"
onClick={() => setPresetsOpen((v) => !v)}
title="Column presets"
className="mt-1.5 rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700"
>
<ChevronDown className={`h-4 w-4 transition-transform ${presetsOpen ? "rotate-180" : ""}`} />
</button>
{presetsOpen && (
<div className="absolute left-0 right-0 top-full mt-1 z-50 rounded-xl border border-gray-100 bg-white shadow-lg overflow-y-auto max-h-64">
<button
type="button"
onClick={() => { update({ name: "", prompt: "", format: "text", tags: [], tagInput: "" }); setPresetsOpen(false); }}
className="w-full px-3 py-2 text-left text-sm text-gray-400 hover:bg-gray-50 transition-colors border-b border-gray-100"
>
No Preset
</button>
{PROMPT_PRESETS.map((preset) => (
<button
key={preset.name}
type="button"
onClick={() => {
update({ name: preset.name, prompt: preset.prompt, format: preset.format, tags: preset.tags ?? [], tagInput: "" });
setPresetsOpen(false);
}}
className="w-full px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-50 transition-colors"
>
{preset.name}
</button>
))}
</div>
)}
</div>
</div>
{/* Format */}
<div className="mt-4">
<label className="text-sm font-medium text-gray-500">Format</label>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="mt-1 flex items-center justify-between rounded-md border border-gray-200 bg-white px-2 py-1.5 text-sm text-gray-700 hover:border-gray-400 focus:outline-none">
<span className="flex items-center gap-2">
<FormatIcon className="h-3.5 w-3.5 text-gray-400" />
{formatLabel(draft.format)}
</span>
<ChevronDown className="h-3.5 w-3.5 text-gray-400" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="z-[200]">
<DropdownMenuRadioGroup
value={draft.format}
onValueChange={(v) => update({ format: v as ColumnFormat, tags: [], tagInput: "" })}
>
{FORMAT_OPTIONS.map((o) => (
<DropdownMenuRadioItem key={o.value} value={o.value}>
<o.icon className="h-3.5 w-3.5 text-gray-400" />
{o.label}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Tag input */}
{draft.format === "tag" && (
<div className="mt-3">
<label className="text-sm font-medium text-gray-500">Tags</label>
<div className="mt-1 flex flex-wrap gap-1.5 rounded-md border border-gray-200 px-2 py-1.5 focus-within:border-gray-400">
{draft.tags.map((tag, tagIdx) => (
<span
key={tag}
className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs ${TAG_COLORS[tagIdx % TAG_COLORS.length]}`}
>
{tag}
<button
type="button"
onClick={() => update({ tags: draft.tags.filter((t) => t !== tag) })}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-2.5 w-2.5" />
</button>
</span>
))}
<input
type="text"
value={draft.tagInput}
onChange={(e) => update({ tagInput: e.target.value })}
onKeyDown={handleTagKeyDown}
onBlur={commitTag}
placeholder="Add tag…"
className="min-w-[80px] flex-1 bg-transparent text-sm text-gray-700 placeholder-gray-400 focus:outline-none"
/>
</div>
<p className="mt-1 text-xs text-gray-400">Press Enter or comma to add a tag.</p>
</div>
)}
{/* Prompt */}
<div className="mt-4 flex items-center justify-between">
<label className="text-sm font-medium text-gray-500">Prompt</label>
<button
type="button"
onClick={autoGeneratePrompt}
disabled={!draft.name.trim() || generating}
className="inline-flex items-center gap-1.5 text-sm text-gray-500 transition-colors hover:text-gray-900 disabled:text-gray-300"
>
{generating ? (
<span className="h-4 w-4 rounded-full border-2 border-gray-300 border-t-gray-600 animate-spin block" />
) : (
<Plus className="h-4 w-4" />
)}
Auto-Generate Prompt
</button>
</div>
<textarea
rows={6}
value={draft.prompt}
onChange={(e) => update({ prompt: e.target.value })}
placeholder="Write the analysis prompt — describe what Mike should extract from each document for this column…"
className="mt-2 w-full rounded-md border border-gray-200 px-3 py-2 text-sm text-gray-700 placeholder-gray-400 focus:border-gray-400 focus:outline-none bg-transparent resize-none leading-relaxed"
/>
</div>
{/* Footer */}
<div className="flex items-center justify-between border-t border-gray-100 px-6 py-4">
<button
type="button"
onClick={onDelete}
className="rounded-lg px-4 py-2 text-sm text-red-500 hover:bg-red-50 transition-colors"
>
Delete
</button>
<div className="flex items-center gap-2">
<button
type="button"
onClick={onClose}
className="rounded-lg px-4 py-2 text-sm text-gray-500 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={!draft.name.trim() || !draft.prompt.trim()}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
Save changes
</button>
</div>
</div>
</form>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,610 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
Plus,
Library,
Table2,
MessageSquare,
User,
ChevronDown,
Check,
} from "lucide-react";
import { HeaderSearchBtn } from "../shared/HeaderSearchBtn";
import {
listWorkflows,
deleteWorkflow,
listHiddenWorkflows,
hideWorkflow,
unhideWorkflow,
} from "@/app/lib/mikeApi";
import type { MikeWorkflow } from "../shared/types";
import { BUILT_IN_WORKFLOWS, BUILT_IN_IDS } from "./builtinWorkflows";
import { DisplayWorkflowModal } from "./DisplayWorkflowModal";
import { NewWorkflowModal } from "./NewWorkflowModal";
import { ToolbarTabs } from "../shared/ToolbarTabs";
import { RowActions } from "../shared/RowActions";
import { MikeIcon } from "@/components/chat/mike-icon";
import { useAuth } from "@/contexts/AuthContext";
type Tab = "all" | "builtin" | "custom" | "hidden";
const CHECK_W = "w-8 shrink-0";
const NAME_COL_W = "w-[300px] shrink-0";
const TABS: { id: Tab; label: string }[] = [
{ id: "all", label: "All Workflows" },
{ id: "builtin", label: "Built-in" },
{ id: "custom", label: "Custom" },
{ id: "hidden", label: "Hidden" },
];
export function WorkflowList() {
const router = useRouter();
const { user } = useAuth();
const [custom, setCustom] = useState<MikeWorkflow[]>([]);
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState<MikeWorkflow | null>(null);
const [activeTab, setActiveTab] = useState<Tab>("all");
const [newModalOpen, setNewModalOpen] = useState(false);
const [hiddenBuiltinIds, setHiddenBuiltinIds] = useState<string[]>([]);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [actionsOpen, setActionsOpen] = useState(false);
const [practiceFilter, setPracticeFilter] = useState<string | null>(null);
const [practiceFilterOpen, setPracticeFilterOpen] = useState(false);
const [typeFilter, setTypeFilter] = useState<MikeWorkflow["type"] | null>(
null,
);
const [typeFilterOpen, setTypeFilterOpen] = useState(false);
const [search, setSearch] = useState("");
const actionsRef = useRef<HTMLDivElement>(null);
const practiceFilterRef = useRef<HTMLDivElement>(null);
const typeFilterRef = useRef<HTMLDivElement>(null);
useEffect(() => {
Promise.all([
listWorkflows("assistant"),
listWorkflows("tabular"),
listHiddenWorkflows(),
])
.then(([assistant, tabular, hidden]) => {
setCustom([...assistant, ...tabular]);
setHiddenBuiltinIds(hidden);
})
.catch(() => setCustom([]))
.finally(() => setLoading(false));
}, []);
useEffect(() => {
setSelectedIds([]);
setActionsOpen(false);
}, [activeTab, practiceFilter, typeFilter]);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (
actionsRef.current &&
!actionsRef.current.contains(e.target as Node)
) {
setActionsOpen(false);
}
}
if (actionsOpen) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [actionsOpen]);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (
practiceFilterRef.current &&
!practiceFilterRef.current.contains(e.target as Node)
) {
setPracticeFilterOpen(false);
}
if (
typeFilterRef.current &&
!typeFilterRef.current.contains(e.target as Node)
) {
setTypeFilterOpen(false);
}
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
const hiddenBuiltins = BUILT_IN_WORKFLOWS.filter((wf) =>
hiddenBuiltinIds.includes(wf.id),
);
const visibleBuiltins = BUILT_IN_WORKFLOWS.filter(
(wf) => !hiddenBuiltinIds.includes(wf.id),
);
const all = [...visibleBuiltins, ...custom];
const byTab =
activeTab === "builtin"
? visibleBuiltins
: activeTab === "custom"
? custom
: activeTab === "hidden"
? hiddenBuiltins
: all;
const practices = Array.from(
new Set(byTab.map((wf) => wf.practice).filter((p): p is string => !!p)),
).sort();
const q = search.toLowerCase();
const filtered = byTab
.filter((wf) => !practiceFilter || wf.practice === practiceFilter)
.filter((wf) => !typeFilter || wf.type === typeFilter)
.filter((wf) => !q || wf.title.toLowerCase().includes(q));
const allSelected =
filtered.length > 0 &&
filtered.every((wf) => selectedIds.includes(wf.id));
const someSelected =
!allSelected && filtered.some((wf) => selectedIds.includes(wf.id));
function toggleAll() {
if (allSelected) setSelectedIds([]);
else setSelectedIds(filtered.map((wf) => wf.id));
}
function toggleOne(id: string) {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
);
}
async function handleHideWorkflow(id: string) {
setHiddenBuiltinIds((prev) => [...prev, id]);
await hideWorkflow(id).catch(() => {
setHiddenBuiltinIds((prev) => prev.filter((x) => x !== id));
});
}
async function handleUnhideWorkflow(id: string) {
setHiddenBuiltinIds((prev) => prev.filter((x) => x !== id));
await unhideWorkflow(id).catch(() => {
setHiddenBuiltinIds((prev) => [...prev, id]);
});
}
async function handleBulkRemove() {
const ids = [...selectedIds];
setActionsOpen(false);
setSelectedIds([]);
const builtinIds = ids.filter((id) => BUILT_IN_IDS.has(id));
const customIds = ids.filter((id) => !BUILT_IN_IDS.has(id));
if (builtinIds.length > 0) {
setHiddenBuiltinIds((prev) => [
...prev,
...builtinIds.filter((id) => !prev.includes(id)),
]);
await Promise.all(
builtinIds.map((id) => hideWorkflow(id).catch(() => {})),
);
}
if (customIds.length > 0) {
await Promise.all(
customIds.map((id) => deleteWorkflow(id).catch(() => {})),
);
setCustom((prev) => prev.filter((w) => !customIds.includes(w.id)));
}
}
async function handleBulkUnhide() {
const ids = [...selectedIds];
setActionsOpen(false);
setSelectedIds([]);
setHiddenBuiltinIds((prev) => prev.filter((id) => !ids.includes(id)));
await Promise.all(ids.map((id) => unhideWorkflow(id).catch(() => {})));
}
const getTypeMeta = (type: MikeWorkflow["type"]) =>
type === "tabular"
? { label: "Tabular", Icon: Table2, className: "text-violet-700" }
: {
label: "Assistant",
Icon: MessageSquare,
className: "text-blue-700",
};
const typeFilterButton = (
<div className="relative" ref={typeFilterRef}>
<button
onClick={() => setTypeFilterOpen((o) => !o)}
className={`flex items-center gap-1 text-xs font-medium transition-colors ${
typeFilter
? "text-gray-700 hover:text-gray-900"
: "text-gray-500 hover:text-gray-700"
}`}
>
{typeFilter
? typeFilter === "tabular"
? "Tabular"
: "Assistant"
: "Filter by type"}
<ChevronDown className="h-3 w-3" />
</button>
{typeFilterOpen && (
<div className="absolute right-0 top-full mt-1.5 z-20 w-40 rounded-xl border border-gray-100 bg-white shadow-lg overflow-hidden">
<button
onClick={() => {
setTypeFilter(null);
setTypeFilterOpen(false);
}}
className="flex items-center justify-between w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
All Types
{!typeFilter && (
<Check className="h-3.5 w-3.5 text-gray-400" />
)}
</button>
<div className="border-t border-gray-100" />
{(["assistant", "tabular"] as const).map((t) => {
const { label, Icon, className } = getTypeMeta(t);
return (
<button
key={t}
onClick={() => {
setTypeFilter(t);
setTypeFilterOpen(false);
}}
className="flex items-center justify-between w-full px-3 py-2 text-xs hover:bg-gray-50 transition-colors"
>
<span
className={`inline-flex items-center gap-1.5 font-medium ${className}`}
>
<Icon className="h-3.5 w-3.5" />
{label}
</span>
{typeFilter === t && (
<Check className="h-3.5 w-3.5 shrink-0 text-gray-400" />
)}
</button>
);
})}
</div>
)}
</div>
);
const practiceFilterButton = (
<div className="relative" ref={practiceFilterRef}>
<button
onClick={() => setPracticeFilterOpen((o) => !o)}
className={`flex items-center gap-1 text-xs font-medium transition-colors ${
practiceFilter
? "text-gray-700 hover:text-gray-900"
: "text-gray-500 hover:text-gray-700"
}`}
>
{practiceFilter ?? "Filter by practice"}
<ChevronDown className="h-3 w-3" />
</button>
{practiceFilterOpen && (
<div className="absolute right-0 top-full mt-1.5 z-20 w-52 rounded-xl border border-gray-100 bg-white shadow-lg overflow-hidden">
<button
onClick={() => {
setPracticeFilter(null);
setPracticeFilterOpen(false);
}}
className="flex items-center justify-between w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
All Practices
{!practiceFilter && (
<Check className="h-3.5 w-3.5 text-gray-400" />
)}
</button>
{practices.length > 0 && (
<div className="border-t border-gray-100" />
)}
{practices.map((p) => (
<button
key={p}
onClick={() => {
setPracticeFilter(p);
setPracticeFilterOpen(false);
}}
className="flex items-center justify-between w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<span className="truncate pr-2">{p}</span>
{practiceFilter === p && (
<Check className="h-3.5 w-3.5 shrink-0 text-gray-400" />
)}
</button>
))}
</div>
)}
</div>
);
const toolbarActions = (
<div className="flex items-center gap-2">
{selectedIds.length > 0 && (
<div ref={actionsRef} className="relative">
<button
onClick={() => setActionsOpen((v) => !v)}
className="flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-gray-900 transition-colors"
>
Actions
<ChevronDown className="h-3.5 w-3.5" />
</button>
{actionsOpen && (
<div className="absolute top-full right-0 mt-1 w-36 rounded-lg border border-gray-100 bg-white shadow-lg z-50 overflow-hidden">
{activeTab === "hidden" ? (
<button
onClick={handleBulkUnhide}
className="w-full px-3 py-1.5 text-left text-xs text-gray-700 hover:bg-gray-50 transition-colors"
>
Unhide
</button>
) : (
<button
onClick={handleBulkRemove}
className="w-full px-3 py-1.5 text-left text-xs text-red-600 hover:bg-red-50 transition-colors"
>
Delete
</button>
)}
</div>
)}
</div>
)}
{typeFilterButton}
{practiceFilterButton}
</div>
);
return (
<div className="flex flex-col flex-1 overflow-hidden bg-white">
{/* Page header */}
<div className="flex items-center justify-between px-8 py-4 shrink-0">
<h1 className="text-2xl font-medium font-serif text-gray-900">
Workflows
</h1>
<div className="flex items-center gap-2">
<HeaderSearchBtn
value={search}
onChange={setSearch}
placeholder="Search workflows…"
/>
<button
onClick={() => setNewModalOpen(true)}
className="flex items-center justify-center p-1.5 text-gray-500 hover:text-gray-900 transition-colors"
>
<Plus className="h-4 w-4" />
</button>
</div>
</div>
<ToolbarTabs
tabs={TABS}
active={activeTab}
onChange={setActiveTab}
actions={toolbarActions}
/>
{/* Table */}
<div className="flex-1 overflow-auto">
<div className="min-w-max">
{/* Column headers */}
<div className="flex items-center h-8 pr-8 border-b border-gray-200 text-xs text-gray-500 font-medium select-none">
<div className={`sticky left-0 z-[60] ${CHECK_W} relative bg-white flex items-center justify-center self-stretch before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-white`}>
{!loading && (
<input
type="checkbox"
checked={allSelected}
ref={(el) => {
if (el) el.indeterminate = someSelected;
}}
onChange={toggleAll}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
)}
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} bg-white pl-2 text-left`}>
Name
</div>
<div className="ml-auto w-28 shrink-0">Type</div>
<div className="w-40 shrink-0">Practice</div>
<div className="w-28 shrink-0">Source</div>
<div className="w-8 shrink-0" />
</div>
{loading && activeTab !== "builtin" ? (
<div>
{[1, 2, 3].map((i) => (
<div
key={i}
className="flex items-center h-10 pr-8 border-b border-gray-50"
>
<div className="w-8 shrink-0" />
<div className="flex-1 min-w-0 pl-3 pr-4">
<div className="h-3.5 w-48 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-28 shrink-0">
<div className="h-3 w-16 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-40 shrink-0">
<div className="h-3 w-24 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-28 shrink-0">
<div className="h-3 w-14 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-8 shrink-0" />
</div>
))}
</div>
) : filtered.length === 0 ? (
<div className="flex flex-col items-start py-24 w-full max-w-xs mx-auto">
{activeTab === "custom" ? (
<>
<Library className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Custom Workflows
</p>
<p className="mt-1 text-xs text-gray-400 text-left">
Build reusable prompts and tabular
review templates tailored to your
practice.
</p>
<button
onClick={() => setNewModalOpen(true)}
className="mt-4 inline-flex items-center gap-1 rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white hover:bg-gray-700 transition-colors shadow-md"
>
+ Create New
</button>
</>
) : activeTab === "hidden" ? (
<>
<Library className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Hidden Workflows
</p>
<p className="mt-1 text-xs text-gray-400 text-left">
Built-in workflows you've hidden will
appear here. You can unhide them at any
time.
</p>
</>
) : (
<>
<Library className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Workflows
</p>
<p className="mt-1 text-xs text-gray-400 text-left">
Automate document analysis with reusable
prompts and tabular review templates.
</p>
</>
)}
</div>
) : (
filtered.map((wf) => {
const rowBg = selectedIds.includes(wf.id)
? "bg-gray-50"
: "bg-white";
return (
<div
key={wf.id}
onClick={() => setSelected(wf)}
className="group flex items-center h-10 pr-8 border-b border-gray-50 hover:bg-gray-50 cursor-pointer transition-colors"
>
<div
className={`sticky left-0 z-[60] ${CHECK_W} p-2 flex items-center justify-center ${rowBg} group-hover:bg-gray-50`}
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={selectedIds.includes(wf.id)}
onChange={() => toggleOne(wf.id)}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} p-2 ${rowBg} group-hover:bg-gray-50`}>
<span className="text-sm text-gray-800 truncate block">
{wf.title}
</span>
</div>
<div className="ml-auto w-28 shrink-0">
{(() => {
const { label, Icon, className } =
getTypeMeta(wf.type);
return (
<span
className={`inline-flex items-center gap-1.5 text-xs font-medium ${className}`}
>
<Icon className="h-3.5 w-3.5" />
{label}
</span>
);
})()}
</div>
<div className="w-40 shrink-0">
{wf.practice ? (
<span className="text-xs font-medium text-gray-600">
{wf.practice}
</span>
) : (
<span className="text-xs text-gray-300">
</span>
)}
</div>
<div className="w-28 shrink-0">
{wf.is_system ? (
<span className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-600">
<MikeIcon size={14} />
Mike
</span>
) : wf.user_id === user?.id ? (
<span className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-600">
<User className="h-3.5 w-3.5 text-gray-500" />
Myself
</span>
) : (
<span className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-600 truncate max-w-full">
<User className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<span className="truncate">
{wf.shared_by_name ?? "Shared"}
</span>
</span>
)}
</div>
<div
className="w-8 shrink-0 flex justify-end"
onClick={(e) => e.stopPropagation()}
>
{wf.is_system ? (
activeTab === "hidden" ? (
<RowActions
onUnhide={() =>
handleUnhideWorkflow(wf.id)
}
/>
) : (
<RowActions
onHide={() =>
handleHideWorkflow(wf.id)
}
/>
)
) : wf.is_owner === false ? null : (
<RowActions
onDelete={async () => {
await deleteWorkflow(wf.id);
setCustom((prev) =>
prev.filter(
(w) => w.id !== wf.id,
),
);
}}
/>
)}
</div>
</div>
);
})
)}
</div>
</div>
<DisplayWorkflowModal
workflows={all}
workflow={selected}
onClose={() => setSelected(null)}
/>
<NewWorkflowModal
open={newModalOpen}
onClose={() => setNewModalOpen(false)}
onCreated={(wf) => {
setCustom((prev) => [wf, ...prev]);
setNewModalOpen(false);
router.push(`/workflows/${wf.id}`);
}}
/>
</div>
);
}

View file

@ -0,0 +1,189 @@
"use client";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import { Markdown } from "tiptap-markdown";
import { useEffect, useRef } from "react";
import {
Bold,
Heading1,
Heading2,
Heading3,
Italic,
List,
ListOrdered,
} from "lucide-react";
interface Props {
value: string;
onChange?: (markdown: string) => void;
readOnly?: boolean;
}
function ToolbarBtn({
onClick,
active,
title,
children,
}: {
onClick: () => void;
active: boolean;
title: string;
children: React.ReactNode;
}) {
return (
<button
type="button"
title={title}
onMouseDown={(e) => {
e.preventDefault(); // keep editor focus
onClick();
}}
className={`p-1.5 rounded transition-colors ${
active
? "bg-gray-200 text-gray-900"
: "text-gray-400 hover:bg-gray-100 hover:text-gray-600"
}`}
>
{children}
</button>
);
}
export function WorkflowPromptEditor({
value,
onChange,
readOnly = false,
}: Props) {
const lastEmittedRef = useRef(value);
const editor = useEditor({
extensions: [
StarterKit.configure({
heading: { levels: [1, 2, 3] },
codeBlock: false,
code: false,
blockquote: false,
horizontalRule: false,
}),
Markdown.configure({
html: false,
transformPastedText: true,
transformCopiedText: true,
}),
],
content: value,
editable: !readOnly,
immediatelyRender: false,
onUpdate: ({ editor }) => {
// tiptap-markdown adds .markdown to storage but isn't typed on Editor.storage
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const md: string = (editor.storage as any).markdown.getMarkdown();
lastEmittedRef.current = md;
onChange?.(md);
},
editorProps: {
attributes: {
class: "workflow-editor-content",
},
},
});
// Sync external value (e.g. on load from API)
useEffect(() => {
if (!editor || editor.isDestroyed) return;
if (value !== lastEmittedRef.current) {
lastEmittedRef.current = value;
editor.commands.setContent(value);
}
}, [value, editor]);
return (
<div className="flex flex-col h-full border border-gray-200 rounded-md overflow-hidden bg-white">
{!readOnly && editor && (
<div className="flex items-center gap-0.5 px-2 py-1.5 border-b border-gray-100 bg-gray-50 shrink-0">
<ToolbarBtn
onClick={() =>
editor
.chain()
.focus()
.toggleHeading({ level: 1 })
.run()
}
active={editor.isActive("heading", { level: 1 })}
title="Heading 1"
>
<Heading1 className="h-4 w-4" />
</ToolbarBtn>
<ToolbarBtn
onClick={() =>
editor
.chain()
.focus()
.toggleHeading({ level: 2 })
.run()
}
active={editor.isActive("heading", { level: 2 })}
title="Heading 2"
>
<Heading2 className="h-4 w-4" />
</ToolbarBtn>
<ToolbarBtn
onClick={() =>
editor
.chain()
.focus()
.toggleHeading({ level: 3 })
.run()
}
active={editor.isActive("heading", { level: 3 })}
title="Heading 3"
>
<Heading3 className="h-4 w-4" />
</ToolbarBtn>
<div className="w-px h-4 bg-gray-200 mx-1 shrink-0" />
<ToolbarBtn
onClick={() =>
editor.chain().focus().toggleBold().run()
}
active={editor.isActive("bold")}
title="Bold"
>
<Bold className="h-4 w-4" />
</ToolbarBtn>
<ToolbarBtn
onClick={() =>
editor.chain().focus().toggleItalic().run()
}
active={editor.isActive("italic")}
title="Italic"
>
<Italic className="h-4 w-4" />
</ToolbarBtn>
<div className="w-px h-4 bg-gray-200 mx-1 shrink-0" />
<ToolbarBtn
onClick={() =>
editor.chain().focus().toggleBulletList().run()
}
active={editor.isActive("bulletList")}
title="Bullet list"
>
<List className="h-4 w-4" />
</ToolbarBtn>
<ToolbarBtn
onClick={() =>
editor.chain().focus().toggleOrderedList().run()
}
active={editor.isActive("orderedList")}
title="Numbered list"
>
<ListOrdered className="h-4 w-4" />
</ToolbarBtn>
</div>
)}
<div className="flex-1 overflow-y-auto">
<EditorContent editor={editor} />
</div>
</div>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,23 @@
export const PRACTICE_OPTIONS = [
"General Transactions",
"Corporate",
"Finance",
"Litigation",
"Real Estate",
"Tax",
"Employment",
"IP",
"Competition",
"Tech Transactions",
"Project Finance",
"EC/VC",
"Private Equity",
"Private Credit",
"ECM",
"DCM",
"Lev Fin",
"Arbitration",
"Others",
] as const;
export type Practice = (typeof PRACTICE_OPTIONS)[number];

View file

@ -0,0 +1,194 @@
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import { useAuth } from "@/contexts/AuthContext";
import {
createChat,
deleteChat,
listChats,
renameChat,
} from "@/app/lib/mikeApi";
import type { MikeChat, MikeMessage } from "@/app/components/shared/types";
interface ChatHistoryContextType {
chats: MikeChat[] | null;
currentChatId: string | null;
setCurrentChatId: (chatId: string | null) => void;
loadChats: () => Promise<void>;
saveChat: (projectId?: string) => Promise<string | null>;
renameChat: (chatId: string, title: string) => Promise<void>;
newChatMessages: MikeMessage[] | null;
setNewChatMessages: (messages: MikeMessage[] | null) => void;
replaceChatId: (
oldChatId: string,
newChatId: string,
title?: string,
) => void;
deleteChat: (chatId: string) => Promise<void>;
}
const ChatHistoryContext = createContext<ChatHistoryContextType | undefined>(
undefined,
);
export function ChatHistoryProvider({ children }: { children: ReactNode }) {
const { user } = useAuth();
const [chats, setChats] = useState<MikeChat[] | null>(null);
const [currentChatId, setCurrentChatId] = useState<string | null>(null);
const [newChatMessages, setNewChatMessages] = useState<
MikeMessage[] | null
>(null);
const loadChats = useCallback(async () => {
if (!user) {
setChats([]);
return;
}
try {
const data = await listChats();
setChats(data);
} catch {
setChats([]);
}
}, [user]);
useEffect(() => {
if (!user) {
setChats([]);
setCurrentChatId(null);
return;
}
void loadChats();
}, [user, loadChats]);
const replaceChatId = useCallback(
(oldChatId: string, newChatId: string, title?: string) => {
if (!oldChatId || !newChatId || oldChatId === newChatId) {
setCurrentChatId(newChatId || oldChatId || null);
return;
}
setChats((prev) => {
if (!prev) return prev;
const nextChats = prev.map((chat) =>
chat.id === oldChatId
? { ...chat, id: newChatId, title: title ?? chat.title }
: chat,
);
const seen = new Set<string>();
return nextChats.filter((chat) => {
if (seen.has(chat.id)) return false;
seen.add(chat.id);
return true;
});
});
setCurrentChatId(newChatId);
},
[],
);
const saveChat = useCallback(
async (projectId?: string): Promise<string | null> => {
try {
const { id } = await createChat(
projectId ? { project_id: projectId } : undefined,
);
const now = new Date().toISOString();
const newChat: MikeChat = {
id,
project_id: projectId ?? null,
user_id: user?.id ?? "",
title: null,
created_at: now,
};
setChats((prev) => [newChat, ...(prev ?? [])]);
return id;
} catch {
return null;
}
},
[user],
);
const renameChatFn = useCallback(
async (chatId: string, title: string) => {
setChats((prev) =>
(prev ?? []).map((c) =>
c.id === chatId ? { ...c, title } : c,
),
);
try {
await renameChat(chatId, title);
} catch {
void loadChats();
}
},
[loadChats],
);
const deleteChatFn = useCallback(
async (chatId: string) => {
setChats((prev) => (prev ?? []).filter((c) => c.id !== chatId));
if (currentChatId === chatId) setCurrentChatId(null);
try {
await deleteChat(chatId);
} catch {
void loadChats();
}
},
[currentChatId, loadChats],
);
const value = useMemo(
() => ({
chats,
currentChatId,
setCurrentChatId,
loadChats,
saveChat,
renameChat: renameChatFn,
newChatMessages,
setNewChatMessages,
replaceChatId,
deleteChat: deleteChatFn,
}),
[
chats,
currentChatId,
loadChats,
saveChat,
renameChatFn,
newChatMessages,
replaceChatId,
deleteChatFn,
],
);
return (
<ChatHistoryContext.Provider value={value}>
{children}
</ChatHistoryContext.Provider>
);
}
export function useChatHistoryContext() {
const context = useContext(ChatHistoryContext);
if (!context) {
throw new Error(
"useChatHistoryContext must be used within a ChatHistoryProvider",
);
}
return context;
}

View file

@ -0,0 +1,15 @@
"use client";
import { createContext, useContext } from "react";
interface SidebarContextValue {
setSidebarOpen: (open: boolean) => void;
}
export const SidebarContext = createContext<SidebarContextValue>({
setSidebarOpen: () => {},
});
export function useSidebar() {
return useContext(SidebarContext);
}

View file

@ -0,0 +1,35 @@
"use client";
import Link from "next/link";
import { useEffect } from "react";
export default function Error({
error,
}: {
error: Error & { digest?: string };
}) {
useEffect(() => {
console.error("App error:", error);
}, [error]);
return (
<div className="min-h-screen bg-white flex items-center justify-center px-4">
<div className="text-center max-w-md">
<h1 className="text-3xl font-eb-garamond font-light text-gray-900 mb-3">
Something went wrong
</h1>
<p className="text-[0.9375rem] text-gray-500 leading-relaxed mb-8">
We encountered an unexpected error. This has been logged and
our team will look into it.
</p>
<Link
href="/"
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full text-sm font-medium text-white bg-gray-900 hover:bg-gray-700 transition-colors"
>
Home
</Link>
</div>
</div>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 9 KiB

View file

@ -0,0 +1,97 @@
"use client";
import { useEffect } from "react";
export default function GlobalError({
error,
}: {
error: Error & { digest?: string };
}) {
useEffect(() => {
console.error("Global error:", error);
}, [error]);
return (
<html lang="en">
<head>
<title>Something went wrong Mike</title>
<style>{`
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=EB+Garamond:wght@400;500&display=swap');
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: #ffffff;
color: #111;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.error-container {
text-align: center;
max-width: 480px;
padding: 2rem;
}
.error-title {
font-family: 'EB Garamond', Georgia, serif;
font-size: 1.75rem;
font-weight: 400;
color: #111;
margin-bottom: 0.75rem;
}
.error-message {
font-size: 0.9375rem;
color: #6b7280;
line-height: 1.6;
margin-bottom: 2rem;
}
.btn-back {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 1.25rem;
border-radius: 0.5rem;
font-size: 0.875rem;
font-weight: 500;
font-family: 'Inter', sans-serif;
cursor: pointer;
transition: all 0.15s ease;
text-decoration: none;
border: none;
background-color: rgb(0, 136, 255);
color: white;
}
.btn-back:hover {
background-color: rgb(0, 120, 230);
}
.btn-back:active {
transform: scale(0.98);
}
`}</style>
</head>
<body>
<div className="error-container">
<h1 className="error-title">Something went wrong</h1>
<p className="error-message">
We encountered an unexpected error. This has been logged
and our team will look into it.
</p>
<button
className="btn-back"
onClick={() => window.history.back()}
>
Back
</button>
</div>
</body>
</html>
);
}

View file

@ -0,0 +1,497 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-inter);
--font-serif: var(--font-eb-garamond);
--color-blue: rgb(0, 136, 255);
--color-blue-50: rgba(0, 136, 255, 0.05);
--color-blue-100: rgba(0, 136, 255, 0.1);
--color-blue-200: rgba(0, 136, 255, 0.3);
--color-blue-600: rgb(0, 136, 255);
--color-blue-700: rgb(0, 120, 230);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--color-azure: 0, 136, 255;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
button {
cursor: pointer;
}
}
.usc-section {
font-family: var(--font-serif);
line-height: 1.6;
}
.usc-section h1,
.usc-section h2,
.usc-section h3,
.usc-section h4,
.usc-section h5,
.usc-section h6 {
font-family: var(--font-serif);
font-weight: 600;
margin-top: 1.5em;
margin-bottom: 0.5em;
line-height: 1.2;
}
.usc-section h1 {
font-size: 1.5em;
}
.usc-section h2 {
font-size: 1.25em;
}
.usc-section h3 {
font-size: 1.125em;
}
.usc-section p {
margin-bottom: 1em;
}
/* Inline cross-reference links within section text */
.usc-xref,
.usc-section a {
color: rgb(var(--color-azure));
text-decoration: none;
border-bottom: 1px dotted rgba(var(--color-azure), 0.4);
transition: border-bottom-color 0.2s;
}
.usc-xref:hover,
.usc-section a:hover {
border-bottom-color: rgb(var(--color-azure));
}
/* Remove automatic list styling for USC section content */
/* The labels are already embedded in the HTML content */
.usc-section ol,
.usc-section ul {
list-style: none !important;
padding-left: 0 !important;
margin: 0;
}
.usc-section li {
margin-bottom: 0.125em;
text-indent: -1.25em;
padding-left: 1.25em;
}
/* Add indentation for nested lists */
.usc-section ol ol,
.usc-section ol ul,
.usc-section ul ol {
padding-left: 0.75em !important;
margin-top: 0;
}
/* ─── CFR (Code of Federal Regulations) ────────────────────────── */
.cfr-section {
font-family: var(--font-serif);
line-height: 1.6;
}
.cfr-section h1,
.cfr-section h2,
.cfr-section h3,
.cfr-section h4,
.cfr-section h5,
.cfr-section h6 {
font-family: var(--font-serif);
font-weight: 600;
margin-top: 1.5em;
margin-bottom: 0.5em;
line-height: 1.2;
}
.cfr-section h1 {
font-size: 1.5em;
}
.cfr-section h2 {
font-size: 1.25em;
}
.cfr-section h3 {
font-size: 1.125em;
}
.cfr-section p {
margin-bottom: 0.75em;
}
.cfr-section a {
color: rgb(var(--color-azure));
text-decoration: none;
border-bottom: 1px dotted rgba(var(--color-azure), 0.4);
transition: border-bottom-color 0.2s;
}
.cfr-section a:hover {
border-bottom-color: rgb(var(--color-azure));
}
.cfr-section table {
width: 100%;
border-collapse: collapse;
margin: 1em 0;
font-size: 0.875em;
}
.cfr-section th,
.cfr-section td {
border: 1px solid #e2e8f0;
padding: 0.5em 0.75em;
text-align: left;
}
.cfr-section th {
background: #f8fafc;
font-weight: 600;
}
.cfr-section .authority-section,
.cfr-section .source-section {
font-size: 0.875em;
color: #64748b;
margin: 1em 0;
padding: 0.75em;
border-left: 3px solid #e2e8f0;
}
@layer utilities {
.font-eb-garamond {
font-family: var(--font-eb-garamond);
}
.sidebar-fade-in {
animation: sidebarFadeIn 0.3s ease-out forwards;
animation-delay: 0.1s;
opacity: 0;
}
.sidebar-fade-in-2 {
animation: sidebarFadeIn 0.3s ease-out forwards;
animation-delay: 0.2s;
opacity: 0;
}
.sidebar-fade-in-3 {
animation: sidebarFadeIn 0.3s ease-out forwards;
animation-delay: 0.25s;
opacity: 0;
}
@keyframes sidebarFadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes scroll-left {
0% {
transform: translateX(0);
}
100% {
transform: translateX(calc(-100% + 100px));
}
}
@keyframes shimmer {
from {
background-position: 0 0;
}
to {
background-position: -200% 0;
}
}
.animate-shimmer {
animation: shimmer 8s linear infinite;
}
}
/* ─── Tiptap WYSIWYG workflow editor ────────────────────────────── */
.workflow-editor-content {
min-height: 100%;
padding: 1rem 1.25rem;
outline: none;
font-size: 0.875rem;
color: #374151;
line-height: 1.65;
font-family: var(--font-serif);
}
.workflow-editor-content h1 {
font-size: 1rem;
font-weight: 600;
color: #111827;
margin-top: 1.25rem;
margin-bottom: 0.375rem;
}
.workflow-editor-content h2 {
font-size: 0.875rem;
font-weight: 600;
color: #111827;
margin-top: 0.875rem;
margin-bottom: 0.25rem;
}
.workflow-editor-content h3 {
font-size: 0.8125rem;
font-weight: 600;
color: #111827;
margin-top: 0.625rem;
margin-bottom: 0.125rem;
}
.workflow-editor-content h1:first-child,
.workflow-editor-content h2:first-child,
.workflow-editor-content h3:first-child {
margin-top: 0;
}
.workflow-editor-content p {
margin-bottom: 0.5rem;
}
.workflow-editor-content p:last-child {
margin-bottom: 0;
}
.workflow-editor-content ul {
list-style-type: disc;
padding-left: 1.375rem;
margin-bottom: 0.5rem;
}
.workflow-editor-content ol {
list-style-type: decimal;
padding-left: 1.375rem;
margin-bottom: 0.5rem;
}
.workflow-editor-content li {
margin-bottom: 0.125rem;
}
.workflow-editor-content li > p {
margin-bottom: 0;
}
.workflow-editor-content strong {
font-weight: 600;
color: #1f2937;
}
.workflow-editor-content em {
font-style: italic;
}
/* ChatBox Animation Styles */
/* PDF text layer */
.pdf-text-layer {
overflow: hidden;
opacity: 1;
line-height: 1;
user-select: none;
pointer-events: none;
}
.pdf-text-layer > span {
color: transparent;
position: absolute;
white-space: pre;
cursor: text;
transform-origin: 0% 0%;
}
.pdf-text-layer .pdf-text-highlight {
background-color: rgba(37, 99, 235, 0.2);
border-radius: 2px;
position: static;
}
.docx-view-container span.docx-text-highlight,
.docx-view-container .docx-text-highlight {
background-color: rgba(37, 99, 235, 0.35) !important;
border-radius: 2px;
padding: 0 1px;
color: inherit !important;
}
/* docx-preview tracked-change styling */
.docx-view-container ins {
color: #16a34a;
text-decoration: none;
background-color: rgba(22, 163, 74, 0.08);
}
.docx-view-container del {
color: #dc2626;
text-decoration: line-through;
background-color: rgba(220, 38, 38, 0.08);
}
/* Kill docx-preview's default dark-gray wrapper chrome let the scroll
container's own bg show through. */
.docx-view-container .docx-wrapper {
background: transparent !important;
padding: 0 !important;
}
.docx-view-container .docx-wrapper > section.docx {
margin: 0 auto 16px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.docx-view-container .docx-edit-flash {
animation: docxEditFlash 2s ease-out;
border-radius: 2px;
}
/* Optimistic Accept/Reject: instantly hide rejected side / de-style kept side.
These are ephemeral DOM mutations; the real re-render replaces the markup. */
.docx-view-container .docx-edit-hidden {
display: none !important;
}
.docx-view-container ins.docx-edit-kept,
.docx-view-container del.docx-edit-kept {
color: inherit !important;
background-color: transparent !important;
text-decoration: none !important;
}
@keyframes docxEditFlash {
0%, 20% {
background-color: rgba(59, 130, 246, 0.45);
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.45);
}
100% {
background-color: rgba(59, 130, 246, 0);
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0);
}
}

View file

@ -0,0 +1,937 @@
"use client";
import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { streamChat, streamProjectChat } from "@/app/lib/mikeApi";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
import { useGenerateChatTitle } from "./useGenerateChatTitle";
import type {
AssistantEvent,
MikeCitationAnnotation,
MikeMessage,
} from "@/app/components/shared/types";
interface UseAssistantChatOptions {
initialMessages?: MikeMessage[];
chatId?: string;
projectId?: string;
}
function findLastContentIndex(events: AssistantEvent[]): number {
for (let i = events.length - 1; i >= 0; i--) {
if (events[i].type === "content") return i;
}
return -1;
}
export function useAssistantChat({
initialMessages = [],
chatId: initialChatId,
projectId,
}: UseAssistantChatOptions = {}) {
const router = useRouter();
const {
replaceChatId,
loadChats,
setCurrentChatId,
saveChat,
setNewChatMessages,
} = useChatHistoryContext();
const { generate: generateTitle } = useGenerateChatTitle();
const [messages, setMessages] = useState<MikeMessage[]>(initialMessages);
const [isResponseLoading, setIsResponseLoading] = useState(false);
const [isLoadingCitations, setIsLoadingCitations] = useState(false);
const [chatId, setChatId] = useState<string | undefined>(initialChatId);
const abortControllerRef = useRef<AbortController | null>(null);
const dripIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const dripTargetRef = useRef<string>("");
const dripDisplayLenRef = useRef<number>(0);
const eventsRef = useRef<AssistantEvent[]>([]);
const DRIP_CHARS_PER_TICK = 8;
const stopDrip = () => {
if (dripIntervalRef.current !== null) {
clearInterval(dripIntervalRef.current);
dripIntervalRef.current = null;
}
};
const updateLastContentEvent = (
prev: MikeMessage[],
text: string,
isStreaming?: boolean,
): MikeMessage[] => {
const updated = [...prev];
const last = updated[updated.length - 1];
if (last?.role !== "assistant") return prev;
const events = last.events ?? [];
const idx = findLastContentIndex(events);
if (idx < 0) return prev;
const newEvents = [...events];
newEvents[idx] = isStreaming
? { type: "content", text, isStreaming: true }
: { type: "content", text };
updated[updated.length - 1] = { ...last, events: newEvents };
return updated;
};
const flushDrip = () => {
stopDrip();
const target = dripTargetRef.current;
dripDisplayLenRef.current = target.length;
setMessages((prev) => updateLastContentEvent(prev, target));
};
/**
* Finalize any in-flight streaming content event and reset the drip
* counters so the next content_delta starts a fresh block. Called
* before any non-content event is appended, so interleaved content /
* reasoning / tool events stay in chronological order without the
* later content block inheriting the earlier block's accumulated text.
*/
const finalizeStreamingContent = () => {
stopDrip();
const events = eventsRef.current;
const last = events[events.length - 1];
if (last?.type === "content" && last.isStreaming) {
const finalText = dripTargetRef.current;
eventsRef.current = [
...events.slice(0, -1),
{ type: "content", text: finalText },
];
const snapshot = [...eventsRef.current];
setMessages((prev) => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg?.role === "assistant") {
updated[updated.length - 1] = {
...lastMsg,
events: snapshot,
};
}
return updated;
});
}
dripTargetRef.current = "";
dripDisplayLenRef.current = 0;
};
// If the model transitions from reasoning into content/tool without a
// reasoning_block_end (or the events arrive out of order), the prior
// reasoning event would otherwise stay flagged isStreaming forever.
const finalizeStreamingReasoning = () => {
const events = eventsRef.current;
const last = events[events.length - 1];
if (last?.type !== "reasoning" || !last.isStreaming) return;
eventsRef.current = [
...events.slice(0, -1),
{ type: "reasoning", text: last.text },
];
const snapshot = [...eventsRef.current];
setMessages((prev) => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg?.role === "assistant") {
updated[updated.length - 1] = {
...lastMsg,
events: snapshot,
};
}
return updated;
});
};
const startDrip = () => {
if (dripIntervalRef.current !== null) return;
dripIntervalRef.current = setInterval(() => {
const target = dripTargetRef.current;
const displayLen = dripDisplayLenRef.current;
if (displayLen >= target.length) return;
const newLen = Math.min(
displayLen + DRIP_CHARS_PER_TICK,
target.length,
);
dripDisplayLenRef.current = newLen;
const visibleText = target.slice(0, newLen);
const events = eventsRef.current;
const lastIdx = events.length - 1;
const last = events[lastIdx];
if (last?.type === "content" && last.isStreaming) {
const next = events.slice();
next[lastIdx] = {
type: "content",
text: visibleText,
isStreaming: true,
};
eventsRef.current = next;
}
setMessages((prev) =>
updateLastContentEvent(prev, visibleText, true),
);
}, 16);
};
const cancel = () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
setIsResponseLoading(false);
setIsLoadingCitations(false);
}
};
// Transient placeholder events (tool_call_start, thinking) fill the
// latency gap between real SSE events so the wrapper doesn't look stuck.
// Anytime a real event arrives, drop any streaming placeholder first.
const isStreamingPlaceholder = (e: AssistantEvent) =>
(e.type === "tool_call_start" || e.type === "thinking") &&
!!e.isStreaming;
const clearStreamingPlaceholders = () => {
const before = eventsRef.current;
const after = before.filter((e) => !isStreamingPlaceholder(e));
if (after.length === before.length) return;
eventsRef.current = after;
const snapshot = [...after];
setMessages((prev) => {
const updated = [...prev];
const last = updated[updated.length - 1];
if (last?.role === "assistant") {
updated[updated.length - 1] = { ...last, events: snapshot };
}
return updated;
});
};
const pushThinkingPlaceholder = () => {
const events = eventsRef.current;
const last = events[events.length - 1];
// Don't stack placeholders back-to-back; one "Thinking…" line is plenty.
if (last && isStreamingPlaceholder(last)) return;
eventsRef.current = [
...events,
{ type: "thinking" as const, isStreaming: true },
];
const snapshot = [...eventsRef.current];
setMessages((prev) => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg?.role === "assistant") {
updated[updated.length - 1] = { ...lastMsg, events: snapshot };
}
return updated;
});
};
const pushEvent = (event: AssistantEvent) => {
finalizeStreamingContent();
finalizeStreamingReasoning();
// Drop any in-flight placeholder unless we're pushing one ourselves.
let next = eventsRef.current;
if (event.type !== "tool_call_start" && event.type !== "thinking") {
next = next.filter((e) => !isStreamingPlaceholder(e));
}
eventsRef.current = [...next, event];
const snapshot = [...eventsRef.current];
setMessages((prev) => {
const updated = [...prev];
const last = updated[updated.length - 1];
if (last?.role === "assistant") {
updated[updated.length - 1] = { ...last, events: snapshot };
}
return updated;
});
};
const updateMatchingEvent = (
predicate: (e: AssistantEvent) => boolean,
updater: (e: AssistantEvent) => AssistantEvent,
) => {
const events = eventsRef.current;
const idx = [...events]
.map((_, i) => i)
.reverse()
.find((i) => predicate(events[i]));
if (idx === undefined) return;
const newEvents = [...events];
newEvents[idx] = updater(events[idx]);
eventsRef.current = newEvents;
const snapshot = [...newEvents];
setMessages((prev) => {
const updated = [...prev];
const last = updated[updated.length - 1];
if (last?.role === "assistant") {
updated[updated.length - 1] = { ...last, events: snapshot };
}
return updated;
});
};
const handleChat = async (
message: MikeMessage,
opts?: {
displayedDoc?: { filename: string; documentId: string } | null;
},
): Promise<string | null> => {
if (!message.content.trim()) return null;
setIsResponseLoading(true);
const lastMessage = messages[messages.length - 1];
const isMessageAlreadyAdded =
lastMessage &&
lastMessage.role === "user" &&
lastMessage.content === message.content;
const newMessages: MikeMessage[] = isMessageAlreadyAdded
? messages
: [...messages, message];
setMessages([
...newMessages,
{ role: "assistant", content: "", annotations: [], events: [] },
]);
let streamedChatId: string | null = null;
stopDrip();
dripTargetRef.current = "";
dripDisplayLenRef.current = 0;
eventsRef.current = [];
try {
const controller = new AbortController();
abortControllerRef.current = controller;
const apiMessages = newMessages.map((currentMessage) => ({
role: currentMessage.role,
content: currentMessage.content,
files: currentMessage.files,
workflow: currentMessage.workflow,
}));
const model = message.model;
const displayedDoc = opts?.displayedDoc ?? null;
// Pull the user's attachments from the just-submitted message.
// These are the files dragged into / picked from the chat input
// for this turn (separate from the running history of past
// attachments). Sent as a request-level field so the backend
// can call them out specifically in the system prompt.
const attachedDocs = (
message.files?.filter((f) => !!f.document_id) ?? []
).map((f) => ({
filename: f.filename,
document_id: f.document_id as string,
}));
const response = await (projectId
? streamProjectChat({
projectId,
messages: apiMessages,
chat_id: chatId,
model,
displayed_doc: displayedDoc
? {
filename: displayedDoc.filename,
document_id: displayedDoc.documentId,
}
: undefined,
attached_documents:
attachedDocs.length > 0 ? attachedDocs : undefined,
signal: controller.signal,
})
: streamChat({
messages: apiMessages,
chat_id: chatId,
model,
signal: controller.signal,
}));
if (!response.ok) {
const errText = await response.text();
throw new Error(`HTTP ${response.status}: ${errText}`);
}
const reader = response.body?.getReader();
if (!reader) throw new Error("No response body");
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || !trimmed.startsWith("data:")) continue;
const dataStr = trimmed.slice(5).trim();
if (dataStr === "[DONE]") continue;
try {
const data = JSON.parse(dataStr);
if (data.type === "chat_id") {
streamedChatId = data.chatId;
setChatId(data.chatId);
setCurrentChatId(data.chatId);
continue;
}
if (data.type === "content_done") {
setIsLoadingCitations(true);
continue;
}
if (data.type === "content_delta") {
const text = data.text as string;
// Real content is streaming — retire any
// "Thinking…" / "Running…" placeholders, and
// finalize any in-flight reasoning block so it
// doesn't get stuck rendering as streaming.
clearStreamingPlaceholders();
finalizeStreamingReasoning();
// Ensure a streaming content event exists. If
// the last event isn't already a streaming
// content block, start a fresh one — and reset
// the drip so we don't inherit a previous
// block's accumulated text.
const events = eventsRef.current;
const lastEvent = events[events.length - 1];
if (
lastEvent?.type !== "content" ||
!lastEvent.isStreaming
) {
dripTargetRef.current = text;
dripDisplayLenRef.current = 0;
eventsRef.current = [
...events,
{
type: "content" as const,
text: "",
isStreaming: true,
},
];
const snapshot = [...eventsRef.current];
setMessages((prev) => {
const updated = [...prev];
const last = updated[updated.length - 1];
if (last?.role === "assistant") {
updated[updated.length - 1] = {
...last,
events: snapshot,
};
}
return updated;
});
} else {
dripTargetRef.current += text;
}
startDrip();
continue;
}
if (data.type === "reasoning_delta") {
const text = data.text as string;
let events = eventsRef.current;
const last = events[events.length - 1];
if (
last?.type === "reasoning" &&
last.isStreaming
) {
eventsRef.current = [
...events.slice(0, -1),
{
type: "reasoning" as const,
text: last.text + text,
isStreaming: true,
},
];
} else {
// New reasoning block — finalize any in-flight
// content event first so the next content_delta
// starts a fresh block at the correct position.
finalizeStreamingContent();
clearStreamingPlaceholders();
events = eventsRef.current;
eventsRef.current = [
...events,
{
type: "reasoning" as const,
text,
isStreaming: true,
},
];
}
const snapshot = [...eventsRef.current];
setMessages((prev) => {
const updated = [...prev];
const last = updated[updated.length - 1];
if (last?.role === "assistant") {
updated[updated.length - 1] = {
...last,
events: snapshot,
};
}
return updated;
});
continue;
}
if (data.type === "reasoning_block_end") {
const events = eventsRef.current;
const last = events[events.length - 1];
if (
last?.type === "reasoning" &&
last.isStreaming
) {
eventsRef.current = [
...events.slice(0, -1),
{
type: "reasoning" as const,
text: last.text,
},
];
}
const snapshot = [...eventsRef.current];
setMessages((prev) => {
const updated = [...prev];
const last = updated[updated.length - 1];
if (last?.role === "assistant") {
updated[updated.length - 1] = {
...last,
events: snapshot,
};
}
return updated;
});
pushThinkingPlaceholder();
continue;
}
if (data.type === "tool_call_start") {
// Transient placeholder so the client immediately
// shows activity after Claude ends a turn with
// tool_use. Replaced by the real tool event
// (doc_edited_start, doc_read_start, …) if one
// arrives; otherwise it lingers as a "Working…"
// indicator until the next iteration streams.
pushEvent({
type: "tool_call_start",
name: (data.name as string) ?? "",
isStreaming: true,
});
continue;
}
if (data.type === "workflow_applied") {
pushEvent({
type: "workflow_applied",
workflow_id: data.workflow_id as string,
title: data.title as string,
});
continue;
}
if (data.type === "doc_read_start") {
pushEvent({
type: "doc_read",
filename: data.filename as string,
isStreaming: true,
});
continue;
}
if (data.type === "doc_read") {
updateMatchingEvent(
(e) =>
e.type === "doc_read" &&
e.filename === data.filename &&
!!e.isStreaming,
(e) => ({ ...e, isStreaming: false }),
);
pushThinkingPlaceholder();
continue;
}
if (data.type === "doc_find_start") {
pushEvent({
type: "doc_find",
filename: data.filename as string,
query: (data.query as string) ?? "",
total_matches: 0,
isStreaming: true,
});
continue;
}
if (data.type === "doc_find") {
updateMatchingEvent(
(e) =>
e.type === "doc_find" &&
e.filename === data.filename &&
e.query === (data.query as string) &&
!!e.isStreaming,
(e) => ({
...e,
isStreaming: false,
total_matches:
typeof data.total_matches === "number"
? (data.total_matches as number)
: (
e as {
type: "doc_find";
total_matches: number;
}
).total_matches,
}),
);
pushThinkingPlaceholder();
continue;
}
if (data.type === "doc_created_start") {
pushEvent({
type: "doc_created",
filename: data.filename as string,
download_url: "",
isStreaming: true,
});
continue;
}
if (data.type === "doc_download") {
pushEvent({
type: "doc_download",
filename: data.filename as string,
download_url: data.download_url as string,
});
continue;
}
if (data.type === "doc_created") {
updateMatchingEvent(
(e) =>
e.type === "doc_created" &&
e.filename === data.filename &&
!!e.isStreaming,
(e) => {
const next: Extract<
AssistantEvent,
{ type: "doc_created" }
> = {
type: "doc_created",
filename: (e as { filename: string })
.filename,
download_url:
data.download_url as string,
isStreaming: false,
};
if (typeof data.document_id === "string") {
next.document_id =
data.document_id as string;
}
if (typeof data.version_id === "string") {
next.version_id =
data.version_id as string;
}
if (
typeof data.version_number === "number"
) {
next.version_number =
data.version_number as number;
}
return next;
},
);
pushThinkingPlaceholder();
continue;
}
if (data.type === "doc_replicate_start") {
pushEvent({
type: "doc_replicated",
filename: data.filename as string,
count:
typeof data.count === "number"
? (data.count as number)
: 1,
isStreaming: true,
});
continue;
}
if (data.type === "doc_replicated") {
updateMatchingEvent(
(e) =>
e.type === "doc_replicated" &&
e.filename === data.filename &&
!!e.isStreaming,
() => ({
type: "doc_replicated",
filename: data.filename as string,
count:
typeof data.count === "number"
? (data.count as number)
: Array.isArray(data.copies)
? (data.copies as unknown[])
.length
: 1,
copies: Array.isArray(data.copies)
? (data.copies as {
new_filename: string;
document_id: string;
version_id: string;
}[])
: undefined,
error:
typeof data.error === "string"
? (data.error as string)
: undefined,
isStreaming: false,
}),
);
pushThinkingPlaceholder();
continue;
}
if (data.type === "doc_edited_start") {
pushEvent({
type: "doc_edited",
filename: data.filename as string,
document_id: "",
version_id: "",
download_url: "",
annotations: [],
isStreaming: true,
});
continue;
}
if (data.type === "doc_edited") {
updateMatchingEvent(
(e) =>
e.type === "doc_edited" &&
e.filename === data.filename &&
!!e.isStreaming,
() => ({
type: "doc_edited",
filename: data.filename as string,
document_id:
(data.document_id as string) ?? "",
version_id:
(data.version_id as string) ?? "",
version_number:
typeof data.version_number === "number"
? (data.version_number as number)
: null,
download_url:
(data.download_url as string) ?? "",
annotations: Array.isArray(data.annotations)
? (data.annotations as import("@/app/components/shared/types").MikeEditAnnotation[])
: [],
error:
typeof data.error === "string"
? (data.error as string)
: undefined,
isStreaming: false,
}),
);
pushThinkingPlaceholder();
continue;
}
if (data.type === "citations") {
// End-of-stream signal — scrub any lingering
// placeholders so they don't persist into the
// finalised message.
clearStreamingPlaceholders();
const incoming = (data.citations ??
[]) as MikeCitationAnnotation[];
setMessages((prev) => {
const updated = [...prev];
const last = updated[updated.length - 1];
if (last?.role === "assistant") {
updated[updated.length - 1] = {
...last,
annotations: incoming,
};
}
return updated;
});
continue;
}
} catch (e) {
console.warn(
"[useAssistantChat] failed to parse SSE line:",
trimmed,
e,
);
}
}
}
flushDrip();
finalizeStreamingReasoning();
setIsResponseLoading(false);
setIsLoadingCitations(false);
const finalChatId = streamedChatId || chatId || null;
if (finalChatId && finalChatId !== chatId) {
if (chatId) {
replaceChatId(
chatId,
finalChatId,
message.content.trim().slice(0, 120) || "New Chat",
);
}
setCurrentChatId(finalChatId);
const chatBasePath = projectId
? `/projects/${projectId}/assistant/chat`
: `/assistant/chat`;
router.replace(`${chatBasePath}/${finalChatId}`);
}
await loadChats();
const finalChatIdForTitle = streamedChatId || chatId || null;
if (finalChatIdForTitle && newMessages.length === 1) {
const titleParts = [message.content];
if (message.workflow)
titleParts.push(`Workflow: ${message.workflow.title}`);
if (message.files?.length)
titleParts.push(
`Files: ${message.files.map((f) => f.filename).join(", ")}`,
);
void generateTitle(finalChatIdForTitle, titleParts.join("\n"));
}
return streamedChatId || null;
} catch (error: any) {
if (error.name === "AbortError") {
flushDrip();
setMessages((prev) => {
const last = prev[prev.length - 1];
if (last?.role === "assistant") {
const updated = [...prev];
const events = last.events ?? [];
const idx = findLastContentIndex(events);
const cancelText = "Cancelled by user";
if (idx >= 0) {
const newEvents = [...events];
const existing = newEvents[idx] as {
type: "content";
text: string;
};
newEvents[idx] = {
type: "content",
text: existing.text
? `${existing.text}\n\nCancelled by user`
: cancelText,
};
updated[updated.length - 1] = {
...last,
events: newEvents,
};
} else {
updated[updated.length - 1] = {
...last,
events: [
...events,
{ type: "content", text: cancelText },
],
};
}
return updated;
}
return [
...prev,
{
role: "assistant",
content: "",
events: [
{ type: "content", text: "Cancelled by user" },
],
},
];
});
} else {
stopDrip();
const errorMessage =
typeof error?.message === "string" && error.message
? error.message
: "Sorry, something went wrong.";
setMessages((prev) => {
const last = prev[prev.length - 1];
if (last?.role === "assistant") {
const updated = [...prev];
updated[updated.length - 1] = {
...last,
error: errorMessage,
};
return updated;
}
return [
...prev,
{
role: "assistant",
content: "",
error: errorMessage,
},
];
});
}
setIsResponseLoading(false);
setIsLoadingCitations(false);
return null;
} finally {
abortControllerRef.current = null;
}
};
const handleNewChat = async (
message: MikeMessage,
projectId?: string,
): Promise<string | null> => {
if (!message.content.trim()) return null;
setMessages([message]);
setNewChatMessages([message]);
const newChatId = await saveChat(projectId);
if (newChatId) {
setChatId(newChatId);
setCurrentChatId(newChatId);
}
return newChatId;
};
return {
messages,
isResponseLoading,
setIsResponseLoading,
isLoadingCitations,
handleChat,
handleNewChat,
setMessages,
cancel,
chatId,
};
}

View file

@ -0,0 +1,98 @@
"use client";
import { useEffect, useState } from "react";
import { supabase } from "@/lib/supabase";
export interface DocumentVersionRow {
id: string;
version_number: number | null;
source:
| "upload"
| "assistant_edit"
| "user_accept"
| "user_reject"
| "generated";
created_at: string;
}
export interface DocumentVersionsResult {
versions: DocumentVersionRow[];
currentVersionId: string | null;
loading: boolean;
error: string | null;
/** Refetch externally; used after accept/reject or new assistant edits. */
refresh: () => void;
}
/**
* Fetch the list of tracked versions for a document, with the numeric
* version_number we use in UI labels ("V1", "V2", ).
*/
export function useDocumentVersions(
documentId: string | null | undefined,
refreshKey?: number,
): DocumentVersionsResult {
const [versions, setVersions] = useState<DocumentVersionRow[]>([]);
const [currentVersionId, setCurrentVersionId] = useState<string | null>(
null,
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [tick, setTick] = useState(0);
useEffect(() => {
if (!documentId) {
setVersions([]);
setCurrentVersionId(null);
return;
}
let cancelled = false;
setLoading(true);
setError(null);
(async () => {
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ??
"http://localhost:3001";
const resp = await fetch(
`${apiBase}/single-documents/${documentId}/versions`,
{
headers: token
? { Authorization: `Bearer ${token}` }
: {},
},
);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = (await resp.json()) as {
versions: DocumentVersionRow[];
current_version_id: string | null;
};
if (cancelled) return;
setVersions(data.versions ?? []);
setCurrentVersionId(data.current_version_id ?? null);
} catch (e) {
if (!cancelled)
setError(e instanceof Error ? e.message : String(e));
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [documentId, refreshKey, tick]);
return {
versions,
currentVersionId,
loading,
error,
refresh: () => setTick((t) => t + 1),
};
}

View file

@ -0,0 +1,150 @@
"use client";
import { useEffect, useState } from "react";
import { supabase } from "@/lib/supabase";
export interface FetchDocxResult {
bytes: ArrayBuffer | null;
downloadUrl: string | null;
loading: boolean;
error: string | null;
}
// Module-level cache keyed by `${documentId}:${versionId}:${refetchKey}`.
// The same cache is shared across every hook instance so tab switches
// (which remount new DocxView subtrees or re-run the effect because of an
// unstable prop upstream) don't cause a refetch as long as the tuple is
// unchanged. Promises are cached too, so concurrent mounts for the same
// key share a single in-flight request.
const bytesCache = new Map<string, ArrayBuffer>();
const inFlight = new Map<string, Promise<ArrayBuffer>>();
function cacheKey(
documentId: string,
versionId?: string | null,
refetchKey?: number,
): string {
return `${documentId}:${versionId ?? ""}:${refetchKey ?? ""}`;
}
/**
* Fetch the raw .docx bytes for a document, optionally targeting a specific
* tracked-changes version. Results are cached so the DocxView can re-render
* cheaply when switching between versions, and tab switches don't refetch.
*/
export function useFetchDocxBytes(
documentId: string | null | undefined,
versionId?: string | null,
refetchKey?: number,
): FetchDocxResult {
const initialKey = documentId
? cacheKey(documentId, versionId, refetchKey)
: null;
const [bytes, setBytes] = useState<ArrayBuffer | null>(
initialKey ? (bytesCache.get(initialKey) ?? null) : null,
);
const [downloadUrl, setDownloadUrl] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
console.log("[useFetchDocxBytes] init", {
documentId,
versionId,
refetchKey,
initialKey,
cacheHit: initialKey ? bytesCache.has(initialKey) : null,
});
useEffect(() => {
if (!documentId) {
setBytes(null);
setDownloadUrl(null);
return;
}
const key = cacheKey(documentId, versionId, refetchKey);
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3001";
const qs = versionId
? `?version_id=${encodeURIComponent(versionId)}`
: "";
const url = `${apiBase}/single-documents/${documentId}/docx${qs}`;
// Cache hit: reuse bytes synchronously, no network, no spinner.
const cached = bytesCache.get(key);
if (cached) {
setBytes(cached);
setDownloadUrl(url);
setLoading(false);
setError(null);
return;
}
let cancelled = false;
setLoading(true);
setError(null);
const pending =
inFlight.get(key) ??
(async () => {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
// Stream bytes through the backend (avoids CORS on R2
// signed URLs).
const bin = await fetch(url, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!bin.ok) throw new Error(`HTTP ${bin.status}`);
const buf = await bin.arrayBuffer();
bytesCache.set(key, buf);
return buf;
})();
if (!inFlight.has(key)) inFlight.set(key, pending);
pending
.then((buf) => {
if (cancelled) return;
setBytes(buf);
setDownloadUrl(url);
})
.catch((e: unknown) => {
if (cancelled) return;
setError(e instanceof Error ? e.message : String(e));
})
.finally(() => {
inFlight.delete(key);
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [documentId, versionId, refetchKey]);
return { bytes, downloadUrl, loading, error };
}
/**
* Evict cache entries for a given document (e.g. after accept/reject
* writes new bytes at the same storage path, or the user uploads a new
* version). Pass a versionId to scope eviction; omit to clear every
* cached version for that document.
*/
export function invalidateDocxBytes(
documentId: string,
versionId?: string | null,
): void {
if (versionId !== undefined) {
for (const key of Array.from(bytesCache.keys())) {
if (key.startsWith(`${documentId}:${versionId ?? ""}:`)) {
bytesCache.delete(key);
}
}
return;
}
for (const key of Array.from(bytesCache.keys())) {
if (key.startsWith(`${documentId}:`)) bytesCache.delete(key);
}
}

View file

@ -0,0 +1,89 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { supabase } from "@/lib/supabase";
/**
* /display returns either PDF bytes (when the active version has a PDF
* rendition) or raw DOCX bytes otherwise. Reporting the type lets the
* caller swap between DocView (PDF.js) and DocxView (docx-preview)
* accordingly.
*/
export type DocResult =
| { type: "pdf"; buffer: ArrayBuffer }
| { type: "docx" }
| null;
export function useFetchSingleDoc(
documentId: string | null | undefined,
versionId?: string | null,
) {
const [result, setResult] = useState<DocResult>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const prevKeyRef = useRef<string | null>(null);
useEffect(() => {
if (!documentId) return;
const requestKey = `${documentId}:${versionId ?? "current"}`;
if (requestKey === prevKeyRef.current) return;
prevKeyRef.current = requestKey;
setLoading(true);
setError(null);
setResult(null);
let cancelled = false;
(async () => {
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
if (cancelled) return;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ??
"http://localhost:3001";
const qs = versionId
? `?version_id=${encodeURIComponent(versionId)}`
: "";
const response = await fetch(
`${apiBase}/single-documents/${documentId}/display${qs}`,
{
headers: token
? { Authorization: `Bearer ${token}` }
: {},
},
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
if (cancelled) return;
const contentType =
response.headers.get("content-type") ?? "";
if (contentType.includes("application/pdf")) {
const buffer = await response.arrayBuffer();
if (!cancelled) setResult({ type: "pdf", buffer });
} else {
// Drain the body so the connection is reusable, but the
// bytes are useless to the PDF viewer — the caller will
// fall back to DocxView, which fetches `/docx` itself.
await response.arrayBuffer().catch(() => {});
if (!cancelled) setResult({ type: "docx" });
}
} catch {
if (!cancelled) setError("Failed to load document.");
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
prevKeyRef.current = null;
};
}, [documentId, versionId]);
return { result, loading, error };
}

View file

@ -0,0 +1,23 @@
"use client";
import { useCallback } from "react";
import { generateChatTitle } from "@/app/lib/mikeApi";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
export function useGenerateChatTitle() {
const { renameChat } = useChatHistoryContext();
const generate = useCallback(
async (chatId: string, message: string): Promise<void> => {
try {
const { title } = await generateChatTitle(chatId, message);
await renameChat(chatId, title);
} catch {
// best-effort — title generation should never break the chat
}
},
[renameChat],
);
return { generate };
}

View file

@ -0,0 +1,31 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { ALLOWED_MODEL_IDS, DEFAULT_MODEL_ID } from "../components/assistant/ModelToggle";
const STORAGE_KEY = "mike.selectedModel";
function readStored(): string {
if (typeof window === "undefined") return DEFAULT_MODEL_ID;
const raw = window.localStorage.getItem(STORAGE_KEY);
if (raw && ALLOWED_MODEL_IDS.has(raw)) return raw;
return DEFAULT_MODEL_ID;
}
export function useSelectedModel(): [string, (id: string) => void] {
const [model, setModelState] = useState<string>(DEFAULT_MODEL_ID);
useEffect(() => {
setModelState(readStored());
}, []);
const setModel = useCallback((id: string) => {
const next = ALLOWED_MODEL_IDS.has(id) ? id : DEFAULT_MODEL_ID;
setModelState(next);
if (typeof window !== "undefined") {
window.localStorage.setItem(STORAGE_KEY, next);
}
}, []);
return [model, setModel];
}

128
frontend/src/app/icon.svg Normal file
View file

@ -0,0 +1,128 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="100 100 300 300">
<defs>
<clipPath id="topClip">
<rect x="30" y="-25" width="130" height="23" />
</clipPath>
<path id="blade" d="M 40,0 A 4,4 0 0 1 43,-3 Q 95,-22 147,-3 A 4,4 0 0 1 150,0 A 4,4 0 0 1 147,3 Q 95,22 43,3 A 4,4 0 0 1 40,0 Z" />
<linearGradient id="specular" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.85" />
<stop offset="25%" stop-color="#ffffff" stop-opacity="0.4" />
<stop offset="50%" stop-color="#ffffff" stop-opacity="0" />
<stop offset="100%" stop-color="#ffffff" stop-opacity="0" />
</linearGradient>
<linearGradient id="glassBorder" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.8" />
<stop offset="50%" stop-color="#6699cc" stop-opacity="0.5" />
<stop offset="100%" stop-color="#ffffff" stop-opacity="0.65" />
</linearGradient>
<filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
<feDropShadow dx="0" dy="1.5" stdDeviation="3" flood-color="#111827" flood-opacity="0.35" />
</filter>
<linearGradient id="glassFill" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#374151" stop-opacity="0.9" />
<stop offset="30%" stop-color="#4b5563" stop-opacity="0.8" />
<stop offset="70%" stop-color="#1f2937" stop-opacity="0.9" />
<stop offset="100%" stop-color="#374151" stop-opacity="0.9" />
</linearGradient>
<linearGradient id="prism" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#111827" stop-opacity="0.95" />
<stop offset="20%" stop-color="#374151" stop-opacity="0.85" />
<stop offset="40%" stop-color="#0f172a" stop-opacity="0.95" />
<stop offset="60%" stop-color="#1f2937" stop-opacity="0.85" />
<stop offset="80%" stop-color="#111827" stop-opacity="0.95" />
<stop offset="100%" stop-color="#374151" stop-opacity="0.75" />
</linearGradient>
<linearGradient id="innerLight" x1="100%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0" />
<stop offset="40%" stop-color="#6b7280" stop-opacity="0.3" />
<stop offset="60%" stop-color="#111827" stop-opacity="0.2" />
<stop offset="100%" stop-color="#ffffff" stop-opacity="0" />
</linearGradient>
</defs>
<g transform="translate(250,250)">
<g transform="rotate(0)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(30)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(60)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(90)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(120)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(150)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(180)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(210)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(240)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(270)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(300)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
<g transform="rotate(330)" filter="url(#shadow)">
<use href="#blade" fill="url(#glassFill)" />
<use href="#blade" fill="url(#innerLight)" />
<use href="#blade" fill="url(#prism)" opacity="0.3" />
<use href="#blade" fill="url(#specular)" clip-path="url(#topClip)" />
<use href="#blade" fill="none" stroke="url(#glassBorder)" stroke-width="1" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 6.9 KiB

View file

@ -0,0 +1,44 @@
import type { Metadata } from "next";
import { Inter, EB_Garamond } from "next/font/google";
import "./globals.css";
import { Providers } from "@/components/providers";
const inter = Inter({
variable: "--font-inter",
subsets: ["latin"],
});
const ebGaramond = EB_Garamond({
variable: "--font-eb-garamond",
subsets: ["latin"],
weight: ["400", "500", "600", "700"],
});
export const metadata: Metadata = {
title: "Mike - AI Legal Platform",
description:
"AI-powered legal document analysis and contract review platform.",
icons: {
icon: [
{ url: "/icon.svg", type: "image/svg+xml" },
{ url: "/favicon.ico" },
],
apple: "/apple-touch-icon.png",
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${inter.variable} ${ebGaramond.variable} font-sans antialiased`}
>
<Providers>{children}</Providers>
</body>
</html>
);
}

View file

@ -0,0 +1,817 @@
/**
* Mike API client all requests to the Node.js backend.
* Attaches the Supabase auth token for user authentication.
*/
import { supabase } from "@/lib/supabase";
import type {
AssistantEvent,
MikeChat,
MikeChatDetailOut,
MikeCitationAnnotation,
MikeDocument,
MikeFolder,
MikeMessage,
MikeProject,
MikeWorkflow,
TabularReview,
TabularReviewDetailOut,
} from "@/app/components/shared/types";
// Server-side shape before mapping
interface ServerMessage {
id: string;
chat_id: string;
role: "user" | "assistant";
content: string | AssistantEvent[] | null;
files?: { filename: string; document_id?: string }[] | null;
workflow?: { id: string; title: string } | null;
annotations?: MikeCitationAnnotation[] | null;
created_at: string;
}
interface ServerChatDetailOut {
chat: MikeChat;
messages: ServerMessage[];
}
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3001";
async function getAuthHeader(): Promise<Record<string, string>> {
const {
data: { session },
} = await supabase.auth.getSession();
if (!session?.access_token) return {};
return { Authorization: `Bearer ${session.access_token}` };
}
async function apiRequest<T>(path: string, init?: RequestInit): Promise<T> {
const authHeaders = await getAuthHeader();
const { headers: initHeaders, ...restInit } = init ?? {};
const response = await fetch(`${API_BASE}${path}`, {
cache: "no-store",
...restInit,
headers: {
Accept: "application/json",
...authHeaders,
...(initHeaders as Record<string, string> | undefined),
},
});
if (!response.ok) {
const detail = await response.text();
throw new Error(detail || `API error: ${response.status}`);
}
if (
response.status === 204 ||
response.headers.get("content-length") === "0"
) {
return undefined as T;
}
return (await response.json()) as T;
}
// ---------------------------------------------------------------------------
// Projects
// ---------------------------------------------------------------------------
export async function listProjects(): Promise<MikeProject[]> {
return apiRequest<MikeProject[]>("/projects");
}
export async function createProject(
name: string,
cm_number?: string,
shared_with?: string[],
): Promise<MikeProject> {
return apiRequest<MikeProject>("/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, cm_number, shared_with }),
});
}
export async function deleteAccount(): Promise<void> {
return apiRequest<void>("/user/account", { method: "DELETE" });
}
export async function getProject(projectId: string): Promise<MikeProject> {
return apiRequest<MikeProject>(`/projects/${projectId}`);
}
export async function updateProject(
projectId: string,
payload: {
name?: string;
cm_number?: string;
shared_with?: string[];
},
): Promise<MikeProject> {
return apiRequest<MikeProject>(`/projects/${projectId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function deleteProject(projectId: string): Promise<void> {
await apiRequest(`/projects/${projectId}`, { method: "DELETE" });
}
export interface ProjectPeople {
owner: {
user_id: string;
email: string | null;
display_name: string | null;
};
members: { email: string; display_name: string | null }[];
}
export async function getProjectPeople(
projectId: string,
): Promise<ProjectPeople> {
return apiRequest<ProjectPeople>(`/projects/${projectId}/people`);
}
// ---------------------------------------------------------------------------
// Documents
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Folders
// ---------------------------------------------------------------------------
export async function createProjectFolder(
projectId: string,
name: string,
parentFolderId?: string | null,
): Promise<MikeFolder> {
return apiRequest<MikeFolder>(`/projects/${projectId}/folders`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
parent_folder_id: parentFolderId ?? null,
}),
});
}
export async function renameProjectFolder(
projectId: string,
folderId: string,
name: string,
): Promise<MikeFolder> {
return apiRequest<MikeFolder>(
`/projects/${projectId}/folders/${folderId}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
},
);
}
export async function deleteProjectFolder(
projectId: string,
folderId: string,
): Promise<void> {
await apiRequest(`/projects/${projectId}/folders/${folderId}`, {
method: "DELETE",
});
}
export async function moveSubfolderToFolder(
projectId: string,
folderId: string,
parentFolderId: string | null,
): Promise<MikeFolder> {
return apiRequest<MikeFolder>(
`/projects/${projectId}/folders/${folderId}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ parent_folder_id: parentFolderId }),
},
);
}
export async function moveDocumentToFolder(
projectId: string,
documentId: string,
folderId: string | null,
): Promise<MikeDocument> {
return apiRequest<MikeDocument>(
`/projects/${projectId}/documents/${documentId}/folder`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ folder_id: folderId }),
},
);
}
export async function addDocumentToProject(
projectId: string,
documentId: string,
): Promise<MikeDocument> {
return apiRequest<MikeDocument>(
`/projects/${projectId}/documents/${documentId}`,
{ method: "POST" },
);
}
export interface MikeDocumentVersion {
id: string;
version_number: number | null;
source: string;
created_at: string;
display_name: string | null;
}
export async function listDocumentVersions(
documentId: string,
): Promise<{
current_version_id: string | null;
versions: MikeDocumentVersion[];
}> {
return apiRequest(`/single-documents/${documentId}/versions`);
}
export async function uploadDocumentVersion(
documentId: string,
file: File,
displayName?: string,
): Promise<MikeDocumentVersion> {
const authHeaders = await getAuthHeader();
const form = new FormData();
form.append("file", file);
if (displayName) form.append("display_name", displayName);
const response = await fetch(
`${API_BASE}/single-documents/${documentId}/versions`,
{
method: "POST",
headers: { ...authHeaders },
body: form,
},
);
if (!response.ok) throw new Error(await response.text());
return response.json() as Promise<MikeDocumentVersion>;
}
export async function renameDocumentVersion(
documentId: string,
versionId: string,
displayName: string | null,
): Promise<MikeDocumentVersion> {
return apiRequest<MikeDocumentVersion>(
`/single-documents/${documentId}/versions/${versionId}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ display_name: displayName }),
},
);
}
export async function uploadProjectDocument(
projectId: string,
file: File,
): Promise<MikeDocument> {
const authHeaders = await getAuthHeader();
const form = new FormData();
form.append("file", file);
const response = await fetch(
`${API_BASE}/projects/${projectId}/documents`,
{
method: "POST",
headers: { ...authHeaders },
body: form,
},
);
if (!response.ok) throw new Error(await response.text());
return response.json() as Promise<MikeDocument>;
}
export async function uploadStandaloneDocument(
file: File,
): Promise<MikeDocument> {
const authHeaders = await getAuthHeader();
const form = new FormData();
form.append("file", file);
const response = await fetch(`${API_BASE}/single-documents`, {
method: "POST",
headers: { ...authHeaders },
body: form,
});
if (!response.ok) throw new Error(await response.text());
return response.json() as Promise<MikeDocument>;
}
export async function listStandaloneDocuments(): Promise<MikeDocument[]> {
return apiRequest<MikeDocument[]>("/single-documents");
}
export async function deleteDocument(documentId: string): Promise<void> {
await apiRequest(`/single-documents/${documentId}`, { method: "DELETE" });
}
export async function getDocumentUrl(
documentId: string,
versionId?: string | null,
): Promise<{ url: string; filename: string; version_id: string | null }> {
const qs = versionId
? `?version_id=${encodeURIComponent(versionId)}`
: "";
return apiRequest(`/single-documents/${documentId}/url${qs}`);
}
export async function downloadDocumentsZip(
documentIds: string[],
): Promise<Blob> {
const authHeaders = await getAuthHeader();
const response = await fetch(`${API_BASE}/single-documents/download-zip`, {
method: "POST",
cache: "no-store",
headers: {
"Content-Type": "application/json",
...authHeaders,
},
body: JSON.stringify({ document_ids: documentIds }),
});
if (!response.ok) {
const detail = await response.text();
throw new Error(detail || `API error: ${response.status}`);
}
return response.blob();
}
// ---------------------------------------------------------------------------
// Chat
// ---------------------------------------------------------------------------
export async function createChat(payload?: {
project_id?: string;
}): Promise<{ id: string }> {
return apiRequest<{ id: string }>("/chat/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload ?? {}),
});
}
export async function listChats(): Promise<MikeChat[]> {
return apiRequest<MikeChat[]>("/chat");
}
export async function listProjectChats(projectId: string): Promise<MikeChat[]> {
return apiRequest<MikeChat[]>(`/projects/${projectId}/chats`);
}
export async function getChat(chatId: string): Promise<MikeChatDetailOut> {
const raw = await apiRequest<ServerChatDetailOut>(`/chat/${chatId}`);
const messages: MikeMessage[] = raw.messages.map((m) => {
if (m.role === "user") {
return {
role: "user",
content: typeof m.content === "string" ? m.content : "",
files: m.files ?? undefined,
workflow: m.workflow ?? undefined,
};
}
const events = Array.isArray(m.content)
? (m.content as AssistantEvent[])
: undefined;
return {
role: "assistant",
content:
events
?.filter((e) => e.type === "content")
.map((e) => (e as { type: "content"; text: string }).text)
.join("") ?? "",
annotations: m.annotations ?? undefined,
events,
};
});
return { chat: raw.chat, messages };
}
export async function renameChat(chatId: string, title: string): Promise<void> {
await apiRequest(`/chat/${chatId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title }),
});
}
export async function deleteChat(chatId: string): Promise<void> {
await apiRequest(`/chat/${chatId}`, { method: "DELETE" });
}
export async function generateChatTitle(
chatId: string,
message: string,
): Promise<{ title: string }> {
return apiRequest<{ title: string }>(`/chat/${chatId}/generate-title`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message }),
});
}
export async function streamChat(payload: {
messages: {
role: string;
content: string;
files?: { filename: string; document_id?: string }[];
workflow?: { id: string; title: string };
}[];
chat_id?: string;
project_id?: string;
model?: string;
signal?: AbortSignal;
}): Promise<Response> {
const { signal, ...body } = payload;
const authHeaders = await getAuthHeader();
return fetch(`${API_BASE}/chat`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
...authHeaders,
},
body: JSON.stringify(body),
signal,
});
}
type StreamChatMessage = {
role: string;
content: string;
files?: { filename: string; document_id?: string }[];
workflow?: { id: string; title: string };
};
export async function streamProjectChat(payload: {
projectId: string;
messages: StreamChatMessage[];
chat_id?: string;
model?: string;
displayed_doc?: { filename: string; document_id: string };
attached_documents?: { filename: string; document_id: string }[];
signal?: AbortSignal;
}): Promise<Response> {
const { projectId, signal, ...body } = payload;
const authHeaders = await getAuthHeader();
return fetch(`${API_BASE}/projects/${projectId}/chat`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
...authHeaders,
},
body: JSON.stringify(body),
signal,
});
}
// ---------------------------------------------------------------------------
// Tabular Review
// ---------------------------------------------------------------------------
export async function listTabularReviews(
projectId?: string,
): Promise<TabularReview[]> {
const qs = projectId
? `?project_id=${encodeURIComponent(projectId)}`
: "";
return apiRequest<TabularReview[]>(`/tabular-review${qs}`);
}
export async function createTabularReview(payload: {
title?: string;
document_ids: string[];
columns_config: { index: number; name: string; prompt: string }[];
workflow_id?: string;
project_id?: string;
}): Promise<TabularReview> {
return apiRequest<TabularReview>("/tabular-review", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function getTabularReview(
reviewId: string,
): Promise<TabularReviewDetailOut> {
return apiRequest<TabularReviewDetailOut>(`/tabular-review/${reviewId}`);
}
export async function updateTabularReview(
reviewId: string,
payload: {
title?: string;
columns_config?: { index: number; name: string; prompt: string }[];
document_ids?: string[];
project_id?: string | null;
shared_with?: string[];
},
): Promise<TabularReview> {
return apiRequest<TabularReview>(`/tabular-review/${reviewId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function getTabularReviewPeople(
reviewId: string,
): Promise<ProjectPeople> {
return apiRequest<ProjectPeople>(`/tabular-review/${reviewId}/people`);
}
export async function generateTabularColumnPrompt(
title: string,
options?: { format?: string; documentName?: string; tags?: string[] },
): Promise<{ prompt: string; source: "preset" | "llm" | "fallback" }> {
return apiRequest<{
prompt: string;
source: "preset" | "llm" | "fallback";
}>("/tabular-review/prompt", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title,
format: options?.format,
documentName: options?.documentName,
tags: options?.tags,
}),
});
}
export async function uploadReviewDocument(
reviewId: string,
file: File,
options?: {
projectId?: string;
documentIds?: string[];
columnsConfig?: { index: number; name: string; prompt: string }[];
},
): Promise<MikeDocument> {
const uploaded = options?.projectId
? await uploadProjectDocument(options.projectId, file)
: await uploadStandaloneDocument(file);
await updateTabularReview(reviewId, {
columns_config: options?.columnsConfig,
document_ids: [...(options?.documentIds ?? []), uploaded.id],
});
return uploaded;
}
export async function deleteTabularReview(reviewId: string): Promise<void> {
await apiRequest(`/tabular-review/${reviewId}`, { method: "DELETE" });
}
export async function streamTabularGeneration(
reviewId: string,
): Promise<Response> {
const authHeaders = await getAuthHeader();
return fetch(`${API_BASE}/tabular-review/${reviewId}/generate`, {
method: "POST",
headers: { ...authHeaders },
});
}
export async function streamTabularChat(
reviewId: string,
messages: { role: string; content: string }[],
chat_id?: string | null,
signal?: AbortSignal,
context?: { reviewTitle?: string | null; projectName?: string | null },
): Promise<Response> {
const authHeaders = await getAuthHeader();
return fetch(`${API_BASE}/tabular-review/${reviewId}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json", ...authHeaders },
body: JSON.stringify({
messages,
chat_id: chat_id ?? undefined,
review_title: context?.reviewTitle ?? undefined,
project_name: context?.projectName ?? undefined,
}),
signal: signal ?? undefined,
});
}
export interface TRCitationAnnotation {
type: "tabular_citation";
ref: number;
col_index: number;
row_index: number;
col_name: string;
doc_name: string;
quote: string;
}
interface RawTRMessage {
id: string;
chat_id: string;
role: "user" | "assistant";
content: string | AssistantEvent[] | null;
annotations?: TRCitationAnnotation[] | null;
created_at: string;
}
export interface TRDisplayMessage {
role: "user" | "assistant";
content: string;
events?: AssistantEvent[];
annotations?: TRCitationAnnotation[];
}
export interface TRChat {
id: string;
title: string | null;
created_at: string;
updated_at: string;
}
export function mapTRMessages(raw: RawTRMessage[]): TRDisplayMessage[] {
return raw.map((m) => {
if (m.role === "user") {
return {
role: "user" as const,
content: typeof m.content === "string" ? m.content : "",
};
}
const events = Array.isArray(m.content)
? (m.content as AssistantEvent[])
: undefined;
const content =
events
?.filter((e) => e.type === "content")
.map((e) => (e as { type: "content"; text: string }).text)
.join("") ?? "";
return {
role: "assistant" as const,
content,
events,
annotations: m.annotations ?? undefined,
};
});
}
export async function getTabularChats(reviewId: string): Promise<TRChat[]> {
return apiRequest<TRChat[]>(`/tabular-review/${reviewId}/chats`);
}
export async function getTabularChatMessages(
reviewId: string,
chatId: string,
): Promise<RawTRMessage[]> {
return apiRequest<RawTRMessage[]>(
`/tabular-review/${reviewId}/chats/${chatId}/messages`,
);
}
export async function deleteTabularChat(
reviewId: string,
chatId: string,
): Promise<void> {
await apiRequest(`/tabular-review/${reviewId}/chats/${chatId}`, {
method: "DELETE",
});
}
export async function regenerateTabularCell(
reviewId: string,
documentId: string,
columnIndex: number,
): Promise<{
summary: string;
flag: "green" | "grey" | "yellow" | "red";
reasoning: string;
}> {
return apiRequest(`/tabular-review/${reviewId}/regenerate-cell`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
document_id: documentId,
column_index: columnIndex,
}),
});
}
export async function clearTabularCells(
reviewId: string,
documentIds: string[],
): Promise<void> {
await apiRequest(`/tabular-review/${reviewId}/clear-cells`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ document_ids: documentIds }),
});
}
// ---------------------------------------------------------------------------
// Workflows
// ---------------------------------------------------------------------------
type WorkflowType = MikeWorkflow["type"];
export async function listWorkflows(
type: WorkflowType,
): Promise<MikeWorkflow[]> {
return apiRequest<MikeWorkflow[]>(`/workflows?type=${type}`);
}
export async function getWorkflow(workflowId: string): Promise<MikeWorkflow> {
return apiRequest<MikeWorkflow>(`/workflows/${workflowId}`);
}
export async function createWorkflow(payload: {
title: string;
type: "assistant" | "tabular";
prompt_md?: string;
columns_config?: { index: number; name: string; prompt: string }[];
practice?: string | null;
}): Promise<MikeWorkflow> {
return apiRequest<MikeWorkflow>("/workflows", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function updateWorkflow(
workflowId: string,
payload: {
title?: string;
prompt_md?: string;
columns_config?: { index: number; name: string; prompt: string }[];
practice?: string | null;
},
): Promise<MikeWorkflow> {
return apiRequest<MikeWorkflow>(`/workflows/${workflowId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function deleteWorkflow(workflowId: string): Promise<void> {
await apiRequest(`/workflows/${workflowId}`, { method: "DELETE" });
}
export async function listHiddenWorkflows(): Promise<string[]> {
return apiRequest<string[]>("/workflows/hidden");
}
export async function hideWorkflow(workflowId: string): Promise<void> {
await apiRequest("/workflows/hidden", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ workflow_id: workflowId }),
});
}
export async function unhideWorkflow(workflowId: string): Promise<void> {
await apiRequest(`/workflows/hidden/${workflowId}`, { method: "DELETE" });
}
export async function shareWorkflow(
workflowId: string,
payload: { emails: string[]; allow_edit: boolean },
): Promise<void> {
await apiRequest<void>(`/workflows/${workflowId}/share`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function listWorkflowShares(
workflowId: string,
): Promise<
{
id: string;
shared_with_email: string;
allow_edit: boolean;
created_at: string;
}[]
> {
return apiRequest(`/workflows/${workflowId}/shares`);
}
export async function deleteWorkflowShare(
workflowId: string,
shareId: string,
): Promise<void> {
await apiRequest(`/workflows/${workflowId}/shares/${shareId}`, {
method: "DELETE",
});
}

View file

@ -0,0 +1,39 @@
import { MODELS, type ModelOption } from "../components/assistant/ModelToggle";
export type ModelProvider = "claude" | "gemini";
export function getModelProvider(modelId: string): ModelProvider | null {
const model = MODELS.find((m) => m.id === modelId);
if (!model) return null;
return model.group === "Anthropic" ? "claude" : "gemini";
}
export function isModelAvailable(
modelId: string,
apiKeys: { claudeApiKey: string | null; geminiApiKey: string | null },
): boolean {
const provider = getModelProvider(modelId);
if (!provider) return false;
return provider === "claude"
? !!apiKeys.claudeApiKey?.trim()
: !!apiKeys.geminiApiKey?.trim();
}
export function isProviderAvailable(
provider: ModelProvider,
apiKeys: { claudeApiKey: string | null; geminiApiKey: string | null },
): boolean {
return provider === "claude"
? !!apiKeys.claudeApiKey?.trim()
: !!apiKeys.geminiApiKey?.trim();
}
export function providerLabel(provider: ModelProvider): string {
return provider === "claude" ? "Anthropic (Claude)" : "Google (Gemini)";
}
export function modelGroupToProvider(
group: ModelOption["group"],
): ModelProvider {
return group === "Anthropic" ? "claude" : "gemini";
}

View file

@ -0,0 +1,125 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { supabase } from "@/lib/supabase";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import Link from "next/link";
import { SiteLogo } from "@/components/site-logo";
import { useAuth } from "@/contexts/AuthContext";
export default function LoginPage() {
const router = useRouter();
const { isAuthenticated, authLoading } = useAuth();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!authLoading && isAuthenticated) {
router.replace("/assistant");
}
}, [authLoading, isAuthenticated, router]);
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) throw error;
router.push("/assistant");
} catch (error: any) {
setError(error.message || "An error occurred during login");
} finally {
setLoading(false);
}
};
return (
<div className="min-h-dvh bg-white flex items-start justify-center px-6 pt-32 md:pt-40 pb-10 relative">
<div className="absolute top-4 md:top-8 left-1/2 -translate-x-1/2">
<SiteLogo size="md" className="md:text-4xl" asLink />
</div>
<div className="w-full max-w-md">
{/* Login Form */}
<div className="bg-white border border-gray-200 rounded-2xl p-8">
<div className="flex justify-between items-center mb-6">
<h2 className="text-left text-2xl font-serif">
Log In
</h2>
<div className="bg-gray-100 p-1 rounded-md flex text-xs font-medium">
<span className="text-gray-600 px-3 py-1 bg-white rounded-sm shadow-sm">
Log in
</span>
<Link
href="/signup"
className="px-3 py-1 text-gray-500 hover:text-gray-900"
>
Sign up
</Link>
</div>
</div>
<form onSubmit={handleLogin} className="space-y-4">
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700 mb-2"
>
Email
</label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
required
className="w-full"
/>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700 mb-2"
>
Password
</label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
required
className="w-full"
/>
</div>
{error && (
<div className="text-red-600 text-sm bg-red-50 p-3 rounded">
{error}
</div>
)}
<Button
type="submit"
disabled={loading}
className="w-full mt-5 bg-black hover:bg-gray-900 text-white"
>
{loading ? "Logging in..." : "Log in"}
</Button>
</form>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,24 @@
import Link from "next/link";
export default function NotFound() {
return (
<div className="min-h-screen bg-white flex items-center justify-center px-4">
<div className="text-center max-w-md">
<h1 className="text-3xl font-eb-garamond font-light text-gray-900 mb-3">
Page not found
</h1>
<p className="text-[0.9375rem] text-gray-500 leading-relaxed mb-8">
The page you&apos;re looking for doesn&apos;t exist or may
have been moved.
</p>
<Link
href="/"
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full text-sm font-medium text-white bg-gray-900 hover:bg-gray-700 transition-colors"
>
Go home
</Link>
</div>
</div>
);
}

View file

@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function RootPage() {
redirect("/assistant");
}

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