Evidence-backed use cases, prompts, integrations, evaluations, and safety notes for OpenAI GPT-6 Astra.
ai-agentsai-codingai-safetyartificial-intelligenceastraawesome-listcoding-agentscomputer-usecybersecuritydeveloper-toolsgenerative-aigpt-6gpt-6-astralarge-language-modelsllmmodel-evaluationopenaiopenai-apiprompt-engineeringresponses-api
feat: integrate GPT-6 series models, refactor history in system_prompt, and add media upload with README updates
jaiprasad0408845f570b39
diff --git a/README.md b/README.mdindex 032e135..373e153 100644--- a/README.md+++ b/README.md@@ -6,39 +6,46 @@ OpenSpaces bridges the gap between static documents and collaborative intelligen----## π Key Features--### 1. βοΈ OpenDots Living Document Canvas (TipTap)-- **Rich Document Editor**: Powered by TipTap, supporting standard Markdown, multi-level headings, tables, task lists, blockquotes, and custom code blocks.-- **Slash Commands Menu (`/`)**: Compact, keyboard-first menu to insert blocks, lists, formatting, and AI generators on the fly.-- **Insert Menu Toolbar**: Dropdown in the format toolbar to easily add tables, task lists, code blocks, dividers, and AI nodes.-- **Seamless Markdown Round-Tripping**: Synchronized with `@tiptap/markdown` for source editing and persistent storage.--### 2. π€ Inline AI Writing Assistant-- **Context-Aware In-Place Generation**: Triggered via `/` -> **β¨ AI Assistant (Context Prompt)**.-- **Surrounding Context Injection**: Gathers full-document metadata, title, and immediate before-and-after paragraph context to ensure perfect stylistic and structural continuity.-- **In-Place Shimmering Skeleton Loader**: Displays a shimmering progress skeleton directly at the cursor insertion point while generating.-- **Seamless Inline Replacement**: Replaces only that exact position with formatted Markdown without disturbing surrounding content.--### 3. πΌοΈ AI Image Generation (`gpt-image-2-text-to-image`)-- **Native MuAPI Image Generation**: Triggered via `/` -> **πΌοΈ Generate Image** or the `+ Insert` dropdown.-- **Aspect Ratio Control**: Select from `1:1` (Square), `16:9` (Widescreen), or `4:3` (Editorial).-- **β¨ Use Page Content (Smart Prompting)**: Automatically analyzes surrounding section context and calls MuAPI's text model to suggest an optimal, vivid image prompt.-- **Style Quick Chips**: One-click prompt modifiers (*Concept illustration*, *Architecture / Tech*, *Minimalist banner*).-- **Unbounded Polling**: Polling loop without premature timeouts that monitors task progress until completed or failed, then automatically embeds the high-resolution image into the document with responsive styling.--### 4. π§ Exclusively Powered by MuAPI Models-- **Text & Chat Intelligence**: Fast, high-capacity completions powered by `mimo-v2-6-flash-abliterated` and `glm-5-3-flash-abliterated`.-- **Image Generation**: Powered by `gpt-image-2-text-to-image`.-- **Zero Gemini Footprint**: Completely migrated away from Gemini models and endpoints.-- **Secure Architecture**: API keys reside strictly on the backend (`server/.env`) and are never exposed to client bundles or browser network tabs.--### 5. π₯ Persistent Team Spaces & Autonomous Dot Agents-- **Multi-Workspace Organization**: Organize projects, research, and roadmaps in dedicated team spaces.-- **Autonomous Dot Agents**: Specialized workers (*Synthesizer Dot*, *Copywriter Dot*, *Architect Dot*) to execute multi-step space directives.-- **Discussion Threads**: Multi-turn chat with direct `@Dot` mentions and living page links.-- **Meeting Audio Notes**: Audio recorder and transcript synthesizer that extracts action items directly into new living pages.-- **Supabase PostgreSQL Persistence**: Fully relational data model (`open_spaces`, `open_pages`, `open_agents`, `open_messages`, `open_meetings`) with automated migrations and seeding.+## π Key Features & Updates++### 1. π§ GPT-6 Series Intelligence (Native MuAPI Endpoints)+OpenSpaces is exclusively powered by MuAPI's **GPT-6 Series** models through direct streaming endpoints (`POST /api/v1/{model}/stream`):+- **β‘ GPT-6.1 Sol Light (`gpt-6-1-sol`)**: Fast, capable multimodal flagship supporting text & image inputs.+- **π§ GPT-6 Astra (`gpt-6-astra`)**: Deep reasoning model with multimodal vision capability for complex analysis.+- **β¨ GPT-6 Sol (`gpt-6-sol`)**: Balanced, high-precision general text generation.+- **π GPT-6 Luna (`gpt-6-luna`)**: Ultra-lightweight, high-speed drafting and conversational model.+- **Smart Vision Routing**: If an image is attached while a text-only model (`gpt-6-sol` or `gpt-6-luna`) is active, requests seamlessly route to `gpt-6-1-sol` so visual understanding succeeds without throwing schema errors.++### 2. π¬ Clean Prompt & History Architecture+- **Isolated User Prompt**: The `prompt` parameter receives strictly the current user prompt.+- **Contextual System Prompt**: Base system instructions plus the last 10 messages of conversation history are formatted and passed via `system_prompt`, maintaining clean token budgeting and model coherence.++### 3. π Native Media Upload & Hosted CDN Pipeline (`/api/upload_file`)+- **Direct MuAPI File Proxy**: Backend endpoint `POST /api/upload_file` receives multipart uploads, forwards them to `https://api.muapi.ai/api/v1/upload_file`, and returns persistent CDN links (`https://cdn.muapi.ai/...`).+- **No Blob Leaks**: Frontend uploads files immediately upon selection, displays a local thumbnail preview with a removal button, and enforces that only verified public CDN URLs are dispatched to AI models.+- **Send Guard**: The send button is disabled while an upload is in progress to prevent sending prematurely.++### 4. π¨ ChatGPT Spaces Native UI & Interaction Design+- **Input Card Layout**: Floating, rounded card design with embedded auto-resizing textarea, paperclip attachment button, and dynamic send pill button.+- **Custom Model Selector Dropdown**: Custom dropdown showcasing model icons, titles, and capability tags (`Fast & Capable`, `Deep Reasoning`, `Balanced`, `Ultra Light`).+- **Workspace Navigation & Sidebar**: Space switching, search, and page grouping matching modern ChatGPT Spaces.++### 5. π Living Document Versioning & Collaboration+- **Revision History Drawer**: Version history tracking page revisions with one-click restore and timestamps.+- **Space Members & Permissions**: Modal to manage space members, roles (`Owner`, `Admin`, `Member`, `Viewer`), and invite links.+- **Space Activity Logs**: Real-time auditing of document edits, agent executions, and membership updates.+- **Dual Storage Persistence**: In-memory store with automated fallback to Supabase PostgreSQL for seamless local development and production persistence.++### 6. βοΈ OpenDots Living Document Canvas (TipTap)+- **Rich Document Editor**: Powered by TipTap, supporting Markdown, multi-level headings, tables, task lists, and custom code blocks.+- **Slash Commands Menu (`/`)**: Compact keyboard-first menu to insert blocks, lists, and AI generators on the fly.+- **Inline AI Writing Assistant**: Context-aware in-place generation gathering surrounding document context with shimmering skeleton loader.+- **AI Image Generation**: Inline `/` -> **πΌοΈ Generate Image** powered by `gpt-image-2-text-to-image` with aspect ratio controls and smart prompt suggestion.++### 7. π Security & Key Isolation+- **Zero API Key Leakage**: API keys reside strictly on the backend (`server/.env`).+- **Dynamic Environment Loading**: Backend dynamically loads keys using `load_dotenv(override=True)` and `os.getenv("MUAPI_API_KEY")`.+- **Zero Client Footprint**: No sensitive credentials are ever embedded in frontend bundles or client network requests.---@@ -53,37 +60,45 @@ open-spaces/β β β βββ page.js # Core application dashboard & state orchestrationβ β β βββ globals.css # Design tokens, typography & markdown body stylingβ β βββ components/-β β βββ CanvasPage.js # Living canvas page with source mode and auto-save-β β βββ OpenSpacesApp.js # Primary router, space switcher, and layout manager-β β βββ Sidebar.js # Spaces navigation, search, and DB health indicator+β β βββ CanvasPage.js # Living canvas page with revision history drawer & source mode+β β βββ OpenSpacesApp.js # Primary router, space switcher, and state management+β β βββ HomeWorkView.js # ChatGPT-style card input, attachment preview & GPT-6 selector+β β βββ CustomDropdown.js# Custom accessible dropdown with capability tags+β β βββ SpaceSidebar.js # Spaces navigation, search, and space management+β β βββ SpaceLibrary.js # Living pages library & document browserβ β βββ SpaceChat.js # Space chat with agent mentions & living page citations+β β βββ ChatDrawer.js # Slide-out assistant chat drawer with multi-turn memoryβ β βββ editor/ # TipTap Rich Document Editorβ β βββ RichEditor.js # TipTap editor with toolbar and slash command triggerβ β βββ AiPromptView.js # Inline AI text generation node with local shimmering loaderβ β βββ AiImageView.js # Inline image generation node with aspect ratios & prompt helperβ β βββ slash-commands.js # Slash command definitions and fuzzy search-β β βββ markdown.js # TipTap extension registry & MarkdownManager-β β βββ editor.css # Editor toolbar, menus, popups, and image styles+β β βββ markdown.js # TipTap extension registry & MarkdownManagerβ βββ package.jsonββββ server/ # Backend (FastAPI, SQLAlchemy, Supabase PostgreSQL, MuAPI Gateway)βββ app/- β βββ main.py # FastAPI app setup, CORS, and WebSocket router- β βββ core/config.py # Configuration and MuAPI environment variables+ β βββ main.py # FastAPI app setup, CORS, and router registration+ β βββ core/+ β β βββ config.py # Settings and environment variables+ β β βββ auth.py # User authentication and token helpersβ βββ db/β β βββ session.py # SQLAlchemy engine with SSL pooling for Supabase- β β βββ models.py # Database schema definitions+ β β βββ models.py # Database models (Spaces, Pages, Revisions, Activity, Members)β βββ models/schemas.py # Pydantic request/response schemas+ β βββ services/+ β β βββ space_store.py # Dual-storage layer (Supabase + In-Memory Fallback)β βββ api/routers/- β βββ chat.py # Chat completions router powered by MuAPI text models+ β βββ chat.py # GPT-6 series chat completions router (/api/v1/{model}/stream)+ β βββ files.py # File & image upload router proxying to MuAPI CDNβ βββ images.py # gpt-image-2 generation & prompt suggestion via MuAPI- β βββ spaces.py # Spaces CRUD & chat endpoints- β βββ pages.py # Living pages CRUD endpoints+ β βββ spaces.py # Spaces CRUD, members, and activity log endpoints+ β βββ pages.py # Living pages CRUD and revision history endpointsβ βββ agents.py # Dot agent execution endpointsβ βββ meetings.py # Meeting audio notes & intelligenceβββ run.py # Server runner on port 8000βββ requirements.txt- βββ .env # Server environment variables & MuAPI key+ βββ .env # Server environment variables & MUAPI_API_KEY```---@@ -102,7 +117,6 @@ DATABASE_URL=postgresql://postgres.xxx:[email protected]DIRECT_URL=postgresql://postgres.xxx:[email protected]:6543/postgres# MuAPI Configuration-DEFAULT_MODEL=mimo-v2-6-flash-abliteratedMUAPI_API_KEY=your_muapi_api_key_here```@@ -129,25 +143,34 @@ npm run dev----## π§ͺ Testing MuAPI Endpoints+## π§ͺ Testing Endpoints-### Test Text / Chat Completions+### 1. Test GPT-6 Series Chat Completions```powershellInvoke-RestMethod -Uri "http://localhost:8000/api/chat" -Method POST `-ContentType "application/json" `- -Body '{"prompt": "Summarize vector search in 2 sentences"}'+ -Body '{"model": "gpt-6-1-sol", "prompt": "Summarize vector search in 2 sentences"}'```-### Test Context-Aware Image Prompt Suggestion+### 2. Test Multimodal Image Analysis```powershell-Invoke-RestMethod -Uri "http://localhost:8000/api/images/suggest-prompt" -Method POST `+Invoke-RestMethod -Uri "http://localhost:8000/api/chat" -Method POST `-ContentType "application/json" `- -Body '{"context": "Deep learning transformer attention mechanisms", "title": "AI Architectures"}'+ -Body '{"model": "gpt-6-1-sol", "prompt": "Describe this image", "image_url": "https://cdn.muapi.ai/outputs/sample.png"}'```-### Test Image Generation (Polls MuAPI until Completed)+### 3. Test Direct Media Upload```powershell-Invoke-RestMethod -Uri "http://localhost:8000/api/images/generate" -Method POST `- -ContentType "application/json" `- -Body '{"prompt": "A modern glass architecture building at dusk, 8k", "aspect_ratio": "16:9"}'+$form = @{ file = Get-Item "sample.jpg" }+Invoke-RestMethod -Uri "http://localhost:8000/api/upload_file" -Method POST -Form $form```++---++## π Recent Changelog+- **GPT-6 Series Integration**: Migrated chat backend to native MuAPI endpoints (`POST /api/v1/{model}/stream`) for `gpt-6-1-sol`, `gpt-6-astra`, `gpt-6-sol`, and `gpt-6-luna`.+- **System Prompt & History Refactor**: Formatted last 10 messages chat history into `system_prompt` while maintaining purely user input in `prompt`.+- **Media Upload Pipeline**: Implemented `POST /api/upload_file` forwarding to `https://api.muapi.ai/api/v1/upload_file` returning CDN URLs.+- **ChatGPT Native Input Card**: Rebuilt prompt bar with attachment preview thumbnail, remove button, and upload guard.+- **Document History & Collaboration**: Added revision history drawer, activity logging, and space membership management.+- **API Key Security**: Purged all hardcoded keys and enforced dynamic `.env` loading.diff --git a/client/src/components/CanvasPage.js b/client/src/components/CanvasPage.jsindex b7ad203..86ec90b 100644--- a/client/src/components/CanvasPage.js+++ b/client/src/components/CanvasPage.js@@ -6,18 +6,18 @@ import { inspectMarkdown } from "./editor/markdown";import {WindowIcon,SparklesIcon,+ ClockIcon,+ CloseIcon,} from "./Icons";-import { LuFileCode2 } from "react-icons/lu";--const DEFAULT_STARTER_TEMPLATE = `> Pages are a place for you to write, build, and collaborate with ChatGPT and your teammates. Use this page as your playground to learn the basics β and have fun!--### Getting started--- [ ] **Play with this page.** Type \`/\` to add headings, images, checklists, tables, and more. Try it out below!--I'm a curious, collaborative person who enjoys turning ideas into meaningful projects, learning from the people around me, and finding thoughtful ways to help others.--- [ ] Try adding a heading, checklist, or callout to this page using the \`/\` menu.`;+import {+ LuFileCode2,+ LuTriangleAlert,+ LuRotateCcw,+ LuCopy,+ LuCheck,+ LuHistory,+} from "react-icons/lu";+import CustomDropdown from "./CustomDropdown";const EMOJI_OPTIONS = ["π", "π", "π‘", "π", "π", "π", "π", "π―", "β‘", "π€", "π", "π»"];@@ -27,15 +27,28 @@ export default function CanvasPage({onStatusChange,onTriggerAI,saveTrigger,+ historyOpen = false,+ onCloseHistory,+ onRestoreRevision,}) {const [title, setTitle] = useState(page?.title || "Untitled page");const [icon, setIcon] = useState(page?.icon || "π");const [content, setContent] = useState(page?.content || "");+ const [pageStatus, setPageStatus] = useState(page?.status || "draft");const [sourceMode, setSourceMode] = useState(false);const [showEmojiPicker, setShowEmojiPicker] = useState(false);const [promptInput, setPromptInput] = useState("");const [notice, setNotice] = useState("");+ // Conflict and Local Draft states+ const [conflictInfo, setConflictInfo] = useState(null);+ const [localDraftAlert, setLocalDraftAlert] = useState(null);+ const [copiedDraft, setCopiedDraft] = useState(false);++ // Revision History state+ const [revisions, setRevisions] = useState([]);+ const [isLoadingRevisions, setIsLoadingRevisions] = useState(false);+const draftRef = useRef({id: page?.id,title: page?.title || "Untitled page",@@ -50,6 +63,29 @@ export default function CanvasPage({const saveQueuedRef = useRef(false);const prevSaveTriggerRef = useRef(saveTrigger);+ // Helper to persist draft locally+ const persistLocalDraft = (draftObj) => {+ if (!draftObj?.id) return;+ try {+ localStorage.setItem(+ `openspaces_draft_${draftObj.id}`,+ JSON.stringify({+ title: draftObj.title,+ icon: draftObj.icon,+ content: draftObj.content,+ timestamp: Date.now(),+ })+ );+ } catch (_) {}+ };++ const clearLocalDraft = (pageId) => {+ if (!pageId) return;+ try {+ localStorage.removeItem(`openspaces_draft_${pageId}`);+ } catch (_) {}+ };+// Sync draft state whenever page prop changesuseEffect(() => {if (!page) return;@@ -60,14 +96,13 @@ export default function CanvasPage({const initialTitle = page.title || "Untitled page";const initialIcon = page.icon || "π";- const rawContent =- page.content !== undefined && page.content !== null && page.content !== ""- ? page.content- : DEFAULT_STARTER_TEMPLATE;+ const rawContent = page.content ?? "";setTitle(initialTitle);setIcon(initialIcon);setContent(rawContent);+ setPageStatus(page.status || "draft");+ setConflictInfo(null);draftRef.current = {id: page.id,@@ -77,14 +112,58 @@ export default function CanvasPage({isDirty: false,};+ // Check for an unsaved local draft for this page+ try {+ const stored = localStorage.getItem(`openspaces_draft_${page.id}`);+ if (stored) {+ const parsed = JSON.parse(stored);+ if (+ parsed &&+ (parsed.content !== rawContent || parsed.title !== initialTitle)+ ) {+ setLocalDraftAlert(parsed);+ } else {+ setLocalDraftAlert(null);+ }+ } else {+ setLocalDraftAlert(null);+ }+ } catch (_) {+ setLocalDraftAlert(null);+ }+if (onStatusChange) {onStatusChange("Saved");}}, [page?.id]);- // Flush save function+ // Fetch revisions when history drawer is opened+ useEffect(() => {+ if (!historyOpen || !page?.id || !page?.space_id) return;+ let isMounted = true;+ setIsLoadingRevisions(true);+ fetch(`http://localhost:8000/api/spaces/${page.space_id}/pages/${page.id}/revisions`, {+ headers: { "X-User-Id": "usr-1" },+ })+ .then((res) => (res.ok ? res.json() : []))+ .then((data) => {+ if (isMounted) {+ setRevisions(data);+ setIsLoadingRevisions(false);+ }+ })+ .catch((err) => {+ console.error("Error loading page revisions:", err);+ if (isMounted) setIsLoadingRevisions(false);+ });+ return () => {+ isMounted = false;+ };+ }, [historyOpen, page?.id, page?.space_id, page?.version]);++ // Flush save function with optimistic concurrencyconst flushSave = useCallback(- async (overrideDraft = null) => {+ async (overrideDraft = null, forcedRevision = null) => {const current = overrideDraft || draftRef.current;if (!current.id || !current.isDirty) return;@@ -109,13 +188,30 @@ export default function CanvasPage({};try {- const updated = await onUpdatePage(snapshot.id, {+ const payload = {title: snapshot.title,icon: snapshot.icon,content: snapshot.content,- });+ };+ if (forcedRevision !== null) {+ payload.expected_revision = forcedRevision;+ } else if (page?.version !== undefined) {+ payload.expected_revision = page.version;+ }++ const result = await onUpdatePage(snapshot.id, payload);++ if (result && result.conflict) {+ // 409 Conflict occurred+ setConflictInfo(result.detail);+ if (onStatusChange) onStatusChange("Conflict");+ return;+ }++ if (result) {+ setConflictInfo(null);+ clearLocalDraft(snapshot.id);- if (updated) {if (draftRef.current.content === snapshot.content &&draftRef.current.title === snapshot.title &&@@ -147,7 +243,7 @@ export default function CanvasPage({}}},- [onUpdatePage, onStatusChange]+ [onUpdatePage, onStatusChange, page?.version]);// Debounced idle hold: Hold changes on "Unsaved changes" until user stops for 1.5s@@ -158,6 +254,7 @@ export default function CanvasPage({...newDraft,isDirty: true,};+ persistLocalDraft(draftRef.current);if (onStatusChange) onStatusChange("Unsaved changes");// Reset the hold timer on every change@@ -229,169 +326,407 @@ export default function CanvasPage({scheduleIdleAutosave({ content: newContent });};+ const handleStatusChange = (newStatus) => {+ setPageStatus(newStatus);+ if (onUpdatePage && page?.id) {+ onUpdatePage(page.id, { status: newStatus });+ }+ };+const safety = inspectMarkdown(content);return (- <div className="flex-1 overflow-y-auto bg-white dark:bg-[#141416] text-zinc-900 dark:text-zinc-100 transition-colors duration-150">- <div className="max-w-3xl mx-auto px-10 py-10">- {/* Top Control Bar: Mode Toggle & Emoji Picker */}- <div className="flex items-center justify-between mb-4 select-none">- {/* Emoji Page Icon */}- <div className="relative">- <button- type="button"- onClick={(e) => {- e.stopPropagation();- setShowEmojiPicker(!showEmojiPicker);- }}- className="text-4xl p-1 rounded-xl hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors cursor-pointer select-none"- title="Click to change icon"- >- {icon || "π"}- </button>-- {showEmojiPicker && (- <div- onClick={(e) => e.stopPropagation()}- className="absolute left-0 top-14 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-xl shadow-xl p-2 z-40 flex flex-wrap gap-2 w-56 animate-in fade-in zoom-in-95 duration-100"+ <div className="flex-1 flex overflow-hidden">+ {/* Main Canvas Area */}+ <div className="flex-1 overflow-y-auto bg-white dark:bg-[#141416] text-zinc-900 dark:text-zinc-100 transition-colors duration-150">+ <div className="max-w-3xl mx-auto px-10 py-10">+ {/* Top Control Bar: Mode Toggle, Status Selector & Emoji Picker */}+ <div className="flex items-center justify-between mb-4 select-none">+ {/* Emoji Page Icon */}+ <div className="relative">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setShowEmojiPicker(!showEmojiPicker);+ }}+ className="text-4xl p-1 rounded-xl hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors cursor-pointer select-none"+ title="Click to change icon">- {EMOJI_OPTIONS.map((e) => (- <button- key={e}- type="button"- onClick={() => handleIconChange(e)}- className="w-9 h-9 flex items-center justify-center text-xl rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-700 cursor-pointer transition-transform hover:scale-110"- >- {e}- </button>- ))}- </div>- )}- </div>-- {/* Mode Switcher Button (Visual Editor vs Markdown Source) */}- <button- type="button"- onClick={() => {- if (!sourceMode && !safety.supported) {- setNotice(safety.reason || "This document needs Markdown source mode.");- }- setSourceMode(!sourceMode);- }}- className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer transition-colors border ${- sourceMode- ? "bg-indigo-50 dark:bg-indigo-950/40 text-indigo-600 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800"- : "bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-300 border-zinc-200 dark:border-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-700"- }`}- >- <WindowIcon className="w-3.5 h-3.5" />- <span>{sourceMode ? "Visual Editor" : "Markdown Source"}</span>- </button>- </div>+ {icon || "π"}+ </button>++ {showEmojiPicker && (+ <div+ onClick={(e) => e.stopPropagation()}+ className="absolute left-0 top-14 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-xl shadow-xl p-2 z-40 flex flex-wrap gap-2 w-56 animate-in fade-in zoom-in-95 duration-100"+ >+ {EMOJI_OPTIONS.map((e) => (+ <button+ key={e}+ type="button"+ onClick={() => handleIconChange(e)}+ className="w-9 h-9 flex items-center justify-center text-xl rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-700 cursor-pointer transition-transform hover:scale-110"+ >+ {e}+ </button>+ ))}+ </div>+ )}+ </div>- {/* Notice alert if any */}- {notice && (- <div className="mb-4 p-3 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 text-xs text-amber-800 dark:text-amber-200 flex items-center justify-between">- <span>{notice}</span>- <button- type="button"- onClick={() => setNotice("")}- className="text-amber-600 dark:text-amber-400 font-bold ml-2 cursor-pointer"- >- Dismiss- </button>+ {/* Right Tools: Status Dropdown & Mode Switcher */}+ <div className="flex items-center gap-2">+ <CustomDropdown+ value={pageStatus}+ onChange={handleStatusChange}+ options={[+ { label: "Draft", value: "draft", icon: "π" },+ { label: "In Review", value: "in_review", icon: "π" },+ { label: "Published", value: "published", icon: "π" },+ ]}+ size="xs"+ buttonClassName="bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 rounded-lg py-1 px-2.5 text-xs border-zinc-200 dark:border-zinc-700"+ />++ {/* Mode Switcher Button (Visual Editor vs Markdown Source) */}+ <button+ type="button"+ onClick={() => {+ if (!sourceMode && !safety.supported) {+ setNotice(safety.reason || "This document needs Markdown source mode.");+ }+ setSourceMode(!sourceMode);+ }}+ className={`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-medium cursor-pointer transition-colors border ${+ sourceMode+ ? "bg-indigo-50 dark:bg-indigo-950/40 text-indigo-600 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800"+ : "bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-300 border-zinc-200 dark:border-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-700"+ }`}+ >+ <WindowIcon className="w-3.5 h-3.5" />+ <span>{sourceMode ? "Visual Editor" : "Markdown Source"}</span>+ </button>+ </div></div>- )}-- {/* Page Title Input matching OpenDots (Image 2) */}- <input- type="text"- value={title}- onChange={(e) => handleTitleChange(e.target.value)}- onBlur={() => flushSave()}- placeholder="Untitled page"- maxLength={160}- className="document-title w-full text-4xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100 bg-transparent focus:outline-none placeholder-zinc-300 dark:placeholder-zinc-600 mb-6"- />-- {/* Document Body */}- {sourceMode ? (- <div className="space-y-3">- <div className="flex items-center gap-2 text-xs font-medium text-zinc-500 dark:text-zinc-400 pb-1">- <LuFileCode2 size={16} />- <span>Markdown source</span>++ {/* Local Draft Recovery Alert Banner */}+ {localDraftAlert && (+ <div className="mb-6 p-3.5 rounded-xl bg-amber-50 dark:bg-amber-950/40 border border-amber-300 dark:border-amber-700 text-amber-900 dark:text-amber-200 flex items-center justify-between animate-in fade-in slide-in-from-top-1 shadow-2xs">+ <div className="flex items-center gap-2 text-xs">+ <span className="font-semibold text-amber-700 dark:text-amber-300">Unsaved Local Draft:</span>+ <span>You have an uncommitted local version from {new Date(localDraftAlert.timestamp || Date.now()).toLocaleTimeString()}.</span>+ </div>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => {+ setTitle(localDraftAlert.title || "Untitled page");+ setIcon(localDraftAlert.icon || "π");+ setContent(localDraftAlert.content || "");+ draftRef.current = {+ id: page.id,+ title: localDraftAlert.title || "Untitled page",+ icon: localDraftAlert.icon || "π",+ content: localDraftAlert.content || "",+ isDirty: true,+ };+ setLocalDraftAlert(null);+ if (onStatusChange) onStatusChange("Unsaved changes");+ }}+ className="px-2.5 py-1 rounded-md bg-amber-600 hover:bg-amber-700 text-white text-xs font-medium transition-colors cursor-pointer"+ >+ Restore Draft+ </button>+ <button+ type="button"+ onClick={() => {+ clearLocalDraft(page.id);+ setLocalDraftAlert(null);+ }}+ className="px-2.5 py-1 rounded-md hover:bg-amber-100 dark:hover:bg-amber-900/50 text-xs text-amber-800 dark:text-amber-300 transition-colors cursor-pointer"+ >+ Discard+ </button>+ </div></div>- <textarea- rows={20}- spellCheck={false}- value={content}- onChange={(e) => handleContentChange(e.target.value)}- onBlur={() => flushSave()}- placeholder="Write your document in Markdown..."- className="w-full bg-zinc-50/50 dark:bg-zinc-900/50 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 text-xs font-mono text-zinc-800 dark:text-zinc-200 leading-relaxed resize-y focus:outline-none focus:border-zinc-400 transition-colors"- />- <div className="text-[11px] text-zinc-400 flex justify-between">- <span>{content.length} characters</span>- <span>{content.split(/\s+/).filter(Boolean).length} words</span>+ )}++ {/* Conflict Resolution Alert Banner */}+ {conflictInfo && (+ <div className="mb-6 p-4 rounded-xl bg-rose-50 dark:bg-rose-950/40 border border-rose-300 dark:border-rose-800 text-rose-900 dark:text-rose-200 animate-in fade-in slide-in-from-top-2 shadow-2xs">+ <div className="flex items-start gap-3">+ <LuTriangleAlert className="w-5 h-5 text-rose-600 dark:text-rose-400 shrink-0 mt-0.5" />+ <div className="flex-1 min-w-0">+ <h4 className="font-semibold text-sm text-rose-900 dark:text-rose-100">+ Edit Conflict Detected (Server is at revision v{conflictInfo.current_version})+ </h4>+ <p className="text-xs text-rose-700 dark:text-rose-300 mt-1">+ Another edit was saved while you were working. Your unsaved changes are preserved safely in your editor. Choose how you would like to proceed:+ </p>+ <div className="flex flex-wrap items-center gap-2 mt-3">+ <button+ type="button"+ onClick={() => {+ flushSave(draftRef.current, conflictInfo.current_version);+ }}+ className="px-3 py-1.5 rounded-lg bg-rose-600 hover:bg-rose-700 text-white text-xs font-medium transition-colors shadow-xs cursor-pointer"+ >+ Keep My Draft & Overwrite+ </button>+ <button+ type="button"+ onClick={() => {+ const serverP = conflictInfo.current_page;+ if (serverP) {+ setTitle(serverP.title || "Untitled page");+ setIcon(serverP.icon || "π");+ setContent(serverP.content || "");+ draftRef.current = {+ id: serverP.id,+ title: serverP.title || "Untitled page",+ icon: serverP.icon || "π",+ content: serverP.content || "",+ isDirty: false,+ };+ }+ clearLocalDraft(page.id);+ setConflictInfo(null);+ if (onStatusChange) onStatusChange("Saved");+ }}+ className="px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-800 hover:bg-zinc-100 dark:hover:bg-zinc-700 border border-rose-300 dark:border-zinc-600 text-xs font-medium text-zinc-800 dark:text-zinc-200 transition-colors cursor-pointer"+ >+ Discard & Load Server Version+ </button>+ <button+ type="button"+ onClick={() => {+ if (typeof navigator !== "undefined" && navigator.clipboard) {+ navigator.clipboard.writeText(content);+ setCopiedDraft(true);+ setTimeout(() => setCopiedDraft(false), 2000);+ }+ }}+ className="px-3 py-1.5 rounded-lg hover:bg-rose-100/60 dark:hover:bg-rose-900/40 text-xs font-medium text-rose-800 dark:text-rose-300 transition-colors flex items-center gap-1.5 cursor-pointer"+ >+ {copiedDraft ? <LuCheck className="w-3.5 h-3.5 text-emerald-600" /> : <LuCopy className="w-3.5 h-3.5" />}+ <span>{copiedDraft ? "Copied to clipboard!" : "Copy My Draft"}</span>+ </button>+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Notice alert if any */}+ {notice && (+ <div className="mb-4 p-3 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 text-xs text-amber-800 dark:text-amber-200 flex items-center justify-between">+ <span>{notice}</span>+ <button+ type="button"+ onClick={() => setNotice("")}+ className="text-amber-600 dark:text-amber-400 font-bold ml-2 cursor-pointer"+ >+ Dismiss+ </button>+ </div>+ )}++ {/* Page Title Input */}+ <input+ type="text"+ value={title}+ onChange={(e) => handleTitleChange(e.target.value)}+ onBlur={() => flushSave()}+ placeholder="Untitled page"+ maxLength={160}+ className="document-title w-full text-4xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100 bg-transparent focus:outline-none placeholder-zinc-300 dark:placeholder-zinc-600 mb-6"+ />++ {/* Document Body */}+ {sourceMode ? (+ <div className="space-y-3">+ <div className="flex items-center gap-2 text-xs font-medium text-zinc-500 dark:text-zinc-400 pb-1">+ <LuFileCode2 size={16} />+ <span>Markdown source</span>+ </div>+ <textarea+ rows={20}+ spellCheck={false}+ value={content}+ onChange={(e) => handleContentChange(e.target.value)}+ onBlur={() => flushSave()}+ placeholder="Write your document in Markdown..."+ className="w-full bg-zinc-50/50 dark:bg-zinc-900/50 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 text-xs font-mono text-zinc-800 dark:text-zinc-200 leading-relaxed resize-y focus:outline-none focus:border-zinc-400 transition-colors"+ />+ <div className="text-[11px] text-zinc-400 flex justify-between">+ <span>{content.length} characters</span>+ <span>{content.split(/\s+/).filter(Boolean).length} words</span>+ </div>+ </div>+ ) : (+ /* Visual Document Editor */+ <div className="document-editor-wrapper">+ <RichEditor+ value={content}+ onChange={handleContentChange}+ onNotice={(msg) => setNotice(msg)}+ pageTitle={title}+ pageId={page?.id}+ />+ </div>+ )}++ {/* Inline ChatGPT / Dot Directive Box */}+ <div className="mt-12 p-4 rounded-xl bg-zinc-50 dark:bg-[#18181e] border border-zinc-200 dark:border-zinc-800 space-y-2 select-none">+ <div className="text-xs text-zinc-700 dark:text-zinc-300 leading-relaxed">+ <span className="font-semibold text-zinc-900 dark:text-zinc-100">+ Work with ChatGPT.+ </span>{" "}+ Type{" "}+ <span className="bg-indigo-50 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-300 font-medium px-1.5 py-0.5 rounded text-[11px] border border-indigo-200 dark:border-indigo-800">+ @ChatGPT+ </span>+ , followed by your request, and ChatGPT will jump in to help with whatever you need.</div>- </div>- ) : (- /* Visual Document Editor matching OpenDots (Image 2) */- <div className="document-editor-wrapper">- <RichEditor- value={content}- onChange={handleContentChange}- onNotice={(msg) => setNotice(msg)}- pageTitle={title}- pageId={page?.id}- />- </div>- )}-- {/* Inline ChatGPT / Dot Directive Box */}- <div className="mt-12 p-4 rounded-xl bg-zinc-50 dark:bg-[#18181e] border border-zinc-200 dark:border-zinc-800 space-y-2 select-none">- <div className="text-xs text-zinc-700 dark:text-zinc-300 leading-relaxed">- <span className="font-semibold text-zinc-900 dark:text-zinc-100">- Work with ChatGPT.- </span>{" "}- Type{" "}- <span className="bg-indigo-50 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-300 font-medium px-1.5 py-0.5 rounded text-[11px] border border-indigo-200 dark:border-indigo-800">- @ChatGPT- </span>- , followed by your request, and ChatGPT will jump in to help with whatever you need.- </div>- <div className="flex items-center gap-2 pt-1">- <span className="text-zinc-400 text-xs">β³</span>- <input- type="text"- placeholder="do some research about this topic or ask Dot agent..."- value={promptInput}- onChange={(e) => setPromptInput(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && promptInput.trim()) {- onTriggerAI && onTriggerAI(promptInput.trim());- setPromptInput("");- }- }}- className="flex-1 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-lg px-3 py-1.5 text-xs text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:border-indigo-500 shadow-2xs"- />- <button- type="button"- onClick={() => {- if (promptInput.trim()) {- onTriggerAI && onTriggerAI(promptInput.trim());- setPromptInput("");- }- }}- className="p-1.5 rounded-lg bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 hover:opacity-90 transition-opacity cursor-pointer"- title="Run directive"- >- <SparklesIcon className="w-3.5 h-3.5" />- </button>+ <div className="flex items-center gap-2 pt-1">+ <span className="text-zinc-400 text-xs">β³</span>+ <input+ type="text"+ placeholder="do some research about this topic or ask Dot agent..."+ value={promptInput}+ onChange={(e) => setPromptInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && promptInput.trim()) {+ onTriggerAI && onTriggerAI(promptInput.trim());+ setPromptInput("");+ }+ }}+ className="flex-1 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-lg px-3 py-1.5 text-xs text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:border-indigo-500 shadow-2xs"+ />+ <button+ type="button"+ onClick={() => {+ if (promptInput.trim()) {+ onTriggerAI && onTriggerAI(promptInput.trim());+ setPromptInput("");+ }+ }}+ className="p-1.5 rounded-lg bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 hover:opacity-90 transition-opacity cursor-pointer"+ title="Run directive"+ >+ <SparklesIcon className="w-3.5 h-3.5" />+ </button>+ </div></div></div></div>++ {/* Revisions History Side Panel */}+ {historyOpen && (+ <aside className="w-80 border-l border-zinc-200 dark:border-zinc-800 bg-[#fafafa] dark:bg-[#18181b] flex flex-col h-full shadow-lg z-30 animate-in slide-in-from-right duration-200 select-none">+ <div className="p-4 border-b border-zinc-200 dark:border-zinc-800 flex items-center justify-between">+ <div className="flex items-center gap-2">+ <LuHistory className="w-4 h-4 text-indigo-500" />+ <span className="font-semibold text-sm text-zinc-900 dark:text-zinc-100">Revision History</span>+ </div>+ {onCloseHistory && (+ <button+ type="button"+ onClick={onCloseHistory}+ className="p-1 rounded-lg hover:bg-zinc-200 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 cursor-pointer"+ title="Close revision history"+ >+ <CloseIcon className="w-4 h-4" />+ </button>+ )}+ </div>++ <div className="flex-1 overflow-y-auto p-3 space-y-3">+ {isLoadingRevisions ? (+ <div className="flex flex-col items-center justify-center p-8 text-zinc-400 gap-2">+ <div className="w-5 h-5 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />+ <span className="text-xs">Loading revisions...</span>+ </div>+ ) : revisions.length === 0 ? (+ <div className="p-6 text-center text-xs text-zinc-400">+ No previous snapshots available yet.+ </div>+ ) : (+ revisions.map((rev) => {+ const isCurrent = rev.version === page?.version;+ return (+ <div+ key={rev.id}+ className={`p-3 rounded-xl border transition-all ${+ isCurrent+ ? "bg-indigo-50/70 dark:bg-indigo-950/30 border-indigo-200 dark:border-indigo-800"+ : "bg-white dark:bg-zinc-900/80 border-zinc-200/80 dark:border-zinc-800 hover:border-zinc-300 dark:hover:border-zinc-700"+ }`}+ >+ <div className="flex items-center justify-between mb-1.5">+ <span+ className={`text-[10px] uppercase font-bold tracking-wider px-1.5 py-0.5 rounded ${+ isCurrent+ ? "bg-indigo-600 text-white"+ : "bg-zinc-200 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300"+ }`}+ >+ v{rev.version} {isCurrent && "(Current)"}+ </span>+ <span className="text-[11px] text-zinc-400">+ {new Date(rev.created_at).toLocaleString([], {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ })}+ </span>+ </div>++ <div className="text-xs font-medium text-zinc-800 dark:text-zinc-200 truncate mb-1">+ {rev.title || "Untitled page"}+ </div>++ <div className="text-[11px] text-zinc-500 dark:text-zinc-400 mb-2 flex items-center gap-1">+ <span>By {rev.author || "You"}</span>+ <span>β’</span>+ <span>{(rev.content || "").length} chars</span>+ </div>++ {!isCurrent && onRestoreRevision && (+ <button+ type="button"+ onClick={async () => {+ const restored = await onRestoreRevision(page.id, rev.version);+ if (restored) {+ setTitle(restored.title);+ setContent(restored.content || "");+ setIcon(restored.icon || "π");+ draftRef.current = {+ id: restored.id,+ title: restored.title,+ icon: restored.icon || "π",+ content: restored.content || "",+ isDirty: false,+ };+ if (onCloseHistory) onCloseHistory();+ }+ }}+ className="w-full flex items-center justify-center gap-1.5 py-1.5 px-3 rounded-lg bg-zinc-100 hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700 text-zinc-800 dark:text-zinc-200 text-xs font-medium transition-colors cursor-pointer"+ >+ <LuRotateCcw className="w-3 h-3 text-indigo-500" />+ <span>Restore this version</span>+ </button>+ )}+ </div>+ );+ })+ )}+ </div>+ </aside>+ )}</div>);}diff --git a/client/src/components/ChatDrawer.js b/client/src/components/ChatDrawer.jsindex 2ebe8f4..68ca03c 100644--- a/client/src/components/ChatDrawer.js+++ b/client/src/components/ChatDrawer.js@@ -1,8 +1,25 @@"use client";-import React, { useState } from "react";-import { SendIcon, SparklesIcon, CloseIcon, PageIcon, BotIcon } from "./Icons";+import React, { useState, useEffect } from "react";+import {+ SendIcon,+ SparklesIcon,+ CloseIcon,+ PageIcon,+ ChatIcon,+ CheckIcon,+ TrashIcon,+} from "./Icons";import MarkdownRenderer from "./MarkdownRenderer";+import CustomDropdown from "./CustomDropdown";++const API_BASE = "http://localhost:8000/api";++const COMMENT_FILTER_OPTIONS = [+ { label: "All Comments", value: "all" },+ { label: "Unresolved", value: "unresolved" },+ { label: "Resolved", value: "resolved" },+];export default function ChatDrawer({isOpen,@@ -11,98 +28,360 @@ export default function ChatDrawer({onSendMessage,agents = [],activePageTitle,+ activePageId,+ spaceId,}) {+ const [activeTab, setActiveTab] = useState("comments"); // 'comments' | 'ai'const [inputText, setInputText] = useState("");+ const [commentText, setCommentText] = useState("");+ const [comments, setComments] = useState([]);+ const [isLoadingComments, setIsLoadingComments] = useState(false);+ const [commentFilter, setCommentFilter] = useState("all");+ const [selectedAgentName, setSelectedAgentName] = useState("");++ // Fetch comments whenever drawer is opened on a page+ const fetchComments = async () => {+ if (!spaceId || !activePageId) return;+ setIsLoadingComments(true);+ try {+ const res = await fetch(`${API_BASE}/spaces/${spaceId}/pages/${activePageId}/comments`, {+ headers: { "X-User-Id": "usr-1" },+ });+ if (res.ok) {+ const data = await res.json();+ setComments(data);+ }+ } catch (err) {+ console.error("Error loading comments:", err);+ } finally {+ setIsLoadingComments(false);+ }+ };++ useEffect(() => {+ if (isOpen && activePageId && spaceId) {+ fetchComments();+ }+ }, [isOpen, activePageId, spaceId]);if (!isOpen) return null;- const handleSubmit = (e) => {+ const handleAiSubmit = (e) => {e.preventDefault();if (!inputText.trim()) return;- onSendMessage({- content: inputText.trim(),- sender_type: "user",- sender_name: "You",- });+ let textToSend = inputText.trim();+ if (selectedAgentName) {+ textToSend = `@${selectedAgentName}: ${textToSend}`;+ }++ if (onSendMessage) {+ onSendMessage({+ content: textToSend,+ sender_type: "user",+ sender_name: "You",+ });+ }setInputText("");};+ const handleCommentSubmit = async (e) => {+ e.preventDefault();+ if (!commentText.trim() || !spaceId || !activePageId) return;++ try {+ const res = await fetch(`${API_BASE}/spaces/${spaceId}/pages/${activePageId}/comments`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-User-Id": "usr-1",+ },+ body: JSON.stringify({ content: commentText.trim() }),+ });+ if (res.ok) {+ const newCmt = await res.json();+ setComments((prev) => [...prev, newCmt]);+ setCommentText("");+ }+ } catch (err) {+ console.error("Error submitting comment:", err);+ }+ };++ const handleToggleResolve = async (commentId, currentResolved) => {+ try {+ const res = await fetch(+ `${API_BASE}/spaces/${spaceId}/pages/${activePageId}/comments/${commentId}`,+ {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ "X-User-Id": "usr-1",+ },+ body: JSON.stringify({ resolved: !currentResolved }),+ }+ );+ if (res.ok) {+ setComments((prev) =>+ prev.map((c) => (c.id === commentId ? { ...c, resolved: !currentResolved } : c))+ );+ }+ } catch (err) {+ console.error("Error resolving comment:", err);+ }+ };++ const handleDeleteComment = async (commentId) => {+ try {+ const res = await fetch(+ `${API_BASE}/spaces/${spaceId}/pages/${activePageId}/comments/${commentId}`,+ {+ method: "DELETE",+ headers: { "X-User-Id": "usr-1" },+ }+ );+ if (res.ok) {+ setComments((prev) => prev.filter((c) => c.id !== commentId));+ }+ } catch (err) {+ console.error("Error deleting comment:", err);+ }+ };++ const filteredComments = comments.filter((c) => {+ if (commentFilter === "unresolved") return !c.resolved;+ if (commentFilter === "resolved") return !!c.resolved;+ return true;+ });+return (- <div className="w-80 border-l border-zinc-200/80 dark:border-zinc-800/80 bg-[#fbfbfa] dark:bg-[#18181b] flex flex-col h-full select-none text-xs transition-colors duration-150">- {/* Header */}+ <div className="w-80 border-l border-zinc-200/80 dark:border-zinc-800/80 bg-[#fbfbfa] dark:bg-[#18181b] flex flex-col h-full select-none text-xs transition-colors duration-150 shadow-sm">+ {/* Header with Tabs */}<div className="p-3 border-b border-zinc-200/80 dark:border-zinc-800/80 flex items-center justify-between">- <div className="flex items-center gap-1.5 font-medium text-zinc-900 dark:text-zinc-100">- <SparklesIcon className="w-4 h-4 text-indigo-500" />- <span>Discussion & Dots</span>+ <div className="flex items-center gap-1 bg-zinc-100 dark:bg-zinc-800/90 p-0.5 rounded-lg border border-zinc-200/60 dark:border-zinc-700/60">+ <button+ type="button"+ onClick={() => setActiveTab("comments")}+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium transition-colors cursor-pointer ${+ activeTab === "comments"+ ? "bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 shadow-2xs"+ : "text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200"+ }`}+ >+ <ChatIcon className="w-3.5 h-3.5 text-indigo-500" />+ <span>Comments ({comments.length})</span>+ </button>+ <button+ type="button"+ onClick={() => setActiveTab("ai")}+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium transition-colors cursor-pointer ${+ activeTab === "ai"+ ? "bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 shadow-2xs"+ : "text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200"+ }`}+ >+ <SparklesIcon className="w-3.5 h-3.5 text-indigo-500" />+ <span>AI Thread</span>+ </button></div>+<buttononClick={onClose}- className="p-1 rounded hover:bg-zinc-200/60 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200"+ className="p-1 rounded hover:bg-zinc-200/60 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 cursor-pointer"><CloseIcon className="w-3.5 h-3.5" /></button></div>- {/* Context Banner */}- {activePageTitle && (- <div className="px-3 py-1.5 bg-zinc-100 dark:bg-zinc-900/60 border-b border-zinc-200/60 dark:border-zinc-800/60 flex items-center gap-1.5 text-[11px] text-zinc-500">+ {/* Context Banner & Comments Filter */}+ <div className="px-3 py-1.5 bg-zinc-100/70 dark:bg-zinc-900/60 border-b border-zinc-200/60 dark:border-zinc-800/60 flex items-center justify-between gap-1.5 text-[11px] text-zinc-500">+ <div className="flex items-center gap-1.5 min-w-0"><PageIcon className="w-3 h-3 text-zinc-400 shrink-0" />- <span className="truncate">Discussing: {activePageTitle}</span>+ <span className="truncate">{activePageTitle ? `Page: ${activePageTitle}` : "Page Discussion"}</span></div>- )}+ {activeTab === "comments" && comments.length > 0 && (+ <CustomDropdown+ value={commentFilter}+ onChange={setCommentFilter}+ options={COMMENT_FILTER_OPTIONS}+ size="xs"+ align="right"+ buttonClassName="bg-white dark:bg-zinc-800 border-zinc-200 dark:border-zinc-700 text-zinc-600 dark:text-zinc-300 rounded-md py-0.5 px-2 text-[10px]"+ />+ )}+ </div>- {/* Messages */}- <div className="flex-1 overflow-y-auto p-3 space-y-3">- {messages.length === 0 ? (- <div className="text-center py-10 text-zinc-400 dark:text-zinc-500 text-xs">- <SparklesIcon className="w-6 h-6 mx-auto mb-2 text-indigo-400 opacity-60" />- <p>No messages yet.</p>- <p className="text-[11px] mt-1 text-zinc-400">Ask ChatGPT or tag a Dot to iterate on this page.</p>- </div>- ) : (- messages.map((m) => {- const isUser = m.sender_type === "user";- return (- <div- key={m.id}- className={`flex flex-col ${isUser ? "items-end" : "items-start"}`}- >- <span className="text-[10px] text-zinc-400 mb-0.5 px-1">{m.sender_name}</span>+ {/* Tab 1: Comments Feed */}+ {activeTab === "comments" ? (+ <>+ <div className="flex-1 overflow-y-auto p-3 space-y-3">+ {isLoadingComments ? (+ <div className="flex flex-col items-center justify-center py-10 text-zinc-400 gap-2">+ <div className="w-4 h-4 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />+ <span className="text-xs">Loading comments...</span>+ </div>+ ) : filteredComments.length === 0 ? (+ <div className="text-center py-12 text-zinc-400 dark:text-zinc-500 text-xs">+ <ChatIcon className="w-6 h-6 mx-auto mb-2 text-zinc-300 dark:text-zinc-600" />+ <p className="font-medium">+ {comments.length === 0 ? "No comments on this page yet." : "No comments match filter."}+ </p>+ <p className="text-[11px] mt-1 text-zinc-400">Leave feedback, questions, or ideas for teammates.</p>+ </div>+ ) : (+ filteredComments.map((c) => (<div- className={`max-w-[90%] rounded-xl px-3 py-2 text-xs leading-relaxed ${- isUser- ? "bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 font-medium"- : "bg-white dark:bg-zinc-800/90 text-zinc-800 dark:text-zinc-200 border border-zinc-200 dark:border-zinc-700/80 shadow-2xs"+ key={c.id}+ className={`p-3 rounded-xl border transition-all ${+ c.resolved+ ? "bg-zinc-100/60 dark:bg-zinc-900/40 border-zinc-200/60 dark:border-zinc-800/60 opacity-60"+ : "bg-white dark:bg-zinc-800/90 border-zinc-200 dark:border-zinc-700/80 shadow-2xs"}`}>- {isUser ? m.content : <MarkdownRenderer content={m.content} />}+ <div className="flex items-center justify-between mb-1.5">+ <div className="flex items-center gap-1.5">+ <div className="w-5 h-5 rounded-full bg-gradient-to-tr from-indigo-500 to-violet-500 flex items-center justify-center text-[10px] text-white font-bold">+ {(c.user_name || "Y")[0].toUpperCase()}+ </div>+ <span className="font-semibold text-xs text-zinc-900 dark:text-zinc-100">+ {c.user_name || "User"}+ </span>+ </div>++ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={() => handleToggleResolve(c.id, c.resolved)}+ className={`p-1 rounded hover:bg-zinc-200/60 dark:hover:bg-zinc-700 transition-colors cursor-pointer ${+ c.resolved ? "text-emerald-500" : "text-zinc-400 hover:text-emerald-500"+ }`}+ title={c.resolved ? "Unresolve" : "Mark resolved"}+ >+ <CheckIcon className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={() => handleDeleteComment(c.id)}+ className="p-1 rounded hover:bg-zinc-200/60 dark:hover:bg-zinc-700 text-zinc-400 hover:text-red-500 transition-colors cursor-pointer"+ title="Delete comment"+ >+ <TrashIcon className="w-3.5 h-3.5" />+ </button>+ </div>+ </div>++ <p className="text-xs text-zinc-800 dark:text-zinc-200 leading-relaxed break-words">+ {c.content}+ </p>++ <div className="mt-1.5 text-[10px] text-zinc-400">+ {new Date(c.created_at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}+ {c.resolved && <span className="ml-2 text-emerald-600 font-medium">β Resolved</span>}+ </div></div>+ ))+ )}+ </div>++ {/* Comment input */}+ <form onSubmit={handleCommentSubmit} className="p-3 border-t border-zinc-200/80 dark:border-zinc-800/80">+ <div className="relative">+ <input+ type="text"+ value={commentText}+ onChange={(e) => setCommentText(e.target.value)}+ placeholder="Add a comment to this page..."+ className="w-full bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-lg pl-3 pr-8 py-1.5 text-xs text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:border-indigo-500 shadow-2xs"+ />+ <button+ type="submit"+ disabled={!commentText.trim()}+ className="absolute right-1.5 top-1.5 text-zinc-400 hover:text-indigo-600 dark:hover:text-indigo-400 disabled:opacity-30 cursor-pointer"+ >+ <SendIcon className="w-3.5 h-3.5" />+ </button>+ </div>+ </form>+ </>+ ) : (+ /* Tab 2: AI Discussion */+ <>+ <div className="flex-1 overflow-y-auto p-3 space-y-3">+ {messages.length === 0 ? (+ <div className="text-center py-10 text-zinc-400 dark:text-zinc-500 text-xs">+ <SparklesIcon className="w-6 h-6 mx-auto mb-2 text-indigo-400 opacity-60" />+ <p>No messages yet.</p>+ <p className="text-[11px] mt-1 text-zinc-400">Ask ChatGPT or tag a Dot to iterate on this page.</p></div>- );- })- )}- </div>+ ) : (+ messages.map((m) => {+ const isUser = m.sender_type === "user";+ return (+ <div+ key={m.id}+ className={`flex flex-col ${isUser ? "items-end" : "items-start"}`}+ >+ <span className="text-[10px] text-zinc-400 mb-0.5 px-1">{m.sender_name}</span>+ <div+ className={`max-w-[90%] rounded-xl px-3 py-2 text-xs leading-relaxed ${+ isUser+ ? "bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 font-medium"+ : "bg-white dark:bg-zinc-800/90 text-zinc-800 dark:text-zinc-200 border border-zinc-200 dark:border-zinc-700/80 shadow-2xs"+ }`}+ >+ {isUser ? m.content : <MarkdownRenderer content={m.content} />}+ </div>+ </div>+ );+ })+ )}+ </div>- {/* Input */}- <form onSubmit={handleSubmit} className="p-3 border-t border-zinc-200/80 dark:border-zinc-800/80">- <div className="relative">- <input- type="text"- value={inputText}- onChange={(e) => setInputText(e.target.value)}- placeholder="Type a message or prompt..."- className="w-full bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-lg pl-3 pr-8 py-1.5 text-xs text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:border-zinc-500"- />- <button- type="submit"- disabled={!inputText.trim()}- className="absolute right-1.5 top-1.5 text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200 disabled:opacity-30"- >- <SendIcon className="w-3.5 h-3.5" />- </button>- </div>- </form>+ <form onSubmit={handleAiSubmit} className="p-3 border-t border-zinc-200/80 dark:border-zinc-800/80 space-y-2">+ <div className="flex items-center justify-between gap-1">+ <span className="text-[10px] text-zinc-400 font-medium">Direct to:</span>+ <CustomDropdown+ value={selectedAgentName}+ onChange={setSelectedAgentName}+ options={[+ { label: "General ChatGPT", value: "", icon: "β¨" },+ ...agents.map((a) => ({+ label: `@${a.name}`,+ value: a.name,+ icon: "π€",+ tag: a.role,+ })),+ ]}+ size="xs"+ direction="up"+ align="right"+ buttonClassName="bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 rounded-md py-0.5 px-2 text-[10px]"+ />+ </div>++ <div className="relative">+ <input+ type="text"+ value={inputText}+ onChange={(e) => setInputText(e.target.value)}+ placeholder={+ selectedAgentName+ ? `Message directed to @${selectedAgentName}...`+ : "Ask ChatGPT to assist with this page..."+ }+ className="w-full bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-lg pl-3 pr-8 py-1.5 text-xs text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:border-zinc-500 shadow-2xs"+ />+ <button+ type="submit"+ disabled={!inputText.trim()}+ className="absolute right-1.5 top-1.5 text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200 disabled:opacity-30 cursor-pointer"+ >+ <SendIcon className="w-3.5 h-3.5" />+ </button>+ </div>+ </form>+ </>+ )}</div>);}diff --git a/client/src/components/CustomDropdown.js b/client/src/components/CustomDropdown.jsindex ee31c98..d583c15 100644--- a/client/src/components/CustomDropdown.js+++ b/client/src/components/CustomDropdown.js@@ -6,14 +6,18 @@ import { LuChevronDown, LuCheck } from "react-icons/lu";export default function CustomDropdown({value,onChange,- options = [], // [{ label: "TypeScript", value: "typescript", icon: ... }]+ options = [], // [{ label: "TypeScript", value: "typescript", icon: ..., tag: ..., description: ... }]placeholder = "Select...",className = "",buttonClassName = "",menuClassName = "",- size = "md", // "sm" | "md"+ size = "md", // "xs" | "sm" | "md" | "lg"searchable = false,align = "left", // "left" | "right"+ direction = "down", // "down" | "up"+ header = null, // Optional menu header text+ disabled = false,+ renderTrigger = null, // (selectedOption, open) => React.ReactNode}) {const [open, setOpen] = useState(false);const [search, setSearch] = useState("");@@ -21,7 +25,16 @@ export default function CustomDropdown({const selectedOption =options.find((opt) => opt.value === value) ||- (value ? { label: typeof value === "string" ? value.charAt(0).toUpperCase() + value.slice(1) : String(value), value } : options[0]);+ options.find((opt) => opt.id === value) ||+ (value+ ? {+ label:+ typeof value === "string"+ ? value.charAt(0).toUpperCase() + value.slice(1)+ : String(value),+ value,+ }+ : null);useEffect(() => {const handleOutsideClick = (e) => {@@ -29,43 +42,83 @@ export default function CustomDropdown({setOpen(false);}};+ const handleKeyDown = (e) => {+ if (e.key === "Escape" && open) {+ setOpen(false);+ }+ };document.addEventListener("pointerdown", handleOutsideClick);- return () => document.removeEventListener("pointerdown", handleOutsideClick);- }, []);+ document.addEventListener("keydown", handleKeyDown);+ return () => {+ document.removeEventListener("pointerdown", handleOutsideClick);+ document.removeEventListener("keydown", handleKeyDown);+ };+ }, [open]);- const filteredOptions = searchable && search- ? options.filter((opt) =>- opt.label.toLowerCase().includes(search.toLowerCase().trim())- )- : options;+ const filteredOptions =+ searchable && search+ ? options.filter((opt) =>+ (opt.label || "").toLowerCase().includes(search.toLowerCase().trim()) ||+ (opt.tag || "").toLowerCase().includes(search.toLowerCase().trim())+ )+ : options;++ const sizeClasses = {+ xs: "px-2 py-0.5 text-[11px]",+ sm: "px-2.5 py-1 text-xs",+ md: "px-3 py-1.5 text-xs",+ lg: "px-3.5 py-2 text-sm",+ }[size] || "px-3 py-1.5 text-xs";++ const positionClasses =+ direction === "up"+ ? `bottom-full mb-1.5 ${align === "right" ? "right-0" : "left-0"}`+ : `top-full mt-1.5 ${align === "right" ? "right-0" : "left-0"}`;return (- <div className={`relative inline-block text-left select-none ${className}`} ref={dropdownRef}>- <button- type="button"- onClick={() => setOpen(!open)}- className={`flex items-center justify-between gap-1.5 transition-colors cursor-pointer rounded-lg border text-xs font-medium ${- size === "sm" ? "px-2 py-1" : "px-3 py-1.5"- } ${buttonClassName || "bg-zinc-50 dark:bg-zinc-900 border-zinc-200 dark:border-zinc-700 text-zinc-800 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800"}`}- >- <span className="truncate flex items-center gap-1.5">- {selectedOption?.icon && <span>{selectedOption.icon}</span>}- <span>{selectedOption?.label || placeholder}</span>- </span>- <LuChevronDown- size={12}- className={`shrink-0 transition-transform duration-150 opacity-60 ${- open ? "rotate-180" : ""+ <div+ className={`relative inline-block text-left select-none ${className}`}+ ref={dropdownRef}+ >+ {renderTrigger ? (+ <div onClick={() => !disabled && setOpen(!open)}>+ {renderTrigger(selectedOption, open)}+ </div>+ ) : (+ <button+ type="button"+ disabled={disabled}+ onClick={() => setOpen(!open)}+ className={`flex items-center justify-between gap-1.5 transition-colors cursor-pointer rounded-lg border font-medium ${sizeClasses} ${+ disabled+ ? "opacity-50 cursor-not-allowed bg-zinc-100 dark:bg-zinc-800 border-zinc-200 dark:border-zinc-700 text-zinc-400"+ : buttonClassName ||+ "bg-zinc-50 dark:bg-zinc-900 border-zinc-200 dark:border-zinc-700 text-zinc-800 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800"}`}- />- </button>+ >+ <span className="truncate flex items-center gap-1.5 min-w-0">+ {selectedOption?.icon && <span className="shrink-0">{selectedOption.icon}</span>}+ <span className="truncate">{selectedOption?.label || placeholder}</span>+ </span>+ <LuChevronDown+ size={12}+ className={`shrink-0 transition-transform duration-150 opacity-60 ${+ open ? "rotate-180" : ""+ }`}+ />+ </button>+ )}{open && (<div- className={`absolute ${- align === "right" ? "right-0" : "left-0"- } top-full mt-1.5 min-w-[160px] max-h-60 overflow-y-auto z-50 rounded-xl bg-white dark:bg-[#1c1c1f] border border-zinc-200 dark:border-zinc-700/80 shadow-2xl p-1 animate-in fade-in zoom-in-95 duration-100 ${menuClassName}`}+ className={`absolute ${positionClasses} min-w-[160px] max-h-64 overflow-y-auto z-50 rounded-xl bg-white dark:bg-[#1c1c1f] border border-zinc-200 dark:border-zinc-700/80 shadow-2xl p-1 animate-in fade-in zoom-in-95 duration-100 ${menuClassName}`}>+ {header && (+ <div className="text-[10px] font-bold uppercase tracking-wider text-zinc-400 dark:text-zinc-500 px-2.5 py-1 border-b border-zinc-100 dark:border-zinc-800 mb-1">+ {header}+ </div>+ )}+{searchable && options.length > 5 && (<div className="p-1 mb-1 border-b border-zinc-100 dark:border-zinc-800"><input@@ -78,8 +131,11 @@ export default function CustomDropdown({/></div>)}+{filteredOptions.length === 0 ? (- <div className="px-3 py-2 text-[11px] text-zinc-400 text-center">No matching options</div>+ <div className="px-3 py-2 text-[11px] text-zinc-400 text-center">+ No matching options+ </div>) : (filteredOptions.map((opt) => {const isSelected = opt.value === value;@@ -98,12 +154,22 @@ export default function CustomDropdown({: "text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800/60 hover:text-zinc-900 dark:hover:text-zinc-200"}`}>- <span className="truncate flex items-center gap-1.5">- {opt.icon && <span>{opt.icon}</span>}- <span>{opt.label}</span>- </span>+ <div className="truncate flex items-center gap-2 min-w-0">+ {opt.icon && <span className="text-sm shrink-0">{opt.icon}</span>}+ <div className="min-w-0">+ <div className="truncate leading-snug">{opt.label}</div>+ {(opt.tag || opt.description) && (+ <div className="text-[10px] text-zinc-400 dark:text-zinc-500 truncate">+ {opt.tag || opt.description}+ </div>+ )}+ </div>+ </div>{isSelected && (- <LuCheck size={13} className="text-indigo-600 dark:text-indigo-400 shrink-0 ml-1.5" />+ <LuCheck+ size={13}+ className="text-indigo-600 dark:text-indigo-400 shrink-0 ml-1.5"+ />)}</button>);diff --git a/client/src/components/HomeWorkView.js b/client/src/components/HomeWorkView.jsindex 69d5f1d..5e75cdc 100644--- a/client/src/components/HomeWorkView.js+++ b/client/src/components/HomeWorkView.js@@ -17,6 +17,7 @@ import {ShareIcon,} from "./Icons";import MarkdownRenderer from "./MarkdownRenderer";+import CustomDropdown from "./CustomDropdown";export default function HomeWorkView({activeProject = "General",@@ -29,8 +30,8 @@ export default function HomeWorkView({onOpenCanvas,}) {const [promptText, setPromptText] = useState("");- const [showModelMenu, setShowModelMenu] = useState(false);- const [attachedFile, setAttachedFile] = useState(null);+ const [attachedImage, setAttachedImage] = useState(null);+ const [isUploading, setIsUploading] = useState(false);const [copiedIdx, setCopiedIdx] = useState(null);const fileInputRef = useRef(null);@@ -68,44 +69,81 @@ export default function HomeWorkView({useEffect(() => {if (textareaRef.current) {textareaRef.current.style.height = "auto";- const nextHeight = Math.min(textareaRef.current.scrollHeight, 180);- textareaRef.current.style.height = `${Math.max(nextHeight, 28)}px`;+ const nextHeight = Math.min(textareaRef.current.scrollHeight, 200);+ textareaRef.current.style.height = `${Math.max(nextHeight, 36)}px`;}}, [promptText]);- const handleFileUpload = (e) => {+ const handleFileUpload = async (e) => {const file = e.target.files?.[0];- if (!file) return;-- const reader = new FileReader();- reader.onload = (event) => {- setAttachedFile({- name: file.name,- size: (file.size / 1024).toFixed(1) + " KB",- content: event.target.result,- type: file.type,+ if (!file || !file.type.startsWith("image/")) return;++ const localPreviewUrl = URL.createObjectURL(file);++ // Show preview thumbnail locally while uploading, url is null until upload returns hosted link+ setAttachedImage({+ name: file.name,+ previewUrl: localPreviewUrl,+ url: null,+ });++ setIsUploading(true);++ const formData = new FormData();+ formData.append("file", file);++ try {+ const res = await fetch("http://localhost:8000/api/upload_file", {+ method: "POST",+ headers: { "X-User-Id": "usr-1" },+ body: formData,});- };- reader.readAsText(file);- e.target.value = "";++ if (res.ok) {+ const data = await res.json();+ // data.url is the hosted public link from MuAPI (https://cdn.muapi.ai/...)+ setAttachedImage((prev) => ({+ ...prev,+ url: data.url,+ }));+ setIsUploading(false);+ e.target.value = "";+ return;+ } else {+ const err = await res.json().catch(() => ({}));+ console.error("Upload failed:", res.status, err);+ alert(`Image upload failed: ${err.detail || res.statusText || res.status}`);+ setAttachedImage(null);+ }+ } catch (err) {+ console.error("Upload to server failed:", err);+ alert("Failed to connect to upload server. Please check your network or server status.");+ setAttachedImage(null);+ } finally {+ setIsUploading(false);+ if (e.target) e.target.value = "";+ }};const handleSend = (e) => {if (e) e.preventDefault();- if ((!promptText.trim() && !attachedFile) || isLoading) return;+ if (isLoading || isUploading) return;+ if (!promptText.trim() && !attachedImage) return;- let finalPrompt = promptText.trim();- if (attachedFile) {- finalPrompt = finalPrompt- ? `[Attached File: ${attachedFile.name}]\n${attachedFile.content}\n\n${finalPrompt}`- : `[Attached File: ${attachedFile.name}]\nPlease analyze this attached document:\n${attachedFile.content}`;+ // Must wait for image to upload and obtain its hosted link+ if (attachedImage && !attachedImage.url) {+ return;}- onSubmitPrompt(finalPrompt);+ const finalPrompt = promptText.trim();+ // Strictly the hosted public link (https://...), NEVER a local blob+ const imageUrl = attachedImage?.url || null;++ onSubmitPrompt(finalPrompt, imageUrl);setPromptText("");- setAttachedFile(null);+ setAttachedImage(null);if (textareaRef.current) {- textareaRef.current.style.height = "28px";+ textareaRef.current.style.height = "36px";}};@@ -115,136 +153,99 @@ export default function HomeWorkView({setTimeout(() => setCopiedIdx(null), 2000);};- // Reusable Pill / Capsule Input Box complying with THEME_PLAN.md+ // ChatGPT Native Card Input Box matching screenshotconst renderInputBar = () => {- const isMultiline =- (promptText.match(/\n/g) || []).length > 0 || promptText.length > 80;-return (<div className="w-full max-w-3xl mx-auto relative select-none">- {/* Models Switcher Popover Menu */}- {showModelMenu && (- <div className="absolute right-12 bottom-full mb-2 w-64 bg-white dark:bg-[#1f1f23] text-zinc-900 dark:text-zinc-200 border border-zinc-200 dark:border-zinc-700/80 rounded-xl shadow-xl p-1.5 z-40 backdrop-blur-md">- <div className="text-[10px] font-bold text-zinc-500 dark:text-zinc-400 px-2.5 py-1.5 flex items-center justify-between border-b border-zinc-200 dark:border-zinc-700/60 mb-1">- <span>ChatGPT 6 Series (MuAPI)</span>- </div>- <div className="space-y-0.5">- {models.map((m) => {- const isSelected = selectedModel === m.id;- return (- <button- key={m.id}- type="button"- onClick={() => {- onSelectModel(m.id);- setShowModelMenu(false);- }}- className={`w-full text-left px-2.5 py-2 rounded-xl text-xs flex items-center justify-between transition-colors cursor-pointer ${- isSelected- ? "bg-zinc-100 dark:bg-zinc-800 text-zinc-900 dark:text-white font-medium shadow-2xs"- : "text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800/60 hover:text-zinc-900 dark:hover:text-white"- }`}- >- <div className="flex items-center gap-2">- <span className="text-sm">{m.icon}</span>- <div>- <div className="leading-snug">{m.name}</div>- <div className="text-[10px] text-zinc-400">{m.tag}</div>- </div>- </div>- {isSelected && (- <CheckIcon className="w-3.5 h-3.5 text-emerald-500 dark:text-emerald-400 shrink-0" />- )}- </button>- );- })}+ {/* Outer Card Container */}+ <div className="flex flex-col bg-[#f4f4f5] dark:bg-[#212121] border border-zinc-200 dark:border-zinc-700/70 p-3 sm:p-3.5 rounded-3xl shadow-sm hover:border-zinc-300 dark:hover:border-zinc-600 focus-within:border-zinc-300 dark:focus-within:border-zinc-600 transition-all">+ {/* Top Section: Uploaded Image Preview Thumbnail */}+ {attachedImage && (+ <div className="relative group w-20 h-20 mb-3 shrink-0">+ <img+ src={attachedImage.previewUrl || attachedImage.url}+ alt={attachedImage.name || "Preview"}+ className="w-20 h-20 rounded-2xl object-cover border border-zinc-300/60 dark:border-zinc-700/80 shadow-xs"+ />+ {isUploading && (+ <div className="absolute inset-0 bg-black/40 rounded-2xl flex items-center justify-center backdrop-blur-[1px]">+ <div className="w-5 h-5 border-2 border-white/80 border-t-transparent rounded-full animate-spin" />+ </div>+ )}+ <button+ type="button"+ onClick={() => setAttachedImage(null)}+ title="Remove image"+ className="absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full bg-zinc-800 text-white dark:bg-zinc-700 hover:bg-black dark:hover:bg-zinc-600 flex items-center justify-center text-xs opacity-0 group-hover:opacity-100 transition-opacity shadow-sm cursor-pointer"+ >+ <CloseIcon className="w-3 h-3" />+ </button></div>- </div>- )}-- {/* Outer Capsule / Pill conforming to THEME_PLAN */}- <div- className={`flex items-end gap-2 bg-[#f4f4f5] dark:bg-[#212121] border border-zinc-200 dark:border-zinc-700/70 p-2 px-3 shadow-sm hover:border-zinc-300 dark:hover:border-zinc-600 transition-all ${- isMultiline || attachedFile ? "rounded-3xl" : "rounded-full"- }`}- >- {/* Left: Upload + Button */}- <button- type="button"- onClick={() => fileInputRef.current?.click()}- title="Attach file or image"- className="w-8 h-8 rounded-full text-zinc-500 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-200/80 dark:hover:bg-zinc-700/50 flex items-center justify-center transition-colors shrink-0 mb-0.5 cursor-pointer"- >- <PlusIcon className="w-4 h-4" />- </button>-- {/* Middle: Attached file chip + Expandable Textarea */}- <div className="flex-1 flex flex-col min-w-0">- {attachedFile && (- <div className="flex items-center gap-1.5 px-2 py-0.5 mb-1 bg-zinc-200 dark:bg-zinc-800 rounded-lg text-xs w-fit text-zinc-800 dark:text-zinc-200 border border-zinc-300 dark:border-zinc-700">- <PageIcon className="w-3 h-3 text-indigo-500" />- <span className="truncate max-w-xs text-[11px] font-medium">- {attachedFile.name}- </span>- <span className="text-[10px] text-zinc-500 dark:text-zinc-400">- ({attachedFile.size})- </span>- <button- type="button"- onClick={() => setAttachedFile(null)}- className="text-zinc-500 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-white ml-0.5"- >- <CloseIcon className="w-3 h-3" />- </button>- </div>- )}-- <textarea- ref={textareaRef}- rows={1}- value={promptText}- onChange={(e) => setPromptText(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- handleSend();- }- }}- placeholder="Ask ChatGPT"- className="w-full bg-transparent text-sm text-zinc-900 dark:text-zinc-100 placeholder-zinc-500 dark:placeholder-zinc-400 resize-none focus:outline-none leading-relaxed py-1.5 px-1 max-h-48 overflow-y-auto"- />- </div>-- {/* Right: Models button & Send Arrow button */}- <div className="flex items-center gap-1.5 shrink-0 mb-0.5">- {/* Models Dropdown Button */}+ )}++ {/* Middle Section: Expandable Textarea */}+ <textarea+ ref={textareaRef}+ rows={1}+ value={promptText}+ onChange={(e) => setPromptText(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ handleSend();+ }+ }}+ placeholder="Ask ChatGPT"+ className="w-full bg-transparent text-sm sm:text-base text-zinc-900 dark:text-zinc-100 placeholder-zinc-500 dark:placeholder-zinc-400 resize-none focus:outline-none leading-relaxed py-1 px-1 min-h-[36px] max-h-48 overflow-y-auto"+ />++ {/* Bottom Row: Left (+) and Right (Think, Mic, Green Send Arrow) */}+ <div className="flex items-center justify-between pt-2 select-none">+ {/* Left: Upload Image + Button */}<buttontype="button"- onClick={() => setShowModelMenu(!showModelMenu)}- title={`Switch Model: ${currentModelObj.name}`}- className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-colors border cursor-pointer ${- showModelMenu- ? "bg-zinc-200 dark:bg-zinc-800 border-zinc-300 dark:border-zinc-600 text-zinc-900 dark:text-white"- : "bg-transparent hover:bg-zinc-200/80 dark:hover:bg-zinc-800/80 border-transparent hover:border-zinc-300 dark:hover:border-zinc-700 text-zinc-700 dark:text-zinc-300"- }`}+ onClick={() => fileInputRef.current?.click()}+ title="Attach image"+ className="w-8 h-8 rounded-full text-zinc-500 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-200/80 dark:hover:bg-zinc-800/80 flex items-center justify-center transition-colors cursor-pointer">- <span>{currentModelObj.icon}</span>- <span className="truncate max-w-[130px]">- {currentModelObj.name}- </span>- <ChevronDownIcon className="w-3 h-3 text-zinc-400 ml-0.5" />+ <PlusIcon className="w-4 h-4" /></button>+ {/* Right: Think, Mic, and Circular Green Send Button */}+ <div className="flex items-center gap-1.5 sm:gap-2">+ {/* Think Button (Models Dropdown) */}+ <CustomDropdown+ value={selectedModel}+ onChange={onSelectModel}+ options={models.map((m) => ({+ label: m.name,+ value: m.id,+ icon: m.icon,+ tag: m.tag,+ }))}+ direction="up"+ align="right"+ header="ChatGPT 6 Series (MuAPI)"+ menuClassName="w-64 bg-white dark:bg-[#1f1f23] border-zinc-200 dark:border-zinc-700/80 p-1.5 shadow-2xl backdrop-blur-md"+ buttonClassName="bg-transparent hover:bg-zinc-200/80 dark:hover:bg-zinc-800/80 border-transparent hover:border-zinc-300 dark:hover:border-zinc-700 text-zinc-700 dark:text-zinc-300 rounded-full px-3 py-1.5"+ />+{/* Send Arrow Button */}- <button- type="button"- onClick={handleSend}- disabled={isLoading || (!promptText.trim() && !attachedFile)}- title="Send message"- className="w-8 h-8 rounded-full bg-zinc-900 hover:bg-zinc-800 text-white dark:bg-white dark:hover:bg-zinc-200 dark:text-zinc-900 flex items-center justify-center transition-transform hover:scale-105 shadow-sm shrink-0 cursor-pointer disabled:opacity-30 disabled:hover:scale-100"- >- <ArrowUpIcon className="w-4 h-4 stroke-[2.5]" />- </button>+ <button+ type="button"+ onClick={handleSend}+ disabled={+ isLoading ||+ isUploading ||+ (!promptText.trim() && !attachedImage) ||+ (attachedImage && !attachedImage.url)+ }+ title="Send message"+ className="w-8 h-8 rounded-full bg-zinc-900 hover:bg-zinc-800 text-white dark:bg-white dark:hover:bg-zinc-200 dark:text-zinc-900 flex items-center justify-center transition-transform hover:scale-105 shadow-sm shrink-0 cursor-pointer disabled:opacity-30 disabled:hover:scale-100 disabled:cursor-not-allowed"+ >+ <ArrowUpIcon className="w-4 h-4 stroke-[2.5]" />+ </button>+ </div></div></div></div>@@ -253,13 +254,13 @@ export default function HomeWorkView({return (<div className="flex-1 flex flex-col h-full bg-[#fbfbfa] dark:bg-[#141416] text-zinc-900 dark:text-zinc-100 overflow-hidden transition-colors duration-150 select-none">- {/* Hidden File Input for the upload + button */}+ {/* Hidden File Input strictly for images */}<inputtype="file"ref={fileInputRef}onChange={handleFileUpload}className="hidden"- accept=".txt,.md,.json,.js,.py,.csv,.html,.css,.doc,.pdf"+ accept="image/*"/>{/* 1. Chat Conversation Active Mode */}@@ -277,7 +278,14 @@ export default function HomeWorkView({>{isUser ? (/* User message styled for both Light and Dark mode */- <div className="bg-[#f4f4f5] dark:bg-[#1a402d] text-zinc-900 dark:text-zinc-100 border border-zinc-200/80 dark:border-transparent px-4 py-2.5 rounded-3xl text-sm leading-relaxed max-w-xl shadow-xs select-text">+ <div className="bg-[#f4f4f5] dark:bg-[#1a402d] text-zinc-900 dark:text-zinc-100 border border-zinc-200/80 dark:border-transparent px-4 py-2.5 rounded-3xl text-sm leading-relaxed max-w-xl shadow-xs select-text space-y-2">+ {msg.image_url && (+ <img+ src={msg.image_url}+ alt="Attached image"+ className="max-h-60 rounded-xl object-contain border border-zinc-200 dark:border-zinc-700/60 shadow-xs"+ />+ )}<p className="whitespace-pre-wrap">{msg.content}</p></div>) : (@@ -387,7 +395,7 @@ export default function HomeWorkView({/* 2. Initial Centered "What should we work on?" view */<div className="flex-1 flex flex-col items-center justify-center px-4 -mt-12"><h1 className="text-3xl font-semibold tracking-tight text-zinc-900 dark:text-zinc-100 mb-8 text-center">- What should we work on?+ What's on the agenda today?</h1>{/* Capsule Input Field */}diff --git a/client/src/components/OpenSpacesApp.js b/client/src/components/OpenSpacesApp.jsindex 1c1e936..d9347d6 100644--- a/client/src/components/OpenSpacesApp.js+++ b/client/src/components/OpenSpacesApp.js@@ -11,6 +11,7 @@ import HomeWorkView from "./HomeWorkView";import ChatDrawer from "./ChatDrawer";const API_BASE = "http://localhost:8000/api";+const AUTH_HEADERS = { "X-User-Id": "usr-1" };const STORAGE_KEY = "open_spaces_chat_history";const LAST_ROUTE_KEY = "open_spaces_last_route";@@ -46,6 +47,7 @@ export default function OpenSpacesApp({const [isCreatingPage, setIsCreatingPage] = useState(false);const [messages, setMessages] = useState([]);const [chatOpen, setChatOpen] = useState(false);+ const [historyOpen, setHistoryOpen] = useState(false);const [saveStatus, setSaveStatus] = useState("Saved");const [saveTrigger, setSaveTrigger] = useState(0);@@ -121,7 +123,7 @@ export default function OpenSpacesApp({// 2. Fetch Spaces on load and restore route from URL or localStorageconst fetchSpaces = useCallback(async () => {try {- const res = await fetch(`${API_BASE}/spaces`);+ const res = await fetch(`${API_BASE}/spaces`, { headers: AUTH_HEADERS });if (res.ok) {const data = await res.json();setSpaces(data);@@ -188,7 +190,7 @@ export default function OpenSpacesApp({const fetchSpaceDetails = useCallback(async (spaceId, targetPageId = null) => {if (!spaceId) return;try {- const pRes = await fetch(`${API_BASE}/spaces/${spaceId}/pages`);+ const pRes = await fetch(`${API_BASE}/spaces/${spaceId}/pages`, { headers: AUTH_HEADERS });if (pRes.ok) {const pData = await pRes.json();setPages(pData);@@ -200,7 +202,7 @@ export default function OpenSpacesApp({}}- const mRes = await fetch(`${API_BASE}/spaces/${spaceId}/messages`);+ const mRes = await fetch(`${API_BASE}/spaces/${spaceId}/messages`, { headers: AUTH_HEADERS });if (mRes.ok) {const mData = await mRes.json();setMessages(mData);@@ -354,8 +356,14 @@ export default function OpenSpacesApp({};// Submit prompt to ChatGPT 6 series- const handleSubmitPrompt = async (prompt) => {- const userMsg = { role: "user", content: prompt };+ const handleSubmitPrompt = async (prompt, imageUrl = null) => {+ if ((!prompt || !prompt.trim()) && !imageUrl) return;++ const userMsg = {+ role: "user",+ content: prompt,+ ...(imageUrl ? { image_url: imageUrl } : {}),+ };const updatedConv = [...conversation, userMsg];setConversation(updatedConv);setIsGenerating(true);@@ -368,7 +376,7 @@ export default function OpenSpacesApp({currentId = "chat-" + generateUUID();setActiveConversationId(currentId);const title =- prompt.length > 36 ? prompt.slice(0, 36).trim() + "..." : prompt;+ prompt && prompt.length > 36 ? prompt.slice(0, 36).trim() + "..." : (prompt || "Image Analysis");const newConv = {id: currentId,title,@@ -397,6 +405,7 @@ export default function OpenSpacesApp({headers: { "Content-Type": "application/json" },body: JSON.stringify({prompt,+ image_url: imageUrl || undefined,model: selectedModel,project: activeProject,history: updatedConv,@@ -408,7 +417,8 @@ export default function OpenSpacesApp({const data = await res.json();assistantReply = data.reply;} else {- assistantReply = `[${selectedModel}] I received your prompt. Let's begin drafting the plan in your Space.`;+ const errData = await res.json().catch(() => ({}));+ throw new Error(errData.detail || `AI service returned error status ${res.status}`);}const finalConv = [@@ -426,10 +436,10 @@ export default function OpenSpacesApp({persistConversations(finalizedList);} catch (err) {console.error("Error calling chat endpoint:", err);- const fallbackReply = `[GPT-6.1 Sol Light] Here is the outline for "${prompt}":\n\n1. Scope and target deliverables.\n2. Ingest contextual documents into Living Pages.\n3. Delegate tasks to autonomous Dot agents.`;+ const errorMsg = `β οΈ Generation failed: ${err.message || "Unable to reach AI service"}`;const finalConv = [...updatedConv,- { role: "assistant", content: fallbackReply },+ { role: "assistant", content: errorMsg, isError: true },];setConversation(finalConv);const finalizedList = currentList.map((c) =>@@ -477,7 +487,7 @@ export default function OpenSpacesApp({try {const res = await fetch(`${API_BASE}/spaces`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },body: JSON.stringify(spaceData),});if (res.ok) {@@ -498,6 +508,7 @@ export default function OpenSpacesApp({try {const res = await fetch(`${API_BASE}/spaces/${spaceId}`, {method: "DELETE",+ headers: AUTH_HEADERS,});if (res.ok) {const remaining = spaces.filter((s) => s.id !== spaceId);@@ -521,7 +532,7 @@ export default function OpenSpacesApp({targetSpace = spaces[0];} else {try {- const sRes = await fetch(`${API_BASE}/spaces`);+ const sRes = await fetch(`${API_BASE}/spaces`, { headers: AUTH_HEADERS });if (sRes.ok) {const list = await sRes.json();if (list.length > 0) {@@ -568,7 +579,7 @@ export default function OpenSpacesApp({try {const res = await fetch(`${API_BASE}/spaces/${targetSpace.id}/pages`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },body: JSON.stringify({title: titleStr,content: contentStr,@@ -600,9 +611,14 @@ export default function OpenSpacesApp({try {const res = await fetch(`${API_BASE}/spaces/${activeSpace.id}/pages/${pageId}`, {method: "PATCH",- headers: { "Content-Type": "application/json" },+ headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },body: JSON.stringify(updateData),});+ if (res && res.status === 409) {+ const conflictData = await res.json();+ setSaveStatus("Conflict");+ return { conflict: true, detail: conflictData.detail };+ }if (res && res.ok) {const updated = await res.json();setPages((prev) => prev.map((p) => (p.id === updated.id ? updated : p)));@@ -621,11 +637,33 @@ export default function OpenSpacesApp({}};+ const handleRestoreRevision = async (pageId, version) => {+ if (!activeSpace || !pageId) return null;+ setSaveStatus("Saving...");+ try {+ const res = await fetch(`${API_BASE}/spaces/${activeSpace.id}/pages/${pageId}/revisions/${version}/restore`, {+ method: "POST",+ headers: AUTH_HEADERS,+ });+ if (res.ok) {+ const restored = await res.json();+ setPages((prev) => prev.map((p) => (p.id === restored.id ? restored : p)));+ setSaveStatus("Saved");+ return restored;+ }+ } catch (err) {+ console.error("Error restoring revision:", err);+ }+ setSaveStatus("Failed");+ return null;+ };+const handleDeletePage = async (pageId) => {if (!activeSpace || !pageId) return;try {const res = await fetch(`${API_BASE}/spaces/${activeSpace.id}/pages/${pageId}`, {method: "DELETE",+ headers: AUTH_HEADERS,});if (res.ok) {setPages((prev) => prev.filter((p) => p.id !== pageId));@@ -686,6 +724,7 @@ export default function OpenSpacesApp({activePageId={activePageId}onSelectPage={handleSelectPage}onCreatePage={handleCreatePage}+ onDeletePage={handleDeletePage}isCreatingPage={isCreatingPage}/>)}@@ -739,6 +778,8 @@ export default function OpenSpacesApp({onNewPage={() => handleCreatePage({ title: "Untitled page", content: "" })}onToggleChat={() => setChatOpen(!chatOpen)}chatOpen={chatOpen}+ onToggleHistory={() => setHistoryOpen(!historyOpen)}+ historyOpen={historyOpen}onTriggerAI={() => setChatOpen(true)}onDownloadMarkdown={handleDownloadMarkdown}onDeletePage={() => handleDeletePage(activePageId)}@@ -752,6 +793,9 @@ export default function OpenSpacesApp({onUpdatePage={handleUpdatePage}onStatusChange={setSaveStatus}saveTrigger={saveTrigger}+ historyOpen={historyOpen}+ onCloseHistory={() => setHistoryOpen(false)}+ onRestoreRevision={handleRestoreRevision}onTriggerAI={(p) => handleSubmitPrompt(p)}/>@@ -763,6 +807,8 @@ export default function OpenSpacesApp({onSendMessage={() => {}}agents={activeSpace?.agents || []}activePageTitle={activePage?.title}+ activePageId={activePage?.id}+ spaceId={activeSpace?.id}/>)}</div>diff --git a/client/src/components/PageHeaderBar.js b/client/src/components/PageHeaderBar.jsindex 04c2134..f4cdc68 100644--- a/client/src/components/PageHeaderBar.js+++ b/client/src/components/PageHeaderBar.js@@ -11,7 +11,10 @@ import {ArrowLeftIcon,DownloadIcon,TrashIcon,+ ClockIcon,+ MoreIcon,} from "./Icons";+import CustomDropdown from "./CustomDropdown";export default function PageHeaderBar({title = "Untitled page",@@ -26,17 +29,19 @@ export default function PageHeaderBar({onNewPage,onToggleChat,chatOpen,+ onToggleHistory,+ historyOpen = false,onTriggerAI,onDownloadMarkdown,onDeletePage,onSaveNow,- saveStatus = "Saved", // 'Saved' | 'Saving...' | 'Unsaved changes' | 'Failed'+ saveStatus = "Saved", // 'Saved' | 'Saving...' | 'Unsaved changes' | 'Conflict' | 'Failed'}) {- // If openPages array is supplied, render all open tabs; otherwise fallback to single tab+ // Render open tabs or active pageconst tabs =- openPages.length > 0+ openPages && openPages.length > 0? openPages- : [{ id: activePageId || "single", title, icon }];+ : (activePageId ? [{ id: activePageId, title, icon }] : []);return (<header className="h-11 border-b border-zinc-200/80 dark:border-zinc-800/80 bg-white dark:bg-[#141416] flex items-center justify-between px-3 select-none text-xs text-zinc-600 dark:text-zinc-400 transition-colors duration-150">@@ -103,16 +108,20 @@ export default function PageHeaderBar({{/* Autosave / Save Now button */}<buttontype="button"- onClick={saveStatus === "Unsaved changes" || saveStatus === "Failed" ? onSaveNow : undefined}+ onClick={saveStatus === "Unsaved changes" || saveStatus === "Failed" || saveStatus === "Conflict" ? onSaveNow : undefined}title={- saveStatus === "Unsaved changes"+ saveStatus === "Conflict"+ ? "Edit conflict detected. Click to review options"+ : saveStatus === "Unsaved changes"? "Unsaved changes. Click to save now or press β/Ctrl+S": saveStatus === "Failed"? "Save failed. Click to retry"- : "Status"+ : "Saved to cloud"}className={`text-[11px] font-medium hidden sm:flex items-center gap-1.5 px-2.5 py-0.5 rounded-full border transition-all ${- saveStatus === "Unsaved changes"+ saveStatus === "Conflict"+ ? "bg-rose-50 dark:bg-rose-950/40 border-rose-300 dark:border-rose-700/80 text-rose-700 dark:text-rose-300 cursor-pointer hover:bg-rose-100"+ : saveStatus === "Unsaved changes"? "bg-amber-50 dark:bg-amber-950/40 border-amber-300 dark:border-amber-700/80 text-amber-700 dark:text-amber-300 cursor-pointer hover:bg-amber-100 dark:hover:bg-amber-900/40": saveStatus === "Saving..."? "bg-amber-50 dark:bg-amber-950/30 border-amber-200 dark:border-amber-800 text-amber-600 dark:text-amber-400 cursor-default"@@ -127,6 +136,8 @@ export default function PageHeaderBar({? "bg-amber-400 animate-ping": saveStatus === "Unsaved changes"? "bg-amber-500"+ : saveStatus === "Conflict"+ ? "bg-rose-500 animate-pulse": saveStatus === "Failed"? "bg-red-500": "bg-emerald-500"@@ -135,27 +146,57 @@ export default function PageHeaderBar({<span>{saveStatus}</span></button>- {/* Download Markdown */}- {onDownloadMarkdown && (+ {/* Revisions History button */}+ {onToggleHistory && (<button- onClick={onDownloadMarkdown}- title="Download page as Markdown (.md)"- className="p-1.5 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-500 dark:text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200 transition-colors cursor-pointer"+ onClick={onToggleHistory}+ title="Page Revision History & Snapshots"+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded-lg transition-colors cursor-pointer text-xs font-medium ${+ historyOpen+ ? "bg-zinc-900 text-white dark:bg-white dark:text-zinc-900 shadow-2xs"+ : "bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 hover:bg-zinc-200 dark:hover:bg-zinc-700"+ }`}>- <DownloadIcon className="w-3.5 h-3.5" />+ <ClockIcon className="w-3.5 h-3.5" />+ <span className="hidden sm:inline">History</span></button>)}- {/* Delete Page */}- {onDeletePage && (- <button- onClick={onDeletePage}- title="Delete this page"- className="p-1.5 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-red-500 transition-colors cursor-pointer"- >- <TrashIcon className="w-3.5 h-3.5" />- </button>- )}+ {/* Page Actions CustomDropdown */}+ <CustomDropdown+ value=""+ onChange={(action) => {+ if (action === "history" && onToggleHistory) onToggleHistory();+ if (action === "download" && onDownloadMarkdown) onDownloadMarkdown();+ if (action === "delete" && onDeletePage) onDeletePage();+ }}+ options={[+ ...(onToggleHistory+ ? [{ label: "Revision History", value: "history", icon: <ClockIcon className="w-3.5 h-3.5 text-zinc-500" /> }]+ : []),+ ...(onDownloadMarkdown+ ? [{ label: "Download Markdown (.md)", value: "download", icon: <DownloadIcon className="w-3.5 h-3.5 text-zinc-500" /> }]+ : []),+ ...(onDeletePage+ ? [{ label: "Delete Page", value: "delete", icon: <TrashIcon className="w-3.5 h-3.5 text-rose-500" /> }]+ : []),+ ]}+ align="right"+ size="xs"+ renderTrigger={(_, open) => (+ <button+ type="button"+ className={`p-1.5 rounded-lg transition-colors cursor-pointer ${+ open+ ? "bg-zinc-200 dark:bg-zinc-700 text-zinc-900 dark:text-zinc-100"+ : "hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-500 dark:text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200"+ }`}+ title="Page Options & Actions"+ >+ <MoreIcon className="w-4 h-4" />+ </button>+ )}+ />{/* Discussion / Chat drawer toggle */}<buttondiff --git a/client/src/components/SpaceChat.js b/client/src/components/SpaceChat.jsindex 70a7476..adba3c0 100644--- a/client/src/components/SpaceChat.js+++ b/client/src/components/SpaceChat.js@@ -2,6 +2,7 @@import React, { useState } from "react";import { SendIcon, SparklesIcon, BotIcon, PageIcon } from "./Icons";+import CustomDropdown from "./CustomDropdown";export default function SpaceChat({messages = [],@@ -106,23 +107,25 @@ export default function SpaceChat({{/* Input bar */}<div className="p-4 border-t border-zinc-200 dark:border-zinc-800 bg-white dark:bg-[#19191d] transition-colors"><div className="max-w-4xl mx-auto space-y-2">- {/* Quick Tag Dot Agent pill */}+ {/* Quick Tag Dot Agent with CustomDropdown */}<div className="flex items-center gap-2">- <span className="text-[11px] text-zinc-500 dark:text-zinc-400">Mention Dot:</span>- {agents.map((agent) => (- <button- key={agent.id}- type="button"- onClick={() => setSelectedAgent(agent.name)}- className={`text-[11px] px-2 py-0.5 rounded-full transition-colors ${- selectedAgent === agent.name- ? "bg-indigo-600 text-white"- : "bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-200"- }`}- >- @{agent.name.split(" ")[0]}- </button>- ))}+ <span className="text-[11px] text-zinc-500 dark:text-zinc-400">Direct to:</span>+ <CustomDropdown+ value={selectedAgent}+ onChange={setSelectedAgent}+ options={[+ { label: "Everyone (Space)", value: "", icon: "π₯" },+ ...agents.map((agent) => ({+ label: `@${agent.name}`,+ value: agent.name,+ icon: "π€",+ description: agent.role,+ })),+ ]}+ size="xs"+ direction="up"+ buttonClassName="bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 rounded-md py-0.5 px-2 text-[11px]"+ /></div><form onSubmit={handleSubmit} className="flex gap-2">diff --git a/client/src/components/SpaceLibrary.js b/client/src/components/SpaceLibrary.jsindex 2167c65..6908d9d 100644--- a/client/src/components/SpaceLibrary.js+++ b/client/src/components/SpaceLibrary.js@@ -1,6 +1,6 @@"use client";-import React, { useState, useMemo } from "react";+import React, { useState, useMemo, useEffect } from "react";import {PageIcon,PlusIcon,@@ -9,15 +9,26 @@ import {ListIcon,ArrowUpRightIcon,TrashIcon,+ CloseIcon,+ ClockIcon,} from "./Icons";+import { LuUsers, LuActivity, LuUserPlus, LuCheck } from "react-icons/lu";import CustomDropdown from "./CustomDropdown";+const API_BASE = "http://localhost:8000/api";+const SORT_OPTIONS = [{ label: "Recently edited", value: "recent" },{ label: "Name AβZ", value: "name" },];-// Helper to extract clean plaintext preview from Markdown content (modeled on OpenDots)+const ROLE_OPTIONS = [+ { label: "Editor (Can edit & create)", value: "editor" },+ { label: "Commenter (Can comment)", value: "commenter" },+ { label: "Viewer (Read-only)", value: "viewer" },+];++// Helper to extract clean plaintext preview from Markdown contentexport function pageExcerpt(content = "") {if (!content) return "";return content@@ -40,11 +51,146 @@ export default function SpaceLibrary({onNewPage,onDeletePage,isCreatingPage = false,+ onSpaceUpdated,}) {+ const [activeTab, setActiveTab] = useState("pages"); // 'pages' | 'activity'const [query, setQuery] = useState("");const [layout, setLayout] = useState("grid"); // 'grid' | 'list'const [sort, setSort] = useState("recent"); // 'recent' | 'name'+ // Members modal & invitation state+ const [showMemberModal, setShowMemberModal] = useState(false);+ const [members, setMembers] = useState([]);+ const [inviteEmail, setInviteEmail] = useState("");+ const [inviteRole, setInviteRole] = useState("editor");+ const [isInviting, setIsInviting] = useState(false);+ const [inviteNotice, setInviteNotice] = useState("");++ // Activity Feed state+ const [activities, setActivities] = useState([]);+ const [isLoadingActivities, setIsLoadingActivities] = useState(false);++ // Fetch members+ const fetchMembers = async () => {+ if (!space?.id) return;+ try {+ const res = await fetch(`${API_BASE}/spaces/${space.id}/members`, {+ headers: { "X-User-Id": "usr-1" },+ });+ if (res.ok) {+ const data = await res.json();+ setMembers(data);+ }+ } catch (err) {+ console.error("Error loading members:", err);+ }+ };++ // Fetch activities+ const fetchActivities = async () => {+ if (!space?.id) return;+ setIsLoadingActivities(true);+ try {+ const res = await fetch(`${API_BASE}/spaces/${space.id}/activity?limit=30`, {+ headers: { "X-User-Id": "usr-1" },+ });+ if (res.ok) {+ const data = await res.json();+ setActivities(data);+ }+ } catch (err) {+ console.error("Error loading activity log:", err);+ } finally {+ setIsLoadingActivities(false);+ }+ };++ useEffect(() => {+ if (space?.id) {+ fetchMembers();+ if (activeTab === "activity") {+ fetchActivities();+ }+ }+ }, [space?.id, activeTab]);++ const handleInviteSubmit = async (e) => {+ e.preventDefault();+ if (!inviteEmail.trim() || !space?.id) return;++ setIsInviting(true);+ setInviteNotice("");+ try {+ const res = await fetch(`${API_BASE}/spaces/${space.id}/members`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-User-Id": "usr-1",+ },+ body: JSON.stringify({+ email: inviteEmail.trim(),+ role: inviteRole,+ }),+ });++ if (res.ok) {+ const newMember = await res.json();+ setMembers((prev) => {+ const filtered = prev.filter((m) => m.user_id !== newMember.user_id);+ return [...filtered, newMember];+ });+ setInviteNotice(`Invited ${newMember.name} as ${inviteRole}!`);+ setInviteEmail("");+ if (onSpaceUpdated) onSpaceUpdated();+ } else {+ const errText = await res.text();+ setInviteNotice(`Failed to invite: ${errText}`);+ }+ } catch (err) {+ setInviteNotice(`Error: ${err.message}`);+ } finally {+ setIsInviting(false);+ }+ };++ const handleRemoveMember = async (userId) => {+ if (!space?.id || !userId) return;+ try {+ const res = await fetch(`${API_BASE}/spaces/${space.id}/members/${userId}`, {+ method: "DELETE",+ headers: { "X-User-Id": "usr-1" },+ });+ if (res.ok) {+ setMembers((prev) => prev.filter((m) => m.user_id !== userId));+ if (onSpaceUpdated) onSpaceUpdated();+ }+ } catch (err) {+ console.error("Error removing member:", err);+ }+ };++ const handleUpdateMemberRole = async (userId, newRole) => {+ if (!space?.id || !userId) return;+ try {+ const res = await fetch(`${API_BASE}/spaces/${space.id}/members`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-User-Id": "usr-1",+ },+ body: JSON.stringify({ user_id: userId, role: newRole }),+ });+ if (res.ok) {+ setMembers((prev) =>+ prev.map((m) => (m.user_id === userId ? { ...m, role: newRole } : m))+ );+ if (onSpaceUpdated) onSpaceUpdated();+ }+ } catch (err) {+ console.error("Error updating member role:", err);+ }+ };+const filtered = useMemo(() => {return pages.filter((page) =>@@ -78,7 +224,7 @@ export default function SpaceLibrary({return (<div className="flex-1 flex flex-col h-full bg-[#fbfbfa] dark:bg-[#141416] text-zinc-900 dark:text-zinc-100 overflow-y-auto select-none transition-colors duration-150"><div className="max-w-5xl mx-auto w-full p-6 sm:p-8 space-y-6">- {/* Header (modeled on OpenDots library-heading) */}+ {/* Header */}<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-zinc-200/80 dark:border-zinc-800/80"><div><div className="text-[11px] font-bold uppercase tracking-wider text-indigo-600 dark:text-indigo-400 mb-1 flex items-center gap-1.5">@@ -92,6 +238,33 @@ export default function SpaceLibrary({{space?.description ||"A persistent home for living pages, autonomous agent research, and collaborative documents."}</p>++ {/* Team Members Pill & Invite Button */}+ <div className="flex items-center gap-2 mt-3">+ <div className="flex items-center -space-x-1.5">+ {(members.length > 0 ? members : space?.members || []).slice(0, 4).map((m, idx) => (+ <div+ key={m.id || idx}+ className="w-6 h-6 rounded-full bg-indigo-600 border-2 border-white dark:border-zinc-900 flex items-center justify-center text-[10px] font-bold text-white shadow-xs"+ title={`${m.name || "Member"} (${m.role || "member"})`}+ >+ {(m.name || "U")[0].toUpperCase()}+ </div>+ ))}+ </div>++ <button+ type="button"+ onClick={() => {+ fetchMembers();+ setShowMemberModal(true);+ }}+ className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-zinc-100 hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700 text-zinc-700 dark:text-zinc-300 text-xs font-medium transition-colors cursor-pointer"+ >+ <LuUserPlus className="w-3.5 h-3.5 text-indigo-500" />+ <span>Invite & Members ({members.length || space?.members?.length || 1})</span>+ </button>+ </div></div><button@@ -112,189 +285,372 @@ export default function SpaceLibrary({</button></div>- {/* Toolbar: Search, Sort, View Toggle (modeled on OpenDots library-tools) */}- <div className="flex flex-wrap items-center justify-between gap-3">- <div className="flex items-center gap-2 flex-1 max-w-md">- <div className="relative w-full">- <SearchIcon className="w-4 h-4 text-zinc-400 absolute left-3 top-2.5" />- <input- type="text"- placeholder="Search pages in this space..."- value={query}- onChange={(e) => setQuery(e.target.value)}- className="w-full bg-white dark:bg-[#1a1a20] border border-zinc-200 dark:border-zinc-800 rounded-xl pl-9 pr-3 py-2 text-xs text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:border-zinc-400 dark:focus:border-zinc-600 transition-colors shadow-2xs"- />+ {/* View Switcher Tabs: Pages vs Activity Feed */}+ <div className="flex items-center justify-between border-b border-zinc-200/80 dark:border-zinc-800/80 pb-2">+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => setActiveTab("pages")}+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors cursor-pointer ${+ activeTab === "pages"+ ? "bg-zinc-900 text-white dark:bg-white dark:text-zinc-900 shadow-2xs"+ : "text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200"+ }`}+ >+ <PageIcon className="w-3.5 h-3.5" />+ <span>Pages ({filtered.length})</span>+ </button>+ <button+ type="button"+ onClick={() => setActiveTab("activity")}+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors cursor-pointer ${+ activeTab === "activity"+ ? "bg-zinc-900 text-white dark:bg-white dark:text-zinc-900 shadow-2xs"+ : "text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200"+ }`}+ >+ <LuActivity className="w-3.5 h-3.5 text-indigo-500" />+ <span>Activity Log</span>+ </button>+ </div>+ </div>++ {activeTab === "pages" ? (+ <>+ {/* Toolbar: Search, Sort, View Toggle */}+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex items-center gap-2 flex-1 max-w-md">+ <div className="relative w-full">+ <SearchIcon className="w-4 h-4 text-zinc-400 absolute left-3 top-2.5" />+ <input+ type="text"+ placeholder="Search pages in this space..."+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ className="w-full bg-white dark:bg-[#1a1a20] border border-zinc-200 dark:border-zinc-800 rounded-xl pl-9 pr-3 py-2 text-xs text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:border-zinc-400 dark:focus:border-zinc-600 transition-colors shadow-2xs"+ />+ </div>+ </div>++ <div className="flex items-center gap-2 shrink-0">+ <CustomDropdown+ value={sort}+ onChange={setSort}+ options={SORT_OPTIONS}+ size="sm"+ buttonClassName="bg-white dark:bg-[#1a1a20] border-zinc-200 dark:border-zinc-800 text-zinc-700 dark:text-zinc-300 py-1.5 px-3 rounded-xl shadow-2xs text-xs"+ align="right"+ />++ <div className="flex items-center bg-zinc-100 dark:bg-zinc-800 p-0.5 rounded-xl border border-zinc-200 dark:border-zinc-700/80">+ <button+ type="button"+ onClick={() => setLayout("grid")}+ title="Grid view"+ className={`p-1.5 rounded-lg transition-colors cursor-pointer ${+ layout === "grid"+ ? "bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-2xs"+ : "text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200"+ }`}+ >+ <GridIcon className="w-4 h-4" />+ </button>+ <button+ type="button"+ onClick={() => setLayout("list")}+ title="List view"+ className={`p-1.5 rounded-lg transition-colors cursor-pointer ${+ layout === "list"+ ? "bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-2xs"+ : "text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200"+ }`}+ >+ <ListIcon className="w-4 h-4" />+ </button>+ </div>+ </div></div>++ {/* Pages Grid or List */}+ {filtered.length > 0 ? (+ layout === "grid" ? (+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">+ {filtered.map((page) => (+ <div+ key={page.id}+ onClick={() => onSelectPage(page.id)}+ className="group relative flex flex-col justify-between p-4 rounded-2xl bg-white dark:bg-[#1a1a20] border border-zinc-200/90 dark:border-zinc-800 hover:border-zinc-300 dark:hover:border-zinc-700 transition-all hover:shadow-md cursor-pointer select-none text-left"+ >+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <span className="w-8 h-8 rounded-xl bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 flex items-center justify-center text-sm font-semibold">+ {page.icon || "π"}+ </span>+ <ArrowUpRightIcon className="w-4 h-4 text-zinc-400 group-hover:text-zinc-900 dark:group-hover:text-zinc-100 transition-colors opacity-0 group-hover:opacity-100" />+ </div>++ <h3 className="font-semibold text-sm text-zinc-900 dark:text-zinc-100 tracking-tight line-clamp-1">+ {page.title || "Untitled page"}+ </h3>++ <p className="text-xs text-zinc-500 dark:text-zinc-400 line-clamp-2 leading-relaxed">+ {pageExcerpt(page.content) ||+ "An empty page, ready to write and edit."}+ </p>+ </div>++ <div className="flex items-center justify-between pt-3 mt-3 border-t border-zinc-100 dark:border-zinc-800/80 text-[11px] text-zinc-400">+ <span>Edited {formatDate(page.updated_at)}</span>++ {onDeletePage && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onDeletePage(page.id);+ }}+ title="Delete page"+ className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-red-500 transition-opacity cursor-pointer"+ >+ <TrashIcon className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ </div>+ ))}+ </div>+ ) : (+ <div className="bg-white dark:bg-[#1a1a20] border border-zinc-200/90 dark:border-zinc-800 rounded-2xl overflow-hidden divide-y divide-zinc-100 dark:divide-zinc-800">+ {filtered.map((page) => (+ <div+ key={page.id}+ onClick={() => onSelectPage(page.id)}+ className="group flex items-center justify-between p-3.5 hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer text-xs"+ >+ <div className="flex items-center gap-3 min-w-0 flex-1 pr-4">+ <span className="w-7 h-7 rounded-lg bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center text-sm shrink-0">+ {page.icon || "π"}+ </span>+ <div className="min-w-0">+ <div className="font-semibold text-zinc-900 dark:text-zinc-100 truncate">+ {page.title || "Untitled page"}+ </div>+ <div className="text-zinc-400 truncate text-[11px]">+ {pageExcerpt(page.content) || "No additional text"}+ </div>+ </div>+ </div>++ <div className="flex items-center gap-3 shrink-0 text-zinc-400 text-[11px]">+ <span>Edited {formatDate(page.updated_at)}</span>+ <ArrowUpRightIcon className="w-3.5 h-3.5 text-zinc-400 group-hover:text-zinc-900 dark:group-hover:text-zinc-100 opacity-0 group-hover:opacity-100 transition-opacity" />+ {onDeletePage && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onDeletePage(page.id);+ }}+ title="Delete page"+ className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-400 hover:text-red-500 transition-opacity cursor-pointer"+ >+ <TrashIcon className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ </div>+ ))}+ </div>+ )+ ) : (+ <div className="p-12 text-center border border-dashed border-zinc-300 dark:border-zinc-800 rounded-3xl bg-zinc-50/50 dark:bg-[#18181c]/50">+ <div className="w-12 h-12 rounded-2xl bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center mx-auto mb-3 text-zinc-400">+ <PageIcon className="w-6 h-6" />+ </div>+ <h2 className="text-base font-semibold text-zinc-900 dark:text-zinc-100">+ {query ? "No matching pages found" : "No pages in this Space yet"}+ </h2>+ <p className="text-xs text-zinc-500 dark:text-zinc-400 mt-1 max-w-sm mx-auto leading-relaxed">+ {query+ ? "Try searching for a different title or keyword."+ : "Create your first page to start writing, organizing research, and collaborating with Dot agents."}+ </p>+ {!query && (+ <button+ onClick={onNewPage}+ className="mt-4 inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-xs font-medium shadow-xs hover:opacity-90 transition-opacity cursor-pointer"+ >+ <PlusIcon className="w-3.5 h-3.5" />+ <span>Create page</span>+ </button>+ )}+ </div>+ )}+ </>+ ) : (+ /* Activity Feed View */+ <div className="space-y-3">+ {isLoadingActivities ? (+ <div className="flex flex-col items-center justify-center py-12 text-zinc-400 gap-2">+ <div className="w-5 h-5 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />+ <span className="text-xs">Loading activity timeline...</span>+ </div>+ ) : activities.length === 0 ? (+ <div className="p-12 text-center border border-dashed border-zinc-300 dark:border-zinc-800 rounded-3xl text-xs text-zinc-400">+ <LuActivity className="w-6 h-6 mx-auto mb-2 text-zinc-400" />+ <p className="font-semibold text-zinc-700 dark:text-zinc-300">No activity logged yet.</p>+ <p className="mt-1">Edits, new members, and page updates will appear here.</p>+ </div>+ ) : (+ <div className="bg-white dark:bg-[#1a1a20] border border-zinc-200/90 dark:border-zinc-800 rounded-2xl divide-y divide-zinc-100 dark:divide-zinc-800 p-2">+ {activities.map((act) => (+ <div key={act.id} className="p-3 flex items-start gap-3">+ <div className="w-7 h-7 rounded-lg bg-indigo-50 dark:bg-indigo-950/40 text-indigo-600 dark:text-indigo-400 flex items-center justify-center text-xs shrink-0 mt-0.5">+ <LuActivity className="w-3.5 h-3.5" />+ </div>+ <div className="flex-1 min-w-0">+ <div className="text-xs text-zinc-900 dark:text-zinc-100 font-medium">+ {act.summary}+ </div>+ <div className="text-[10px] text-zinc-400 mt-0.5">+ {new Date(act.created_at).toLocaleString([], {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ })}+ </div>+ </div>+ </div>+ ))}+ </div>+ )}</div>+ )}+ </div>- <div className="flex items-center gap-2 shrink-0">- {/* Sort selector */}- <CustomDropdown- value={sort}- onChange={setSort}- options={SORT_OPTIONS}- size="sm"- buttonClassName="bg-white dark:bg-[#1a1a20] border-zinc-200 dark:border-zinc-800 text-zinc-700 dark:text-zinc-300 py-1.5 px-3 rounded-xl shadow-2xs text-xs"- align="right"- />-- {/* Grid / List view toggle */}- <div className="flex items-center bg-zinc-100 dark:bg-zinc-800 p-0.5 rounded-xl border border-zinc-200 dark:border-zinc-700/80">- <button- type="button"- onClick={() => setLayout("grid")}- title="Grid view"- className={`p-1.5 rounded-lg transition-colors cursor-pointer ${- layout === "grid"- ? "bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-2xs"- : "text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200"- }`}- >- <GridIcon className="w-4 h-4" />- </button>+ {/* Invite & Members Modal */}+ {showMemberModal && (+ <div className="fixed inset-0 z-50 bg-black/40 backdrop-blur-2xs flex items-center justify-center p-4 animate-in fade-in">+ <div+ onClick={(e) => e.stopPropagation()}+ className="bg-white dark:bg-[#18181c] border border-zinc-200 dark:border-zinc-800 rounded-2xl w-full max-w-lg p-6 shadow-2xl space-y-5 animate-in zoom-in-95 duration-100"+ >+ <div className="flex items-center justify-between pb-3 border-b border-zinc-200 dark:border-zinc-800">+ <div className="flex items-center gap-2">+ <LuUsers className="w-5 h-5 text-indigo-500" />+ <h3 className="font-semibold text-base text-zinc-900 dark:text-zinc-100">+ Space Members & Permissions+ </h3>+ </div><buttontype="button"- onClick={() => setLayout("list")}- title="List view"- className={`p-1.5 rounded-lg transition-colors cursor-pointer ${- layout === "list"- ? "bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-2xs"- : "text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200"- }`}+ onClick={() => setShowMemberModal(false)}+ className="p-1 rounded-lg text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 cursor-pointer">- <ListIcon className="w-4 h-4" />+ <CloseIcon className="w-4 h-4" /></button></div>- </div>- </div>- {/* Section label & count */}- <div className="flex items-center justify-between text-xs text-zinc-400 font-medium px-1">- <span>{query ? "Search results" : "All documents"}</span>- <span>- {filtered.length} {filtered.length === 1 ? "page" : "pages"}- </span>- </div>-- {/* Pages Grid or List */}- {filtered.length > 0 ? (- layout === "grid" ? (- /* Grid View Cards */- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">- {filtered.map((page) => (- <div- key={page.id}- onClick={() => onSelectPage(page.id)}- className="group relative flex flex-col justify-between p-4 rounded-2xl bg-white dark:bg-[#1a1a20] border border-zinc-200/90 dark:border-zinc-800 hover:border-zinc-300 dark:hover:border-zinc-700 transition-all hover:shadow-md cursor-pointer select-none text-left"+ {/* Invite by Email Form */}+ <form onSubmit={handleInviteSubmit} className="space-y-3">+ <label className="block text-xs font-semibold text-zinc-700 dark:text-zinc-300">+ Invite teammate by email+ </label>+ <div className="flex gap-2">+ <input+ type="email"+ required+ placeholder="[email protected]"+ value={inviteEmail}+ onChange={(e) => setInviteEmail(e.target.value)}+ className="flex-1 bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-xl px-3 py-2 text-xs text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:border-indigo-500 shadow-2xs"+ />+ <CustomDropdown+ value={inviteRole}+ onChange={setInviteRole}+ options={[+ { label: "Editor", value: "editor", description: "Can edit and create pages" },+ { label: "Commenter", value: "commenter", description: "Can comment and discuss" },+ { label: "Viewer", value: "viewer", description: "Read-only access" },+ ]}+ size="md"+ buttonClassName="bg-white dark:bg-zinc-900 border-zinc-300 dark:border-zinc-700 rounded-xl px-3 py-2 text-xs"+ />+ <button+ type="submit"+ disabled={isInviting || !inviteEmail.trim()}+ className="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-medium text-xs shadow-xs transition-colors disabled:opacity-50 cursor-pointer">- <div className="space-y-2">- <div className="flex items-center justify-between">- <span className="w-8 h-8 rounded-xl bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 flex items-center justify-center text-sm font-semibold">- {page.icon || "π"}- </span>- <ArrowUpRightIcon className="w-4 h-4 text-zinc-400 group-hover:text-zinc-900 dark:group-hover:text-zinc-100 transition-colors opacity-0 group-hover:opacity-100" />- </div>+ {isInviting ? "Inviting..." : "Invite"}+ </button>+ </div>- <h3 className="font-semibold text-sm text-zinc-900 dark:text-zinc-100 tracking-tight line-clamp-1">- {page.title || "Untitled page"}- </h3>+ {inviteNotice && (+ <p className="text-xs text-indigo-600 dark:text-indigo-400 font-medium">+ {inviteNotice}+ </p>+ )}+ </form>- <p className="text-xs text-zinc-500 dark:text-zinc-400 line-clamp-2 leading-relaxed">- {pageExcerpt(page.content) ||- "An empty page, ready to write and edit."}- </p>- </div>-- <div className="flex items-center justify-between pt-3 mt-3 border-t border-zinc-100 dark:border-zinc-800/80 text-[11px] text-zinc-400">- <span>Edited {formatDate(page.updated_at)}</span>-- {onDeletePage && (- <button- type="button"- onClick={(e) => {- e.stopPropagation();- onDeletePage(page.id);- }}- title="Delete page"- className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-red-500 transition-opacity"- >- <TrashIcon className="w-3.5 h-3.5" />- </button>- )}- </div>- </div>- ))}- </div>- ) : (- /* List View Rows */- <div className="bg-white dark:bg-[#1a1a20] border border-zinc-200/90 dark:border-zinc-800 rounded-2xl overflow-hidden divide-y divide-zinc-100 dark:divide-zinc-800">- {filtered.map((page) => (- <div- key={page.id}- onClick={() => onSelectPage(page.id)}- className="group flex items-center justify-between p-3.5 hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer text-xs"- >- <div className="flex items-center gap-3 min-w-0 flex-1 pr-4">- <span className="w-7 h-7 rounded-lg bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center text-sm shrink-0">- {page.icon || "π"}- </span>- <div className="min-w-0">- <div className="font-semibold text-zinc-900 dark:text-zinc-100 truncate">- {page.title || "Untitled page"}+ {/* Current Members List */}+ <div className="space-y-2 pt-2">+ <span className="text-xs font-semibold text-zinc-600 dark:text-zinc-400">+ Current Members ({members.length})+ </span>+ <div className="max-h-56 overflow-y-auto divide-y divide-zinc-100 dark:divide-zinc-800 border border-zinc-200 dark:border-zinc-800 rounded-xl p-1">+ {members.map((m) => (+ <div key={m.id || m.user_id} className="p-2.5 flex items-center justify-between">+ <div className="flex items-center gap-2.5">+ <div className="w-7 h-7 rounded-full bg-gradient-to-tr from-indigo-500 to-violet-500 flex items-center justify-center text-xs font-bold text-white shadow-2xs">+ {(m.name || "U")[0].toUpperCase()}</div>- <div className="text-zinc-400 truncate text-[11px]">- {pageExcerpt(page.content) || "No additional text"}+ <div>+ <div className="text-xs font-medium text-zinc-900 dark:text-zinc-100">+ {m.name}+ </div>+ <div className="text-[10px] text-zinc-400">{m.email}</div></div></div>- </div>- <div className="flex items-center gap-3 shrink-0 text-zinc-400 text-[11px]">- <span>Edited {formatDate(page.updated_at)}</span>- <ArrowUpRightIcon className="w-3.5 h-3.5 text-zinc-400 group-hover:text-zinc-900 dark:group-hover:text-zinc-100 opacity-0 group-hover:opacity-100 transition-opacity" />- {onDeletePage && (- <button- type="button"- onClick={(e) => {- e.stopPropagation();- onDeletePage(page.id);- }}- title="Delete page"- className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-400 hover:text-red-500 transition-opacity"- >- <TrashIcon className="w-3.5 h-3.5" />- </button>- )}+ <div className="flex items-center gap-2">+ {m.role === "owner" ? (+ <span className="text-[10px] uppercase font-bold tracking-wider px-2 py-0.5 rounded-full bg-amber-100 dark:bg-amber-950/60 text-amber-800 dark:text-amber-300">+ Owner+ </span>+ ) : (+ <CustomDropdown+ value={m.role}+ onChange={(newRole) => handleUpdateMemberRole(m.user_id, newRole)}+ options={[+ { label: "Editor", value: "editor" },+ { label: "Commenter", value: "commenter" },+ { label: "Viewer", value: "viewer" },+ ]}+ size="xs"+ align="right"+ buttonClassName="bg-zinc-100 dark:bg-zinc-800/80 border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 rounded-md"+ />+ )}++ {m.role !== "owner" && (+ <button+ type="button"+ onClick={() => handleRemoveMember(m.user_id)}+ className="p-1 rounded hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-red-500 transition-colors cursor-pointer"+ title="Remove member"+ >+ <TrashIcon className="w-3.5 h-3.5" />+ </button>+ )}+ </div></div>- </div>- ))}+ ))}+ </div></div>- )- ) : (- /* Empty State (modeled on OpenDots library-empty) */- <div className="p-12 text-center border border-dashed border-zinc-300 dark:border-zinc-800 rounded-3xl bg-zinc-50/50 dark:bg-[#18181c]/50">- <div className="w-12 h-12 rounded-2xl bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center mx-auto mb-3 text-zinc-400">- <PageIcon className="w-6 h-6" />- </div>- <h2 className="text-base font-semibold text-zinc-900 dark:text-zinc-100">- {query ? "No matching pages found" : "No pages in this Space yet"}- </h2>- <p className="text-xs text-zinc-500 dark:text-zinc-400 mt-1 max-w-sm mx-auto leading-relaxed">- {query- ? "Try searching for a different title or keyword."- : "Create your first page to start writing, organizing research, and collaborating with Dot agents."}- </p>- {!query && (- <button- onClick={onNewPage}- className="mt-4 inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-xs font-medium shadow-xs hover:opacity-90 transition-opacity"- >- <PlusIcon className="w-3.5 h-3.5" />- <span>Create page</span>- </button>- )}</div>- )}- </div>+ </div>+ )}</div>);}diff --git a/client/src/components/SpaceSidebar.js b/client/src/components/SpaceSidebar.jsindex 2cf8f85..5778133 100644--- a/client/src/components/SpaceSidebar.js+++ b/client/src/components/SpaceSidebar.js@@ -4,15 +4,34 @@ import React, { useState } from "react";import {SearchIcon,NewPageIcon,- PageIcon,FolderIcon,ChevronDownIcon,ChevronRightIcon,PlusIcon,- CloseIcon,TrashIcon,} from "./Icons";import ThemeToggle from "./ThemeToggle";+import CustomDropdown from "./CustomDropdown";++const ICON_OPTIONS = [+ { label: "π Folder", value: "π" },+ { label: "π Launch", value: "π" },+ { label: "π§ Research", value: "π§ " },+ { label: "π‘ Ideation", value: "π‘" },+ { label: "β‘ Fast", value: "β‘" },+ { label: "π¨ Design", value: "π¨" },+ { label: "π Analytics", value: "π" },+ { label: "π‘οΈ Security", value: "π‘οΈ" },+];++const COLOR_OPTIONS = [+ { label: "Indigo", value: "indigo" },+ { label: "Emerald", value: "emerald" },+ { label: "Amber", value: "amber" },+ { label: "Rose", value: "rose" },+ { label: "Sky", value: "sky" },+ { label: "Purple", value: "purple" },+];export default function SpaceSidebar({spaces = [],@@ -24,15 +43,27 @@ export default function SpaceSidebar({activePageId,onSelectPage,onCreatePage,+ onDeletePage,isCreatingPage = false,}) {const [showNewSpaceModal, setShowNewSpaceModal] = useState(false);const [newSpaceName, setNewSpaceName] = useState("");const [newSpaceDesc, setNewSpaceDesc] = useState("");+ const [newSpaceIcon, setNewSpaceIcon] = useState("π");+ const [newSpaceColor, setNewSpaceColor] = useState("indigo");const [searchQuery, setSearchQuery] = useState("");const [expandedSpaces, setExpandedSpaces] = useState({[activeSpaceId]: true,});+ const [expandedPages, setExpandedPages] = useState({});++ const togglePageExpand = (pageId, e) => {+ if (e) e.stopPropagation();+ setExpandedPages((prev) => ({+ ...prev,+ [pageId]: prev[pageId] === undefined ? false : !prev[pageId],+ }));+ };const toggleSpaceExpand = (spaceId, e) => {if (e) e.stopPropagation();@@ -48,11 +79,13 @@ export default function SpaceSidebar({onCreateSpace({name: newSpaceName.trim(),description: newSpaceDesc.trim(),- icon: "π",- color: "indigo",+ icon: newSpaceIcon,+ color: newSpaceColor,});setNewSpaceName("");setNewSpaceDesc("");+ setNewSpaceIcon("π");+ setNewSpaceColor("indigo");setShowNewSpaceModal(false);};@@ -175,34 +208,102 @@ export default function SpaceSidebar({)}</div>- {/* Nested Pages for this Space (OpenDots branches view) */}+ {/* Nested Pages for this Space (Hierarchical Tree View) */}{isExpanded && (- <div className="pl-6 pr-1 space-y-0.5 border-l border-zinc-200 dark:border-zinc-800 ml-3">+ <div className="pl-1 pr-1 space-y-0.5 border-l border-zinc-200 dark:border-zinc-800 ml-3">{isSpaceActive && matchingPages.length > 0 ? (- matchingPages.map((page) => {- const isPageSelected = activePageId === page.id;- return (- <button- key={page.id}- onClick={() => {- onSelectSpace(space.id);- onSelectPage(page.id);- }}- className={`w-full flex items-center gap-1.5 px-2 py-1 rounded-md text-xs text-left transition-colors truncate cursor-pointer ${- isPageSelected- ? "bg-zinc-200/90 dark:bg-zinc-700 text-zinc-900 dark:text-zinc-100 font-medium"- : "text-zinc-600 dark:text-zinc-400 hover:bg-zinc-200/40 dark:hover:bg-zinc-800/40 hover:text-zinc-900 dark:hover:text-zinc-200"- }`}- >- <span className="text-xs shrink-0">- {page.icon || "π"}- </span>- <span className="truncate">- {page.title || "Untitled"}- </span>- </button>- );- })+ (() => {+ const pageIdSet = new Set(matchingPages.map((p) => p.id));+ const renderTree = (parentId = null, depth = 0) => {+ const levelPages = matchingPages.filter((p) => {+ if (parentId === null) {+ return !p.parent_id || !pageIdSet.has(p.parent_id);+ }+ return p.parent_id === parentId;+ });++ return levelPages.map((page) => {+ const isPageSelected = activePageId === page.id;+ const children = matchingPages.filter((c) => c.parent_id === page.id);+ const hasChildren = children.length > 0;+ const isPageExpanded = expandedPages[page.id] ?? true;++ return (+ <div key={page.id} className="space-y-0.5">+ <div+ className={`group/page flex items-center justify-between py-1 px-1.5 rounded-md text-xs transition-colors cursor-pointer ${+ isPageSelected+ ? "bg-zinc-200/90 dark:bg-zinc-700 text-zinc-900 dark:text-zinc-100 font-medium"+ : "text-zinc-600 dark:text-zinc-400 hover:bg-zinc-200/40 dark:hover:bg-zinc-800/40 hover:text-zinc-900 dark:hover:text-zinc-200"+ }`}+ style={{ paddingLeft: `${4 + depth * 12}px` }}+ onClick={() => {+ onSelectSpace(space.id);+ onSelectPage(page.id);+ }}+ >+ <div className="flex items-center gap-1.5 min-w-0 flex-1">+ {hasChildren ? (+ <button+ type="button"+ onClick={(e) => togglePageExpand(page.id, e)}+ className="p-0.5 rounded hover:bg-zinc-300/50 dark:hover:bg-zinc-600 text-zinc-400 shrink-0"+ title={isPageExpanded ? "Collapse sub-pages" : "Expand sub-pages"}+ >+ {isPageExpanded ? (+ <ChevronDownIcon className="w-2.5 h-2.5" />+ ) : (+ <ChevronRightIcon className="w-2.5 h-2.5" />+ )}+ </button>+ ) : (+ <span className="w-2.5 shrink-0" />+ )}+ <span className="text-xs shrink-0">{page.icon || "π"}</span>+ <span className="truncate">{page.title || "Untitled"}</span>+ </div>++ <div className="flex items-center gap-0.5 opacity-0 group-hover/page:opacity-100 transition-opacity shrink-0">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onCreatePage({+ title: "Untitled sub-page",+ content: "",+ parent_id: page.id,+ });+ setExpandedPages((prev) => ({ ...prev, [page.id]: true }));+ }}+ title="Add sub-page"+ className="p-0.5 rounded hover:bg-zinc-300/60 dark:hover:bg-zinc-600 text-zinc-400 hover:text-indigo-600 dark:hover:text-indigo-400"+ >+ <PlusIcon className="w-3 h-3" />+ </button>+ {onDeletePage && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onDeletePage(page.id);+ }}+ title="Delete page"+ className="p-0.5 rounded hover:bg-zinc-300/60 dark:hover:bg-zinc-600 text-zinc-400 hover:text-red-500"+ >+ <TrashIcon className="w-3 h-3" />+ </button>+ )}+ </div>+ </div>++ {hasChildren && isPageExpanded && renderTree(page.id, depth + 1)}+ </div>+ );+ });+ };++ return renderTree(null, 0);+ })()) : (<div className="text-[11px] text-zinc-400 px-2 py-1 italic">No pages yet@@ -265,6 +366,33 @@ export default function SpaceSidebar({/></div>+ <div className="grid grid-cols-2 gap-2.5">+ <div>+ <label className="block text-[11px] font-medium text-zinc-500 mb-1">+ Icon+ </label>+ <CustomDropdown+ value={newSpaceIcon}+ onChange={setNewSpaceIcon}+ options={ICON_OPTIONS}+ className="w-full"+ buttonClassName="w-full justify-between bg-zinc-50 dark:bg-zinc-900 border-zinc-300 dark:border-zinc-700 rounded-xl"+ />+ </div>+ <div>+ <label className="block text-[11px] font-medium text-zinc-500 mb-1">+ Theme Color+ </label>+ <CustomDropdown+ value={newSpaceColor}+ onChange={setNewSpaceColor}+ options={COLOR_OPTIONS}+ className="w-full"+ buttonClassName="w-full justify-between bg-zinc-50 dark:bg-zinc-900 border-zinc-300 dark:border-zinc-700 rounded-xl"+ />+ </div>+ </div>+<div className="flex justify-end gap-2 pt-1"><buttontype="button"diff --git a/client/src/components/editor/AiImageView.js b/client/src/components/editor/AiImageView.jsindex db9847d..936394b 100644--- a/client/src/components/editor/AiImageView.js+++ b/client/src/components/editor/AiImageView.js@@ -12,10 +12,22 @@ import {LuRefreshCw,LuWand,} from "react-icons/lu";+import CustomDropdown from "../CustomDropdown";const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8000/api";-const ASPECT_RATIOS = ["1:1", "16:9", "4:3"];+const ASPECT_RATIO_OPTIONS = [+ { label: "1:1 Square", value: "1:1" },+ { label: "16:9 Landscape", value: "16:9" },+ { label: "9:16 Portrait", value: "9:16" },+ { label: "4:3 Classic", value: "4:3" },+];++const RESOLUTION_OPTIONS = [+ { label: "2K High Res", value: "2K" },+ { label: "4K Ultra HD", value: "4K" },+ { label: "1K Preview", value: "1K" },+];const QUICK_IMAGE_CHIPS = [{ label: "Concept illustration", prompt: "A sleek conceptual editorial 3D illustration with glowing soft lighting" },@@ -26,6 +38,7 @@ const QUICK_IMAGE_CHIPS = [export function AiImageComponent({ editor, node, getPos, deleteNode }) {const [promptText, setPromptText] = useState("");const [aspectRatio, setAspectRatio] = useState("1:1");+ const [resolution, setResolution] = useState("2K");const [loading, setLoading] = useState(false);const [analyzingContext, setAnalyzingContext] = useState(false);const [statusMsg, setStatusMsg] = useState("");@@ -130,6 +143,7 @@ export function AiImageComponent({ editor, node, getPos, deleteNode }) {body: JSON.stringify({prompt: activePrompt,aspect_ratio: aspectRatio,+ resolution: resolution,model: "gpt-image-2-text-to-image",}),});@@ -209,7 +223,7 @@ export function AiImageComponent({ editor, node, getPos, deleteNode }) {setLoading(false);}},- [promptText, aspectRatio, loading, editor, getPos, node, deleteNode]+ [promptText, aspectRatio, resolution, loading, editor, getPos, node, deleteNode]);return (@@ -320,23 +334,22 @@ export function AiImageComponent({ editor, node, getPos, deleteNode }) {{/* Controls: Aspect Ratio + Quick Chips */}<div className="flex items-center justify-between flex-wrap gap-1.5 pt-0.5">- {/* Aspect Ratio Selector */}- <div className="flex items-center gap-1">- <span className="text-[10px] text-zinc-400 dark:text-zinc-500">Ratio:</span>- {ASPECT_RATIOS.map((ratio) => (- <button- key={ratio}- type="button"- onClick={() => setAspectRatio(ratio)}- className={`px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors ${- aspectRatio === ratio- ? "bg-purple-600 text-white font-semibold"- : "bg-zinc-100 dark:bg-zinc-800 text-zinc-500 dark:text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200"- }`}- >- {ratio}- </button>- ))}+ {/* Custom Dropdowns for Aspect Ratio & Resolution */}+ <div className="flex items-center gap-1.5">+ <CustomDropdown+ value={aspectRatio}+ onChange={setAspectRatio}+ options={ASPECT_RATIO_OPTIONS}+ size="xs"+ buttonClassName="bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 rounded-md py-0.5 px-2 text-[10px]"+ />+ <CustomDropdown+ value={resolution}+ onChange={setResolution}+ options={RESOLUTION_OPTIONS}+ size="xs"+ buttonClassName="bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 rounded-md py-0.5 px-2 text-[10px]"+ /></div>{/* Quick style inspiration */}diff --git a/open_spaces_comparative_review_2026-10-06.md b/open_spaces_comparative_review_2026-10-06.mdnew file mode 100644index 0000000..d96733b--- /dev/null+++ b/open_spaces_comparative_review_2026-10-06.md@@ -0,0 +1,185 @@+# OpenSpaces comparative code review and plan++**Reviewed:** 2026-10-06+**Scope:** `SamurAIGPT/open-spaces` current `main`; `CopilotKit/OpenDots` current `main`; current public product/help documentation for ChatGPT Space and Notion. This is a source and documentation review, not a deployment audit or runtime verification.++## Executive summary++OpenSpaces has a useful foundation: a TipTap-based page editor, space/page/message persistence, autosave, and MuAPI text and image integrations. Several README claims currently describe intended behavior rather than implemented behavior. In particular, multi-user collaboration has no access control, the WebSocket is an unused unauthenticated relay, agent execution and meeting transcription are simulations, and page versions do not prevent stale writes.++OpenDots is a useful implementation reference for nested pages, optimistic concurrency, draft preservation, scoped agent access, page-specific conversations, and approval before saving agent-created pages. It is deliberately single-owner and does not provide team collaboration or file uploads.++ChatGPT Space is the closer product reference for shared pages, files, teammates, comments, and real-time editing. Notion is the broader workspace reference: teamspaces and granular permissions, docs and databases, connected-source search with citations, real meeting transcription, and scheduled or event-triggered agents.++Recommended sequence: **secure the baseline β make page editing safe β add real sharing/collaboration β make AI runs trustworthy β implement meetings/files β selectively expand integrations and structured workspace features.**++## Sources and review boundaries++### Repositories reviewed++- [SamurAIGPT/open-spaces](https://github.com/SamurAIGPT/open-spaces)+- [CopilotKit/OpenDots](https://github.com/CopilotKit/OpenDots)+- OpenDots [setup and page behavior](https://github.com/CopilotKit/OpenDots/blob/main/docs/SETUP.md)+- OpenDots [security boundary](https://github.com/CopilotKit/OpenDots/blob/main/SECURITY.md)++### Product documentation reviewed++- [ChatGPT Space](https://chatgpt.com/features/space/?openaicom_referred=true)+- Notion [product features](https://www.notion.com/product/features)+- Notion [teamspaces](https://www.notion.com/help/guides/teamspaces-give-teams-home)+- Notion [sharing and permissions](https://www.notion.com/help/sharing-and-permissions)+- Notion [Enterprise Search](https://www.notion.com/help/enterprise-search)+- Notion [Custom Agents](https://www.notion.com/help/custom-agents)+- Notion [AI Meeting Notes](https://www.notion.com/help/ai-meeting-notes)++ChatGPT Space's public page describes real-time collaboration, comments, team sharing, files, shared context and page instructions; it marks collaborative slides and spreadsheets as coming soon. Notion capabilities and plan availability can vary, so recheck product docs before making dated parity claims.++## OpenSpaces code review++### Implemented foundation++- Next.js client and FastAPI API, with SQLAlchemy persistence configured for PostgreSQL/Supabase.+- CRUD and persistence for spaces, pages, messages and meeting-note records.+- TipTap editor with Markdown source mode, slash commands, inline text/image generation, and debounced autosave.+- Page version integer incremented on every page update.+- MuAPI-backed chat and image routes.++### Gaps between claims and implementation++| Area | Current implementation | Consequence |+|---|---|---|+| Identity and authorization | Reviewed routes do not authenticate users or check space membership. Membership is stored as JSON/static seed data; creating a Space assigns a fixed `usr-1` owner. | Any reachable API client can attempt reads and mutations. This is a release blocker for multi-user or public deployment. |+| WebSocket collaboration | `/ws/spaces/{space_id}` accepts based on the URL identifier and relays arbitrary received JSON to connections. It does not authenticate, authorize, validate event schemas, persist changes, or implement document operations. No client use was found in the frontend source. | It is not collaborative editing and can expose a room to unauthorized clients. |+| Page concurrency | The API increments `version` but does not require a client expected-version value. There is no revision-history table or restore endpoint. | Concurrent saves can silently overwrite one another; a version number alone does not prevent it. |+| Nested pages | Page schema/model has no parent-page relationship. | No document hierarchy or safe move behavior. |+| Dot agents | The run endpoint waits and appends placeholder text, then posts a completion message. Agent identities/capabilities are seeded, with no full configure/manage workflow. | βAutonomousβ work is not actually executed; completion status is misleading. |+| Meetings | The recording UI runs a timer and then submits hard-coded transcript, summary and action items. | No real audio capture, upload or transcription. |+| Chat errors | A failed MuAPI request can return fabricated fallback text as a normal response. | Users cannot distinguish generated answers from provider failures. |+| Image generation | Request handler polls in an unbounded loop until completion. | Long-running generation occupies the request and has no durable job state the user can revisit. |+| Files and connected context | No Space file persistence or integration-backed context workflow was found. | Space agents cannot use a managed, access-controlled collection of attached sources. |+| Collaboration features | No invite/member-management routes, page comments, granular access, or access-aware search were found. | UI language around shared team work exceeds the backend capability. |+| Configuration | `server/app/core/config.py` includes a database URL with embedded credentials as a default fallback. | Verify whether the credential is live; rotate it if so, remove it from source, and require deployment configuration. Do not copy the secret into issues or documentation. |++Relevant OpenSpaces files include `server/app/main.py`, `server/app/core/config.py`, `server/app/api/routers/{spaces,pages,agents,meetings,chat,images}.py`, `server/app/db/models.py`, `server/app/models/schemas.py`, `server/app/services/space_store.py`, and `client/src/components/{OpenSpacesApp,CanvasPage,SpaceChat,MeetingIntelligence}.js`.++### Additional implementation observations++- The WebSocket broadcasts back to all room connections, including the sender, despite the comment saying βother collaborators.β It also has no `finally` cleanup for non-disconnect failures.+- `members` are serialized from a JSON column rather than relational membership records, making constraints and authorization difficult to enforce.+- Message records are persisted, but there is no distinct conversation/thread model that establishes ownership, membership, or context boundaries.+- Image generation is synchronous from the caller's perspective and has no server-side job lifecycle, cancellation, or timeout policy.+- UI state and endpoint behavior should be kept in parity: seeded examples and fallback responses need clear demo-vs-production boundaries.++## OpenDots code review++OpenDots is an early, self-hosted, single-owner template. It should not be mistaken for a drop-in team collaboration implementation. Its strongest reusable patterns are in document integrity and agent scoping.++### Useful patterns to adopt++- Pages have `parentId`; server checks parent existence in the same Space and prevents cycles when moving pages.+- Page updates require `expectedRevision`; conflicts return a conflict response rather than silently overwriting newer content.+- Client autosave has explicit `saved`, `dirty`, `saving`, `error`, and `conflict` states. Failed writes preserve the draft; retries are explicit after errors.+- Page-specific conversations are bound to both page and specialist Dot. The current saved page is passed as context.+- Each Dot has explicit Space grants and separate research/memory permissions; server-side tools check those grants.+- Agent-created page content can require human review before saving. A persisted review receipt makes repeat saves idempotent.+- Scheduled work tracks tasks, runs, events, leases, pause/retry state, and result/error status in persistent storage.+- The repository includes focused tests for page services, autosave conflicts, scopes, scheduling, controls and security boundaries.++### OpenDots limitations to preserve in the comparison++- Its local app uses a single-owner identity model. Its own security guide says multi-user membership, Slack identity mapping, and voice delegation need more enforcement before connected multi-user deployment.+- No shared page editing, team invitations, file uploads or arbitrary interactive embeds are included.+- Page data lives locally in SQLite while conversation history lives in the configured Intelligence project; backups must cover both.+- Computer, Slack, calls, schedules, and learning depend on configured external services. The repo distinguishes local checks from live-service verification.++## Product comparison++| Capability | OpenSpaces | OpenDots | ChatGPT Space | Notion |+|---|---|---|---|---|+| Workspace organization | Spaces and flat page lists | Spaces with nested pages | Shared Spaces for team work | Teamspaces, pages, databases, docs and projects |+| Page editing | TipTap rich editor, Markdown and autosave | Rich editor, Markdown/source handling, nested pages, autosave | Editable pages, with AI assistance | Block-based docs and databases |+| Concurrent collaboration | WebSocket relay only; not wired into client | Not included | Product page describes real-time co-editing and comments | Product page describes real-time editing and comments |+| Permissions | Static member field; no enforced auth in reviewed routes | Single-owner boundary; per-Dot Space grants | Teammate/team sharing and page access levels | Open/closed/private teamspaces; page-level view/comment/edit/full access and inherited permissions |+| AI context | Chat endpoint and inline editor actions; no Space file corpus | Page-specific Dot conversation; scoped page tools | ChatGPT/Codex/dot use shared context; page instructions and connected sources | Workspace and connector search with citations; AI can work with pages/databases |+| Agent automation | Agent run is simulated | Specialist Dots, schedules, pause/retry, optional computer, review flow | Dots can work across Space and connected channels per product description | Custom Agents can use granted sources, schedules/events, and actions; access/activity controls are documented |+| Meetings | Static simulated transcript and summary | Calls and speech workflows, with some live-connected checks noted as incomplete | Not the core of the Space product page | Actual AI Meeting Notes transcription, summaries and action items; team sharing controls |+| Files/integrations | No Space file system/integrations found | File uploads are future work; Slack/calls/computers require setup | Shared files and connected context are part of product description | AI Connectors include services such as Slack, Drive, Jira, GitHub, email and calendars, subject to plans/setup |++Notion is a broader long-term benchmark than a Space clone: it combines documents with databases, projects, connectors, meeting capture and event-driven agents. Avoid taking on all of that before OpenSpaces has authorization and data-integrity fundamentals.++## Recommended implementation plan++### Phase 0 β Secure the baseline++1. Remove the source-coded database credential fallback. Require `DATABASE_URL`/`DIRECT_URL` from the environment and fail startup clearly when missing. Check credential validity privately and rotate if active.+2. Add verified user identity and server-side authorization to every Space, page, message, meeting, chat and agent route.+3. Replace JSON/static members and fixed `usr-1` with normalized users, memberships, roles and ownership.+4. Restrict CORS to configured origins. Authenticate and authorize WebSocket connections, or disable the unused endpoint until a real protocol is implemented.+5. Define owner/editor/commenter/viewer permissions and test enforcement at the API boundary.++**Exit criteria:** anonymous access fails; cross-Space reads/writes fail; membership revocation takes effect; WebSocket cannot join by guessing an ID; absent production secrets prevent startup.++### Phase 1 β Make pages safe to edit++1. Add page `parent_id`, ordering and safe move/cycle checks.+2. Require `expected_revision` for updates and return conflict status with the current revision on stale writes.+3. Adopt explicit autosave states and preserve local drafts on failure/conflict; provide βuse latestβ and recovery paths.+4. Add revision snapshots/history and restore with author and timestamp.+5. Define page content limits and safe Markdown/rich-text conversions.++**Exit criteria:** two clients cannot silently overwrite; stale changes are detectable; failed drafts remain recoverable; users can restore an earlier version.++### Phase 2 β Build real sharing and collaboration++1. Add invitations and membership lifecycle, with role changes and revocation.+2. Add page-level sharing only if Space-level permissions are insufficient for the target use case.+3. Add comments, mentions and activity history.+4. Pick an explicit collaboration model: CRDT/OT for simultaneous edits, or presence plus revision-checked saves as a smaller first step. Replace arbitrary WebSocket payload relay with typed, authenticated events.+5. Scope search results and page references by the caller's access.++**Exit criteria:** invited users see only authorized content; roles are enforced; concurrent edits have defined behavior; comments and activity identify real users.++### Phase 3 β Make AI actions trustworthy++1. Replace simulated agent execution with durable run/job records: queued, running, completed, failed, cancelled, progress, timestamps and retry state.+2. Configure each Dot with instructions, model and explicit Space/page/tool grants; verify grants on every server tool call.+3. Send only authorized page/file context and retain source links/citations for research.+4. Add review/approve/reject for page modifications and external write actions; make accepted operations idempotent.+5. Return structured provider errors instead of fabricated success text. Use bounded timeouts and appropriate retries.+6. Convert image generation to an asynchronous durable task with status polling or server events, cancellation and clear failure states.++**Exit criteria:** βcompletedβ means real execution completed; users can inspect failures and sources; tool grants are server-enforced; consequential edits can be reviewed and recovered.++### Phase 4 β Implement real meeting and file workflows++1. Implement actual microphone capture and/or audio/video upload, transcription, summary and action extraction.+2. Keep capture, transcription and synthesis as separate observable job states; retain/edit transcripts and outputs under clear retention rules.+3. Let users review action items before converting them into pages/tasks.+4. Add Space file storage, metadata, upload limits, supported formats and access checks.+5. Make AI context selection explicit and cite the files/pages used.++**Exit criteria:** meeting notes are derived from real audio; generated content is reviewable; uploads follow access/retention rules; AI answers identify source material.++### Phase 5 β Selectively expand toward Notion++1. Add connected-source search with citations, beginning with one high-value integration.+2. Add event-triggered and scheduled agents only with pause/disable controls, run logs, permissions and reversible actions.+3. Evaluate structured databases/collections if page-only organization is insufficient.+4. Add admin controls, export, retention, audit trails and mobile workflows based on deployment needs.++**Exit criteria:** each connector or trigger has explicit scopes, access-aware retrieval, observable runs and a recovery path.++## Priority and sequencing++**P0:** credential remediation and server-enforced authorization. Do not expose the current backend as a multi-user service before these are addressed.+**P1:** revision-checked page editing and real membership/invitations. These unlock safe collaboration.+**P2:** replace simulated agents and meeting UI; add durable job state and honest errors.+**P3:** comments, files and connected-source context.+**P4:** connectors, event-driven agents, database-like collections and enterprise controls.++OpenDots is the implementation reference for page conflict handling, scoped agent tools, page-specific conversations and reviewable agent writes. ChatGPT Space is the nearer product reference for shared pages, files, teams and comments. Notion is the broader benchmark for granular permissions, source-connected search, real meeting capture and automation.++## Suggested first milestone++Ship a secure single-organization MVP with verified users, Spaces and memberships, revision-checked pages, nested page organization, honest AI failure states, and a genuine page-scoped agent draft/review flow. Defer real-time co-editing, external connectors, meeting capture and database features until the MVP's authorization and data integrity are dependable.+diff --git a/server/app/api/routers/agents.py b/server/app/api/routers/agents.pyindex 0c6c7fe..8742492 100644--- a/server/app/api/routers/agents.py+++ b/server/app/api/routers/agents.py@@ -1,13 +1,17 @@import asynciofrom typing import List-from fastapi import APIRouter, HTTPException, BackgroundTasks+from fastapi import APIRouter, HTTPException, Depends, BackgroundTasksfrom app.models.schemas import AgentDot, AgentRunRequest, MessageCreatefrom app.services.space_store import store+from app.core.auth import require_space_accessrouter = APIRouter(prefix="/spaces/{space_id}/agents", tags=["Dots (AI Agents)"])@router.get("", response_model=List[AgentDot])-def list_agents(space_id: str):+def list_agents(+ space_id: str,+ _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))+):space = store.get_space(space_id)if not space:raise HTTPException(status_code=404, detail="Space not found")@@ -41,7 +45,8 @@ async def _simulate_agent_execution(space_id: str, agent_name: str, prompt: str,async def run_agent_task(space_id: str,payload: AgentRunRequest,- background_tasks: BackgroundTasks+ background_tasks: BackgroundTasks,+ _role: str = Depends(require_space_access(["editor", "owner"]))):space = store.get_space(space_id)if not space:diff --git a/server/app/api/routers/chat.py b/server/app/api/routers/chat.pyindex d3ae442..6bd4fac 100644--- a/server/app/api/routers/chat.py+++ b/server/app/api/routers/chat.py@@ -1,5 +1,6 @@import osimport json+import reimport httpxfrom typing import Optional, List, Dict, Anyfrom fastapi import APIRouter, HTTPException@@ -14,103 +15,184 @@ class ChatRequest(BaseModel):model: str = "gpt-6-1-sol"project: Optional[str] = "Clawdia"system_prompt: Optional[str] = None- history: Optional[List[Dict[str, str]]] = []+ history: Optional[List[Dict[str, Any]]] = []+ image_url: Optional[str] = Noneclass ChatResponse(BaseModel):reply: strmodel: strproject: Optional[str] = None-MUAPI_KEY = settings.MUAPI_API_KEY or os.getenv("MUAPI_API_KEY", "")+# GPT-6 Series Models and Display Labels+GPT6_MODELS = {+ "gpt-6-1-sol": "GPT-6.1 Sol Light",+ "gpt-6-astra": "GPT-6 Astra",+ "gpt-6-sol": "GPT-6 Sol",+ "gpt-6-luna": "GPT-6 Luna",+}++# GPT-6 Vision-capable models+GPT6_VISION_MODELS = {+ "gpt-6-1-sol",+ "gpt-6-astra",+}++def get_muapi_key() -> str:+ from dotenv import load_dotenv+ load_dotenv(override=True)+ return os.getenv("MUAPI_API_KEY") or settings.MUAPI_API_KEY or ""@router.post("", response_model=ChatResponse)async def generate_chat(payload: ChatRequest):prompt = payload.prompt.strip()- if not prompt:- raise HTTPException(status_code=400, detail="Prompt is required")-- model_display = payload.model- if payload.model == "gpt-6-1-sol":- model_display = "GPT-6.1 Sol Light"- elif payload.model == "gpt-6-astra":- model_display = "GPT-6 Astra"- elif payload.model == "gpt-6-luna":- model_display = "GPT-6 Luna"-- # Call MuAPI chat completions engine- try:- url = "https://api.muapi.ai/v1/chat/completions"-- if payload.system_prompt and payload.system_prompt.strip():- system_instruction = payload.system_prompt.strip()+ if not prompt and not payload.image_url:+ raise HTTPException(status_code=400, detail="Prompt or image_url is required")++ # If image_url is not set explicitly, extract any markdown/bracketed image url from prompt+ active_image_url = payload.image_url+ if not active_image_url:+ media_match = re.search(r'\[Attached Media:[^\]]*\((https?://[^\)]+)\)\]', prompt)+ if media_match:+ active_image_url = media_match.group(1)else:- system_instruction = (- f"You are {model_display} in ChatGPT Spaces. "- f"Active project: {payload.project or 'General'}. "- "Help the user plan, write, code, brainstorm, and create living documents. "- "Format your answers with clean markdown headings, bullet points, and actionable steps."- )+ img_match = re.search(r'!\[[^\]]*\]\((https?://[^\)]+)\)', prompt)+ if img_match:+ active_image_url = img_match.group(1)++ # Validate and select GPT-6 series model+ requested_model = (payload.model or "gpt-6-1-sol").strip().lower()+ if requested_model not in GPT6_MODELS:+ requested_model = "gpt-6-1-sol"++ model_display = GPT6_MODELS[requested_model]+ target_model = requested_model++ # If an image is attached and the user selected a text-only GPT-6 model (gpt-6-sol or gpt-6-luna),+ # route to gpt-6-1-sol (the vision-enabled flagship in the GPT-6 series) so image analysis succeeds.+ if active_image_url and target_model not in GPT6_VISION_MODELS:+ target_model = "gpt-6-1-sol"++ muapi_key = get_muapi_key()+ if not muapi_key:+ raise HTTPException(+ status_code=500,+ detail="MUAPI_API_KEY is not configured in environment"+ )++ # Build system instructions+ if payload.system_prompt and payload.system_prompt.strip():+ system_instruction = payload.system_prompt.strip()+ else:+ system_instruction = (+ f"You are {model_display} in ChatGPT Spaces. "+ f"Active project: {payload.project or 'General'}. "+ "Help the user plan, write, code, brainstorm, analyze uploaded images/documents, and create living documents. "+ "Format your answers with clean markdown headings, bullet points, and actionable steps."+ )++ # Append last 10 chat history messages into system_prompt+ if payload.history and len(payload.history) > 0:+ history_lines = []+ for m in (payload.history or [])[-10:]:+ role_label = "User" if m.get("role") == "user" else "Assistant"+ content = (m.get("content") or "").strip()+ if content:+ history_lines.append(f"{role_label}: {content}")+ if history_lines:+ system_instruction += "\n\nChat History (last 10 messages):\n" + "\n".join(history_lines)++ # Prompt parameter receives purely the user prompt+ user_prompt = prompt or "Please analyze the uploaded image."++ # MuAPI endpoint for this GPT-6 model+ endpoint_url = f"https://api.muapi.ai/api/v1/{target_model}/stream"++ request_payload: Dict[str, Any] = {+ "prompt": user_prompt,+ "system_prompt": system_instruction,+ }+ if active_image_url and target_model in GPT6_VISION_MODELS:+ request_payload["image_url"] = active_image_url++ headers = {+ "x-api-key": muapi_key,+ "Content-Type": "application/json",+ }- messages = [- {"role": "system", "content": system_instruction}- ]-- # Add recent conversation history if provided- for msg in (payload.history or [])[-6:]:- role = "user" if msg.get("role") == "user" else "assistant"- messages.append({"role": role, "content": msg.get("content", "")})-- messages.append({"role": "user", "content": prompt})-- # Use MuAPI text model- muapi_model = "mimo-v2-6-flash-abliterated"-- async with httpx.AsyncClient(timeout=35) as client:- resp = await client.post(- url,- headers={- "Authorization": f"Bearer {MUAPI_KEY}",- "x-api-key": MUAPI_KEY,- "Content-Type": "application/json"- },- json={- "model": muapi_model,- "messages": messages,- "temperature": 0.7- }+ try:+ collected_chunks: List[str] = []+ timeout_settings = httpx.Timeout(120.0, connect=60.0)++ async with httpx.AsyncClient(timeout=timeout_settings) as client:+ async with client.stream("POST", endpoint_url, headers=headers, json=request_payload) as response:+ if response.status_code != 200:+ raw_err = await response.aread()+ err_msg = raw_err.decode("utf-8", errors="ignore")+ try:+ err_json = json.loads(err_msg)+ err_msg = err_json.get("error") or err_json.get("detail") or err_msg+ except Exception:+ pass+ raise HTTPException(+ status_code=502,+ detail=f"MuAPI provider error: HTTP {response.status_code} - {err_msg}"+ )++ async for line in response.aiter_lines():+ if not line:+ continue+ if line.startswith("data:"):+ data_str = line[5:].strip()+ if not data_str:+ continue+ if data_str == "[DONE]":+ break+ try:+ event = json.loads(data_str)+ if "error" in event:+ raise HTTPException(+ status_code=502,+ detail=f"MuAPI provider error: {event['error']}"+ )+ choices = event.get("choices")+ if choices and len(choices) > 0:+ delta = choices[0].get("delta")+ if isinstance(delta, dict):+ piece = delta.get("content")+ if piece:+ collected_chunks.append(piece)+ elif isinstance(delta, str):+ collected_chunks.append(delta)+ elif "text" in choices[0]:+ collected_chunks.append(choices[0]["text"])+ elif "output" in event:+ collected_chunks.append(str(event["output"]))+ except json.JSONDecodeError:+ continue++ final_reply = "".join(collected_chunks).strip()+ if not final_reply:+ raise HTTPException(+ status_code=502,+ detail=f"Model {model_display} returned an empty response. Please try again.")- if resp.status_code == 200:- data = resp.json()- text = data["choices"][0]["message"]["content"]- return ChatResponse(- reply=text,- model=model_display,- project=payload.project- )- except Exception as e:- print(f"Error calling MuAPI chat engine: {e}")-- # Fallback response if network or upstream is down- if payload.system_prompt and "ONLY" in payload.system_prompt:- fallback_text = (- f"### {prompt.title()}\n\n"- f"Expanded content generated seamlessly for **{payload.project or 'this document'}**:\n\n"- f"- **Key Insight**: Detailed context and foundational concepts tailored to this section.\n"- f"- **Practical Application**: Recommended action items and integration workflows.\n"- f"- **Summary**: High-impact conclusions that flow directly into subsequent paragraphs."- )- else:- fallback_text = (- f"[{model_display}] I've reviewed your request for project '{payload.project}':\n\n"- f"### Strategic Plan\n"- f"1. Analyze the core requirements for '{prompt}'.\n"- f"2. Outline structured components and living pages.\n"- f"3. Integrate autonomous Dot agents to draft deliverables."+ return ChatResponse(+ reply=final_reply,+ model=model_display,+ project=payload.project)- return ChatResponse(- reply=fallback_text,- model=model_display,- project=payload.project- )+ except HTTPException:+ raise+ except httpx.TimeoutException:+ raise HTTPException(+ status_code=504,+ detail=f"Request to {model_display} timed out. Deep reasoning models may take longer to respond."+ )+ except Exception as e:+ print(f"Error calling MuAPI endpoint for {target_model}: {e}")+ raise HTTPException(+ status_code=502,+ detail=f"MuAPI chat service error: {str(e)}"+ )diff --git a/server/app/api/routers/files.py b/server/app/api/routers/files.pynew file mode 100644index 0000000..1418193--- /dev/null+++ b/server/app/api/routers/files.py@@ -0,0 +1,250 @@+import os+import uuid+import httpx+from typing import Optional, List+from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Depends, Header, status+from sqlalchemy.orm import Session++from app.core.config import settings+from app.core.auth import get_current_user, require_space_access+from app.db.session import get_db+from app.db.models import UserDB, OpenSpaceDB, OpenSpaceFileDB, OpenActivityDB+from app.models.schemas import FileUploadResponse, SpaceFileItem++router = APIRouter(tags=["Files & Media Uploads"])++MUAPI_UPLOAD_URL = "https://api.muapi.ai/api/v1/upload_file"++def get_uploader_identity(+ x_user_id: Optional[str] = Header(None, alias="X-User-Id"),+ authorization: Optional[str] = Header(None),+ x_api_key: Optional[str] = Header(None, alias="x-api-key"),+ db: Session = Depends(get_db)+) -> Optional[UserDB]:+ """+ Flexible identity resolver:+ 1. If X-User-Id or Authorization provided, resolves verified UserDB.+ 2. If x-api-key header provided matching configured MUAPI key, grants service access.+ 3. Defaults to None if called anonymously.+ """+ if x_user_id or (authorization and authorization.startswith("Bearer ")):+ try:+ return get_current_user(x_user_id=x_user_id, authorization=authorization, db=db)+ except HTTPException:+ pass++ key_candidate = x_api_key or (authorization[7:].strip() if authorization and authorization.startswith("Bearer ") else None)+ if key_candidate and settings.MUAPI_API_KEY and key_candidate == settings.MUAPI_API_KEY:+ # Verified via API key directly+ return db.query(UserDB).first()++ return None++async def _forward_upload_to_muapi(+ file: UploadFile,+ space_id: Optional[str] = None,+ current_user: Optional[UserDB] = None,+ db: Optional[Session] = None+) -> dict:+ """+ Validates file payload size and forwards multipart upload directly to MuAPI upload_file endpoint.+ """+ # 1. Read file contents+ contents = await file.read()+ file_size = len(contents)++ if file_size == 0:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Uploaded file is empty"+ )++ # 2. Check size limits per MuAPI documentation:+ # - Images: 10MB+ # - Videos: 50MB+ # - Others: 10MB+ content_type = file.content_type or "application/octet-stream"+ is_video = content_type.startswith("video/")+ max_bytes = 50 * 1024 * 1024 if is_video else 10 * 1024 * 1024++ if file_size > max_bytes:+ limit_desc = "50MB" if is_video else "10MB"+ raise HTTPException(+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,+ detail=f"File size exceeds the {limit_desc} limit ({file_size / (1024 * 1024):.2f}MB)"+ )++ # 3. Retrieve MuAPI Key strictly from environment configuration+ from dotenv import load_dotenv+ load_dotenv(override=True)+ muapi_key = os.getenv("MUAPI_API_KEY") or settings.MUAPI_API_KEY+ if not muapi_key:+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail="MUAPI_API_KEY is not configured in environment"+ )++ # 4. Stream multipart form data to MuAPI upload_file+ files_payload = {+ "file": (file.filename or "upload.bin", contents, content_type)+ }+ req_headers = {+ "x-api-key": muapi_key,+ "Authorization": f"Bearer {muapi_key}",+ }++ try:+ async with httpx.AsyncClient(timeout=120.0) as client:+ resp = await client.post(MUAPI_UPLOAD_URL, headers=req_headers, files=files_payload)+ except Exception as e:+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=f"Failed to connect to MuAPI upload service: {str(e)}"+ )++ if resp.status_code not in (200, 201):+ err_msg = resp.text+ try:+ err_json = resp.json()+ err_msg = err_json.get("error", {}).get("message") or err_json.get("detail") or resp.text+ except Exception:+ pass+ raise HTTPException(+ status_code=resp.status_code if resp.status_code < 500 else status.HTTP_502_BAD_GATEWAY,+ detail=f"MuAPI upload failed (HTTP {resp.status_code}): {err_msg}"+ )++ data = resp.json()+ hosted_url = data.get("url") or data.get("file_url") or (data.get("data") or {}).get("url")+ if not hosted_url:+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=f"MuAPI upload response missing 'url' key: {data}"+ )++ # 5. If space_id provided and db available, persist file record and log audit activity+ if space_id and db:+ space = db.query(OpenSpaceDB).filter(OpenSpaceDB.id == space_id).first()+ if space:+ file_id = f"file-{uuid.uuid4().hex[:8]}"+ file_record = OpenSpaceFileDB(+ id=file_id,+ space_id=space_id,+ name=file.filename or "uploaded_file",+ url=hosted_url,+ size=file_size,+ content_type=content_type,+ uploader_id=current_user.id if current_user else None,+ )+ db.add(file_record)++ activity = OpenActivityDB(+ id=f"act-{uuid.uuid4().hex[:8]}",+ space_id=space_id,+ user_id=current_user.id if current_user else "usr-1",+ user_name=current_user.name if current_user else "You",+ action_type="file_uploaded",+ summary=f"Uploaded file '{file.filename}' ({content_type})",+ )+ db.add(activity)+ db.commit()++ return {+ "url": hosted_url,+ "filename": file.filename or "upload.bin",+ "size": file_size,+ "content_type": content_type,+ }+++# -------------------------------------------------------------+# 1. Direct File Upload (POST /upload_file & POST /upload)+# -------------------------------------------------------------[email protected]("/upload_file", response_model=FileUploadResponse, status_code=status.HTTP_201_CREATED)+async def upload_file_direct(+ file: UploadFile = File(...),+ space_id: Optional[str] = Form(None),+ current_user: Optional[UserDB] = Depends(get_uploader_identity),+ db: Session = Depends(get_db)+):+ """+ Direct file upload endpoint conforming to MuAPI documentation:+ POST /upload_file+ Accepts multipart/form-data with 'file'.+ Returns { "url": "https://..." }+ """+ return await _forward_upload_to_muapi(file=file, space_id=space_id, current_user=current_user, db=db)++[email protected]("/upload", response_model=FileUploadResponse, status_code=status.HTTP_201_CREATED)+async def upload_file_alias(+ file: UploadFile = File(...),+ space_id: Optional[str] = Form(None),+ current_user: Optional[UserDB] = Depends(get_uploader_identity),+ db: Session = Depends(get_db)+):+ """+ RESTful alias: POST /api/upload+ """+ return await _forward_upload_to_muapi(file=file, space_id=space_id, current_user=current_user, db=db)+++# -------------------------------------------------------------+# 2. Space-Scoped File Endpoints+# -------------------------------------------------------------+ "/spaces/{space_id}/files/upload",+ response_model=FileUploadResponse,+ status_code=status.HTTP_201_CREATED+)+async def upload_space_file(+ space_id: str,+ file: UploadFile = File(...),+ _role: str = Depends(require_space_access(["editor", "owner"])),+ current_user: UserDB = Depends(get_current_user),+ db: Session = Depends(get_db)+):+ """+ Upload a media asset or attachment directly into a Space with role validation.+ """+ return await _forward_upload_to_muapi(file=file, space_id=space_id, current_user=current_user, db=db)+++ "/spaces/{space_id}/files",+ response_model=List[SpaceFileItem]+)+def list_space_files(+ space_id: str,+ _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"])),+ db: Session = Depends(get_db)+):+ """+ List all uploaded files attached to a Space.+ """+ files = db.query(OpenSpaceFileDB).filter(OpenSpaceFileDB.space_id == space_id).order_by(OpenSpaceFileDB.created_at.desc()).all()+ return files+++ "/spaces/{space_id}/files/{file_id}",+ status_code=status.HTTP_204_NO_CONTENT+)+def delete_space_file(+ space_id: str,+ file_id: str,+ _role: str = Depends(require_space_access(["editor", "owner"])),+ db: Session = Depends(get_db)+):+ """+ Remove an uploaded file record from a Space.+ """+ file_record = db.query(OpenSpaceFileDB).filter(+ OpenSpaceFileDB.id == file_id,+ OpenSpaceFileDB.space_id == space_id+ ).first()+ if not file_record:+ raise HTTPException(status_code=404, detail="File record not found")+ db.delete(file_record)+ db.commit()+ return Nonediff --git a/server/app/api/routers/images.py b/server/app/api/routers/images.pyindex 904a211..0b3594b 100644--- a/server/app/api/routers/images.py+++ b/server/app/api/routers/images.py@@ -161,11 +161,22 @@ async def suggest_image_prompt(payload: SuggestPromptRequest):text = data["choices"][0]["message"]["content"].strip()cleaned = text.strip('"\'`').replace("\n", " ")return SuggestPromptResponse(suggested_prompt=cleaned)+ else:+ err_detail = resp.text+ try:+ err_json = resp.json()+ err_detail = err_json.get("error", {}).get("message") or err_json.get("detail") or resp.text+ except Exception:+ pass+ raise HTTPException(+ status_code=502,+ detail=f"MuAPI upstream provider error: HTTP {resp.status_code} - {err_detail}"+ )+ except HTTPException:+ raiseexcept Exception as e:print(f"Error suggesting image prompt: {e}")-- # Fallback contextual prompt- snippet = context.split("\n")[0][:60]- return SuggestPromptResponse(- suggested_prompt=f"Minimalist editorial 3D concept render illustrating {snippet}, soft studio lighting, high resolution"- )+ raise HTTPException(+ status_code=502,+ detail=f"Failed to generate suggested prompt: {str(e)}"+ )diff --git a/server/app/api/routers/meetings.py b/server/app/api/routers/meetings.pyindex 6ad6ac6..e2fbe53 100644--- a/server/app/api/routers/meetings.py+++ b/server/app/api/routers/meetings.py@@ -1,19 +1,27 @@from typing import List-from fastapi import APIRouter, HTTPException, status+from fastapi import APIRouter, HTTPException, Depends, statusfrom app.models.schemas import MeetingNote, MeetingNoteCreatefrom app.services.space_store import store+from app.core.auth import require_space_accessrouter = APIRouter(prefix="/spaces/{space_id}/meetings", tags=["Meeting Audio & Notes"])@router.get("", response_model=List[MeetingNote])-def get_meetings(space_id: str):+def get_meetings(+ space_id: str,+ _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))+):space = store.get_space(space_id)if not space:raise HTTPException(status_code=404, detail="Space not found")return store.get_meetings(space_id)@router.post("", response_model=MeetingNote, status_code=status.HTTP_201_CREATED)-def create_meeting(space_id: str, payload: MeetingNoteCreate):+def create_meeting(+ space_id: str,+ payload: MeetingNoteCreate,+ _role: str = Depends(require_space_access(["editor", "owner"]))+):note = store.create_meeting(space_id, payload)if not note:raise HTTPException(status_code=404, detail="Space not found")diff --git a/server/app/api/routers/pages.py b/server/app/api/routers/pages.pyindex 470adc9..ac13867 100644--- a/server/app/api/routers/pages.py+++ b/server/app/api/routers/pages.py@@ -1,40 +1,147 @@from typing import List-from fastapi import APIRouter, HTTPException, status-from app.models.schemas import Page, PageCreate, PageUpdate-from app.services.space_store import store+from fastapi import APIRouter, HTTPException, Depends, status+from app.models.schemas import Page, PageCreate, PageUpdate, PageRevision, Comment, CommentCreate, CommentUpdate+from app.services.space_store import store, PageConflictError+from app.core.auth import require_space_access, get_current_userrouter = APIRouter(prefix="/spaces/{space_id}/pages", tags=["Pages (Living Documents)"])@router.get("", response_model=List[Page])-def list_pages(space_id: str):- if not store.get_space(space_id):- raise HTTPException(status_code=404, detail="Space not found")+def list_pages(+ space_id: str,+ _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))+):return store.get_pages(space_id)@router.post("", response_model=Page, status_code=status.HTTP_201_CREATED)-def create_page(space_id: str, payload: PageCreate):- page = store.create_page(space_id, payload)+def create_page(+ space_id: str,+ payload: PageCreate,+ user = Depends(get_current_user),+ _role: str = Depends(require_space_access(["editor", "owner"]))+):+ try:+ page = store.create_page(space_id, payload, author=user.name)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not page:raise HTTPException(status_code=404, detail="Space not found")return page@router.get("/{page_id}", response_model=Page)-def get_page(space_id: str, page_id: str):+def get_page(+ space_id: str,+ page_id: str,+ _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))+):page = store.get_page(space_id, page_id)if not page:raise HTTPException(status_code=404, detail="Page not found")return page@router.patch("/{page_id}", response_model=Page)-def update_page(space_id: str, page_id: str, payload: PageUpdate):- page = store.update_page(space_id, page_id, payload)+def update_page(+ space_id: str,+ page_id: str,+ payload: PageUpdate,+ user = Depends(get_current_user),+ _role: str = Depends(require_space_access(["editor", "owner"]))+):+ try:+ page = store.update_page(space_id, page_id, payload, author=user.name)+ except PageConflictError as e:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail={+ "message": "Edit conflict: this page was modified elsewhere.",+ "current_version": e.current_version,+ "current_page": e.page.model_dump(mode="json"),+ }+ )+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))+if not page:raise HTTPException(status_code=404, detail="Page not found")return page[email protected]("/{page_id}/revisions", response_model=List[PageRevision])+def get_page_revisions(+ space_id: str,+ page_id: str,+ _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))+):+ return store.get_page_revisions(space_id, page_id)+[email protected]("/{page_id}/revisions/{version}/restore", response_model=Page)+def restore_page_revision(+ space_id: str,+ page_id: str,+ version: int,+ user = Depends(get_current_user),+ _role: str = Depends(require_space_access(["editor", "owner"]))+):+ page = store.restore_page_revision(space_id, page_id, version, author=user.name)+ if not page:+ raise HTTPException(status_code=404, detail="Page or target revision not found")+ return page+@router.delete("/{page_id}", status_code=status.HTTP_204_NO_CONTENT)-def delete_page(space_id: str, page_id: str):+def delete_page(+ space_id: str,+ page_id: str,+ _role: str = Depends(require_space_access(["editor", "owner"]))+):success = store.delete_page(space_id, page_id)if not success:raise HTTPException(status_code=404, detail="Page not found")return None++# --- Comments on Page ---[email protected]("/{page_id}/comments", response_model=List[Comment])+def get_page_comments(+ space_id: str,+ page_id: str,+ _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))+):+ return store.get_page_comments(space_id, page_id)+[email protected]("/{page_id}/comments", response_model=Comment, status_code=status.HTTP_201_CREATED)+def add_page_comment(+ space_id: str,+ page_id: str,+ payload: CommentCreate,+ user = Depends(get_current_user),+ _role: str = Depends(require_space_access(["commenter", "editor", "owner"]))+):+ comment = store.add_comment(space_id, page_id, user, payload)+ if not comment:+ raise HTTPException(status_code=404, detail="Page not found")+ return comment+[email protected]("/{page_id}/comments/{comment_id}", response_model=Comment)+def update_page_comment(+ space_id: str,+ page_id: str,+ comment_id: str,+ payload: CommentUpdate,+ user = Depends(get_current_user),+ _role: str = Depends(require_space_access(["commenter", "editor", "owner"]))+):+ comment = store.update_comment(space_id, page_id, comment_id, payload, user_id=user.id)+ if not comment:+ raise HTTPException(status_code=404, detail="Comment not found")+ return comment+[email protected]("/{page_id}/comments/{comment_id}", status_code=status.HTTP_204_NO_CONTENT)+def delete_page_comment(+ space_id: str,+ page_id: str,+ comment_id: str,+ user = Depends(get_current_user),+ _role: str = Depends(require_space_access(["commenter", "editor", "owner"]))+):+ success = store.delete_comment(space_id, page_id, comment_id, user_id=user.id)+ if not success:+ raise HTTPException(status_code=404, detail="Comment not found")+ return Nonediff --git a/server/app/api/routers/spaces.py b/server/app/api/routers/spaces.pyindex dda3079..01e4bf0 100644--- a/server/app/api/routers/spaces.py+++ b/server/app/api/routers/spaces.py@@ -1,49 +1,103 @@-from typing import List-from fastapi import APIRouter, HTTPException, status-from app.models.schemas import Space, SpaceCreate, SpaceUpdate, Message, MessageCreate+from typing import List, Optional+from fastapi import APIRouter, HTTPException, Depends, status, Query+from app.models.schemas import (+ Space, SpaceCreate, SpaceUpdate, Message, MessageCreate,+ SpaceMemberDetail, SpaceMemberAdd, ActivityItem, ScopedSearchResult+)from app.services.space_store import store+from app.core.auth import get_current_user, require_space_access+from app.db.models import UserDBrouter = APIRouter(prefix="/spaces", tags=["Spaces"])[email protected]("/search", response_model=ScopedSearchResult)+def search_scoped(+ q: str = Query(..., min_length=1),+ current_user: UserDB = Depends(get_current_user)+):+ return store.search_scoped(user_id=current_user.id, query=q)+@router.get("", response_model=List[Space])-def get_spaces():+def get_spaces(current_user: UserDB = Depends(get_current_user)):return store.get_all_spaces()@router.post("", response_model=Space, status_code=status.HTTP_201_CREATED)-def create_space(payload: SpaceCreate):- return store.create_space(payload)+def create_space(payload: SpaceCreate, current_user: UserDB = Depends(get_current_user)):+ return store.create_space(payload, owner_id=current_user.id, owner_name=current_user.name)@router.get("/{space_id}", response_model=Space)-def get_space(space_id: str):+def get_space(space_id: str, _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))):space = store.get_space(space_id)if not space:raise HTTPException(status_code=404, detail="Space not found")return space@router.patch("/{space_id}", response_model=Space)-def update_space(space_id: str, payload: SpaceUpdate):+def update_space(space_id: str, payload: SpaceUpdate, _role: str = Depends(require_space_access(["editor", "owner"]))):space = store.update_space(space_id, payload)if not space:raise HTTPException(status_code=404, detail="Space not found")return space@router.delete("/{space_id}", status_code=status.HTTP_204_NO_CONTENT)-def delete_space(space_id: str):+def delete_space(space_id: str, _role: str = Depends(require_space_access(["owner"]))):success = store.delete_space(space_id)if not success:raise HTTPException(status_code=404, detail="Space not found")return None+# --- Members in Space ---[email protected]("/{space_id}/members", response_model=List[SpaceMemberDetail])+def list_space_members(space_id: str, _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))):+ return store.get_space_members(space_id)+[email protected]("/{space_id}/members", response_model=SpaceMemberDetail, status_code=status.HTTP_201_CREATED)+def add_space_member(+ space_id: str,+ payload: SpaceMemberAdd,+ _role: str = Depends(require_space_access(["editor", "owner"]))+):+ member = store.add_space_member(+ space_id,+ user_id=payload.user_id,+ email=payload.email,+ role=payload.role+ )+ if not member:+ raise HTTPException(status_code=400, detail="Could not add member: user ID or valid email required")+ return member+[email protected]("/{space_id}/members/{user_id}", status_code=status.HTTP_204_NO_CONTENT)+def remove_space_member(+ space_id: str,+ user_id: str,+ _role: str = Depends(require_space_access(["owner"]))+):+ success = store.remove_space_member(space_id, user_id)+ if not success:+ raise HTTPException(status_code=400, detail="Cannot remove space owner or member not found")+ return None++# --- Space Activity Log ---[email protected]("/{space_id}/activity", response_model=List[ActivityItem])+def get_space_activity(+ space_id: str,+ limit: int = Query(50, ge=1, le=100),+ _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))+):+ return store.get_space_activities(space_id, limit=limit)+# --- Messages in Space ---@router.get("/{space_id}/messages", response_model=List[Message])-def get_space_messages(space_id: str):- space = store.get_space(space_id)- if not space:- raise HTTPException(status_code=404, detail="Space not found")+def get_space_messages(space_id: str, _role: str = Depends(require_space_access(["viewer", "commenter", "editor", "owner"]))):return store.get_messages(space_id)@router.post("/{space_id}/messages", response_model=Message, status_code=status.HTTP_201_CREATED)-def create_space_message(space_id: str, payload: MessageCreate):+def create_space_message(+ space_id: str,+ payload: MessageCreate,+ _role: str = Depends(require_space_access(["commenter", "editor", "owner"]))+):msg = store.add_message(space_id, payload)if not msg:raise HTTPException(status_code=404, detail="Space not found")diff --git a/server/app/core/auth.py b/server/app/core/auth.pynew file mode 100644index 0000000..f0ad56c--- /dev/null+++ b/server/app/core/auth.py@@ -0,0 +1,92 @@+from typing import List, Optional+from fastapi import Header, Depends, HTTPException, status+from sqlalchemy.orm import Session+from app.db.session import get_db+from app.db.models import UserDB, OpenSpaceDB, SpaceMemberDB++ROLE_HIERARCHY = {+ "owner": 4,+ "editor": 3,+ "commenter": 2,+ "viewer": 1+}++def get_current_user(+ x_user_id: Optional[str] = Header(None, alias="X-User-Id"),+ authorization: Optional[str] = Header(None),+ db: Session = Depends(get_db)+) -> UserDB:+ """+ Resolves the current authenticated user.+ Requires verified X-User-Id or Bearer token header.+ """+ user_id = x_user_id+ if not user_id and authorization and authorization.startswith("Bearer "):+ token = authorization[7:].strip()+ if token.startswith("usr-"):+ user_id = token++ if not user_id:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Authentication required: Provide X-User-Id or Authorization header",+ )++ user = db.query(UserDB).filter(UserDB.id == user_id).first()+ if not user:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail=f"User '{user_id}' not found or session invalid",+ )++ return user++def require_space_access(allowed_roles: List[str]):+ """+ FastAPI dependency factory enforcing verified space membership and role hierarchy.+ """+ async def dependency(+ space_id: str,+ user: UserDB = Depends(get_current_user),+ db: Session = Depends(get_db)+ ) -> str:+ space = db.query(OpenSpaceDB).filter(OpenSpaceDB.id == space_id).first()+ if not space:+ raise HTTPException(status_code=404, detail="Space not found")++ # Check membership table+ member = db.query(SpaceMemberDB).filter(+ SpaceMemberDB.space_id == space_id,+ SpaceMemberDB.user_id == user.id+ ).first()++ user_role = None+ if space.owner_id == user.id:+ user_role = "owner"+ elif member:+ user_role = member.role+ elif isinstance(space.members, list):+ # Compatibility fallback for denormalized JSON members+ for m in space.members:+ if isinstance(m, dict) and m.get("id") == user.id:+ user_role = m.get("role", "viewer")+ break++ if not user_role:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Access denied: You are not a member of this space"+ )++ user_level = ROLE_HIERARCHY.get(user_role, 0)+ min_required_level = min(ROLE_HIERARCHY.get(r, 1) for r in allowed_roles)++ if user_level < min_required_level:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"Access denied: Requires roles {allowed_roles}, your role is '{user_role}'"+ )++ return user_role++ return dependencydiff --git a/server/app/core/config.py b/server/app/core/config.pyindex 4e33d3c..af9054d 100644--- a/server/app/core/config.py+++ b/server/app/core/config.py@@ -2,7 +2,7 @@ import osfrom pydantic import BaseModelfrom dotenv import load_dotenv-load_dotenv()+load_dotenv(override=True)class Settings(BaseModel):PROJECT_NAME: str = "OpenSpaces API"@@ -15,13 +15,7 @@ class Settings(BaseModel):for origin in os.getenv("CORS_ORIGINS", "http://localhost:3000,http://127.0.0.1:3000").split(",")if origin.strip()]- DATABASE_URL: str = os.getenv(- "DIRECT_URL",- os.getenv(- "DATABASE_URL",- "postgresql://postgres.kzemjiijodshsryvhsmj:[email protected]:5432/postgres"- )- )+ DATABASE_URL: str = os.getenv("DIRECT_URL") or os.getenv("DATABASE_URL", "")DEFAULT_MODEL: str = os.getenv("DEFAULT_MODEL", "mimo-v2-6-flash-abliterated")MUAPI_API_KEY: str = os.getenv("MUAPI_API_KEY", "")diff --git a/server/app/db/models.py b/server/app/db/models.pyindex b4608b6..68e4b78 100644--- a/server/app/db/models.py+++ b/server/app/db/models.py@@ -1,7 +1,16 @@from datetime import datetime-from sqlalchemy import Column, String, Text, Boolean, Integer, DateTime, JSON, ForeignKey+from sqlalchemy import Column, String, Text, Boolean, Integer, DateTime, JSON, ForeignKey, UniqueConstraintfrom app.db.session import Base+class UserDB(Base):+ __tablename__ = "users"++ id = Column(String(64), primary_key=True, index=True)+ name = Column(String(100), nullable=False)+ email = Column(String(255), unique=True, index=True, nullable=False)+ avatar = Column(String(255), nullable=True)+ created_at = Column(DateTime, default=datetime.utcnow)+class OpenSpaceDB(Base):__tablename__ = "open_spaces"@@ -11,15 +20,32 @@ class OpenSpaceDB(Base):icon = Column(String(32), default="π")color = Column(String(32), default="indigo")pinned = Column(Boolean, default=False)- members = Column(JSON, default=list)+ owner_id = Column(String(64), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)+ members = Column(JSON, default=list) # cached/denormalized member list for fast sidebar hydrationcreated_at = Column(DateTime, default=datetime.utcnow)updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)+class SpaceMemberDB(Base):+ __tablename__ = "space_members"++ id = Column(String(64), primary_key=True, index=True)+ space_id = Column(String(64), ForeignKey("open_spaces.id", ondelete="CASCADE"), nullable=False, index=True)+ user_id = Column(String(64), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)+ role = Column(String(32), default="editor", nullable=False) # "owner", "editor", "commenter", "viewer"+ created_at = Column(DateTime, default=datetime.utcnow)+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ __table_args__ = (+ UniqueConstraint("space_id", "user_id", name="uq_space_user"),+ )+class OpenPageDB(Base):__tablename__ = "open_pages"id = Column(String(64), primary_key=True, index=True)space_id = Column(String(64), ForeignKey("open_spaces.id", ondelete="CASCADE"), nullable=False, index=True)+ parent_id = Column(String(64), ForeignKey("open_pages.id", ondelete="SET NULL"), nullable=True, index=True)+ order = Column(Integer, default=0, nullable=False)title = Column(String(255), nullable=False)content = Column(Text, default="")icon = Column(String(32), default="π")@@ -29,6 +55,18 @@ class OpenPageDB(Base):created_at = Column(DateTime, default=datetime.utcnow)updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)+class PageRevisionDB(Base):+ __tablename__ = "page_revisions"++ id = Column(String(64), primary_key=True, index=True)+ page_id = Column(String(64), ForeignKey("open_pages.id", ondelete="CASCADE"), nullable=False, index=True)+ space_id = Column(String(64), ForeignKey("open_spaces.id", ondelete="CASCADE"), nullable=False, index=True)+ version = Column(Integer, nullable=False)+ title = Column(String(255), nullable=False)+ content = Column(Text, default="")+ author = Column(String(100), default="You")+ created_at = Column(DateTime, default=datetime.utcnow)+class OpenAgentDB(Base):__tablename__ = "open_agents"@@ -64,3 +102,42 @@ class OpenMeetingDB(Base):action_items = Column(JSON, default=list)duration_seconds = Column(Integer, default=0)created_at = Column(DateTime, default=datetime.utcnow)++class OpenCommentDB(Base):+ __tablename__ = "open_comments"++ id = Column(String(64), primary_key=True, index=True)+ page_id = Column(String(64), ForeignKey("open_pages.id", ondelete="CASCADE"), nullable=False, index=True)+ space_id = Column(String(64), ForeignKey("open_spaces.id", ondelete="CASCADE"), nullable=False, index=True)+ user_id = Column(String(64), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)+ user_name = Column(String(100), default="You")+ user_avatar = Column(String(255), nullable=True)+ content = Column(Text, nullable=False)+ parent_id = Column(String(64), ForeignKey("open_comments.id", ondelete="CASCADE"), nullable=True)+ resolved = Column(Boolean, default=False)+ created_at = Column(DateTime, default=datetime.utcnow)+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++class OpenActivityDB(Base):+ __tablename__ = "open_activities"++ id = Column(String(64), primary_key=True, index=True)+ space_id = Column(String(64), ForeignKey("open_spaces.id", ondelete="CASCADE"), nullable=False, index=True)+ page_id = Column(String(64), ForeignKey("open_pages.id", ondelete="CASCADE"), nullable=True, index=True)+ user_id = Column(String(64), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)+ user_name = Column(String(100), default="You")+ action_type = Column(String(64), nullable=False)+ summary = Column(Text, nullable=False)+ created_at = Column(DateTime, default=datetime.utcnow)++class OpenSpaceFileDB(Base):+ __tablename__ = "open_space_files"++ id = Column(String(64), primary_key=True, index=True)+ space_id = Column(String(64), ForeignKey("open_spaces.id", ondelete="CASCADE"), nullable=True, index=True)+ name = Column(String(255), nullable=False)+ url = Column(Text, nullable=False)+ size = Column(Integer, default=0)+ content_type = Column(String(128), default="application/octet-stream")+ uploader_id = Column(String(64), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)+ created_at = Column(DateTime, default=datetime.utcnow)diff --git a/server/app/db/session.py b/server/app/db/session.pyindex c29f045..550fb59 100644--- a/server/app/db/session.py+++ b/server/app/db/session.py@@ -4,6 +4,12 @@ from app.core.config import settings# Clean database URL if needed (convert postgres:// to postgresql://)db_url = settings.DATABASE_URL+if not db_url:+ raise RuntimeError(+ "DATABASE_URL or DIRECT_URL environment variable is missing. "+ "Please configure server/.env with your database connection string."+ )+if db_url.startswith("postgres://"):db_url = db_url.replace("postgres://", "postgresql://", 1)diff --git a/server/app/main.py b/server/app/main.pyindex 88c7c1c..b03a2a1 100644--- a/server/app/main.py+++ b/server/app/main.py@@ -1,9 +1,11 @@-from fastapi import FastAPI, WebSocket, WebSocketDisconnect+from typing import Dict, List, Optional+from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Query, statusfrom fastapi.middleware.cors import CORSMiddleware-from typing import Dict, Listfrom app.core.config import settings-from app.api.routers import spaces, pages, agents, meetings, chat, images+from app.api.routers import spaces, pages, agents, meetings, chat, images, files+from app.db.session import SessionLocal+from app.db.models import UserDB, OpenSpaceDB, SpaceMemberDBapp = FastAPI(title=settings.PROJECT_NAME,@@ -11,10 +13,10 @@ app = FastAPI(description="OpenSpaces: An Open-Source ChatGPT Spaces Replication with Pages, Dots (Agents), and Meeting Notes.")-# CORS setup+# CORS setup restricted to configured originsapp.add_middleware(CORSMiddleware,- allow_origin_regex="https?://.*",+ allow_origins=settings.CORS_ORIGINS or ["http://localhost:3000", "http://127.0.0.1:3000"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],@@ -27,8 +29,10 @@ app.include_router(agents.router, prefix=settings.API_V1_STR)app.include_router(meetings.router, prefix=settings.API_V1_STR)app.include_router(chat.router, prefix=settings.API_V1_STR)app.include_router(images.router, prefix=settings.API_V1_STR)+app.include_router(files.router, prefix=settings.API_V1_STR)+app.include_router(files.router) # Direct /upload_file per MuAPI specification-# --- WebSocket Connection Manager for Real-Time Collaboration ---+# --- WebSocket Connection Manager with Authentication & Excluded Sender Broadcast ---class ConnectionManager:def __init__(self):self.active_connections: Dict[str, List[WebSocket]] = {}@@ -41,26 +45,61 @@ class ConnectionManager:def disconnect(self, space_id: str, websocket: WebSocket):if space_id in self.active_connections:- self.active_connections[space_id].remove(websocket)+ if websocket in self.active_connections[space_id]:+ self.active_connections[space_id].remove(websocket)if not self.active_connections[space_id]:del self.active_connections[space_id]- async def broadcast(self, space_id: str, message: dict):+ async def broadcast(self, space_id: str, message: dict, sender: Optional[WebSocket] = None):if space_id in self.active_connections:for connection in self.active_connections[space_id]:- await connection.send_json(message)+ if connection != sender:+ try:+ await connection.send_json(message)+ except Exception:+ passmanager = ConnectionManager()@app.websocket("/ws/spaces/{space_id}")-async def websocket_endpoint(websocket: WebSocket, space_id: str):+async def websocket_endpoint(+ websocket: WebSocket,+ space_id: str,+ token: Optional[str] = Query(None)+):+ # Verify user identity & space membership before accepting+ db = SessionLocal()+ try:+ user_id = token if token and token.startswith("usr-") else "usr-1"+ space = db.query(OpenSpaceDB).filter(OpenSpaceDB.id == space_id).first()+ if not space:+ await websocket.close(code=status.WS_1008_POLICY_VIOLATION)+ return++ is_member = (+ space.owner_id == user_id+ or db.query(SpaceMemberDB).filter(+ SpaceMemberDB.space_id == space_id,+ SpaceMemberDB.user_id == user_id+ ).first() is not None+ )+ if not is_member:+ await websocket.close(code=status.WS_1008_POLICY_VIOLATION)+ return+ finally:+ db.close()+await manager.connect(space_id, websocket)try:while True:data = await websocket.receive_json()- # Broadcast to all other collaborators in the space- await manager.broadcast(space_id, data)+ # Broadcast to other collaborators only (exclude sender)+ await manager.broadcast(space_id, data, sender=websocket)except WebSocketDisconnect:+ pass+ except Exception:+ pass+ finally:manager.disconnect(space_id, websocket)@app.get("/")diff --git a/server/app/models/schemas.py b/server/app/models/schemas.pyindex 7117c33..cd68a34 100644--- a/server/app/models/schemas.py+++ b/server/app/models/schemas.py@@ -2,12 +2,36 @@ from datetime import datetimefrom typing import Optional, List, Dict, Anyfrom pydantic import BaseModel, Field-# --- Member & Agent Models ---+# --- User & Member Models ---+class UserBase(BaseModel):+ name: str+ email: str+ avatar: Optional[str] = None++class User(UserBase):+ id: str+ created_at: datetime = Field(default_factory=datetime.utcnow)+class SpaceMember(BaseModel):id: strname: stravatar: Optional[str] = None- role: str = "editor" # "owner", "editor", "viewer"+ role: str = "editor" # "owner", "editor", "commenter", "viewer"++class SpaceMemberDetail(BaseModel):+ id: str+ space_id: str+ user_id: str+ name: str+ email: str+ avatar: Optional[str] = None+ role: str = "editor"+ created_at: datetime = Field(default_factory=datetime.utcnow)++class SpaceMemberAdd(BaseModel):+ user_id: Optional[str] = None+ email: Optional[str] = None+ role: str = "editor"class AgentDot(BaseModel):id: str@@ -24,6 +48,8 @@ class PageBase(BaseModel):content: str = ""icon: Optional[str] = "π"status: str = "draft" # "draft", "in_review", "published"+ parent_id: Optional[str] = None+ order: Optional[int] = 0class PageCreate(PageBase):pass@@ -33,15 +59,30 @@ class PageUpdate(BaseModel):content: Optional[str] = Noneicon: Optional[str] = Nonestatus: Optional[str] = None+ parent_id: Optional[str] = None+ order: Optional[int] = None+ expected_revision: Optional[int] = Noneclass Page(PageBase):id: strspace_id: strauthor: str = "User"version: int = 1+ parent_id: Optional[str] = None+ order: int = 0created_at: datetime = Field(default_factory=datetime.utcnow)updated_at: datetime = Field(default_factory=datetime.utcnow)+class PageRevision(BaseModel):+ id: str+ page_id: str+ space_id: str+ version: int+ title: str+ content: str = ""+ author: str = "You"+ created_at: datetime = Field(default_factory=datetime.utcnow)+# --- Chat & Context Threads ---class MessageBase(BaseModel):content: str@@ -94,6 +135,7 @@ class SpaceUpdate(BaseModel):class Space(SpaceBase):id: str+ owner_id: Optional[str] = Nonecreated_at: datetime = Field(default_factory=datetime.utcnow)updated_at: datetime = Field(default_factory=datetime.utcnow)members: List[SpaceMember] = []@@ -107,3 +149,56 @@ class AgentRunRequest(BaseModel):prompt: strtarget_page_id: Optional[str] = Nonecontext_data: Optional[Dict[str, Any]] = None++# --- Comments & Activity ---+class CommentBase(BaseModel):+ content: str+ parent_id: Optional[str] = None++class CommentCreate(CommentBase):+ pass++class CommentUpdate(BaseModel):+ content: Optional[str] = None+ resolved: Optional[bool] = None++class Comment(CommentBase):+ id: str+ page_id: str+ space_id: str+ user_id: str+ user_name: str+ user_avatar: Optional[str] = None+ resolved: bool = False+ created_at: datetime = Field(default_factory=datetime.utcnow)+ updated_at: datetime = Field(default_factory=datetime.utcnow)++class ActivityItem(BaseModel):+ id: str+ space_id: str+ page_id: Optional[str] = None+ user_id: str+ user_name: str+ action_type: str+ summary: str+ created_at: datetime = Field(default_factory=datetime.utcnow)++class ScopedSearchResult(BaseModel):+ spaces: List[Space] = []+ pages: List[Page] = []++class FileUploadResponse(BaseModel):+ url: str+ filename: Optional[str] = None+ size: Optional[int] = None+ content_type: Optional[str] = None++class SpaceFileItem(BaseModel):+ id: str+ space_id: Optional[str] = None+ name: str+ url: str+ size: int+ content_type: str+ uploader_id: Optional[str] = None+ created_at: datetime = Field(default_factory=datetime.utcnow)diff --git a/server/app/services/space_store.py b/server/app/services/space_store.pyindex 20a73b2..f653372 100644--- a/server/app/services/space_store.py+++ b/server/app/services/space_store.py@@ -1,22 +1,99 @@import uuidfrom datetime import datetimefrom typing import List, Optional+from sqlalchemy import textfrom sqlalchemy.orm import Sessionfrom app.db.session import SessionLocal, Base, engine-from app.db.models import OpenSpaceDB, OpenPageDB, OpenAgentDB, OpenMessageDB, OpenMeetingDB-from app.models.schemas import Space, Page, AgentDot, SpaceMember, Message, MeetingNote, SpaceCreate, SpaceUpdate, PageCreate, PageUpdate, MessageCreate, MeetingNoteCreate+from app.db.models import (+ OpenSpaceDB, OpenPageDB, OpenAgentDB, OpenMessageDB, OpenMeetingDB,+ UserDB, SpaceMemberDB, PageRevisionDB, OpenCommentDB, OpenActivityDB+)+from app.models.schemas import (+ Space, Page, AgentDot, SpaceMember, Message, MeetingNote,+ SpaceCreate, SpaceUpdate, PageCreate, PageUpdate, MessageCreate, MeetingNoteCreate,+ SpaceMemberDetail, User, PageRevision, Comment, CommentCreate, CommentUpdate,+ ActivityItem, ScopedSearchResult+)++MAX_PAGE_CONTENT_LENGTH = 500_000++class PageConflictError(Exception):+ def __init__(self, current_version: int, page: Page):+ super().__init__(f"Edit conflict: current version is {current_version}")+ self.current_version = current_version+ self.page = page++def check_page_cycle(db: Session, page_id: str, new_parent_id: Optional[str]) -> bool:+ """Returns True if assigning new_parent_id to page_id creates a cycle."""+ if not new_parent_id:+ return False+ if page_id == new_parent_id:+ return True+ current = new_parent_id+ visited = {page_id}+ while current:+ if current in visited:+ return True+ visited.add(current)+ parent_row = db.query(OpenPageDB).filter(OpenPageDB.id == current).first()+ if not parent_row:+ break+ current = parent_row.parent_id+ return Falseclass SupabaseSpaceService:def __init__(self):- # Ensure tables exist+ # Ensure schema migrations & tables exist+ try:+ with engine.connect() as conn:+ conn.execute(text("ALTER TABLE open_spaces ADD COLUMN IF NOT EXISTS owner_id VARCHAR(64);"))+ conn.execute(text("ALTER TABLE open_pages ADD COLUMN IF NOT EXISTS parent_id VARCHAR(64);"))+ conn.execute(text('ALTER TABLE open_pages ADD COLUMN IF NOT EXISTS "order" INTEGER DEFAULT 0;'))+ conn.commit()+ except Exception as e:+ print(f"Migration note: {e}")Base.metadata.create_all(bind=engine)self._seed_default_data_if_empty()def _seed_default_data_if_empty(self):db: Session = SessionLocal()try:+ # 1. Ensure baseline users exist+ u1 = db.query(UserDB).filter(UserDB.id == "usr-1").first()+ if not u1:+ u1 = UserDB(+ id="usr-1",+ name="Alex Morgan",+ email="[email protected]",+ avatar="https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=100&auto=format&fit=crop&q=80"+ )+ db.add(u1)+ u2 = db.query(UserDB).filter(UserDB.id == "usr-2").first()+ if not u2:+ u2 = UserDB(+ id="usr-2",+ name="Jordan Lee",+ email="[email protected]",+ avatar="https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&auto=format&fit=crop&q=80"+ )+ db.add(u2)+ db.commit()+count = db.query(OpenSpaceDB).count()if count > 0:+ # Backfill space_members for existing spaces if needed+ for s in db.query(OpenSpaceDB).all():+ if not s.owner_id:+ s.owner_id = "usr-1"+ m_count = db.query(SpaceMemberDB).filter(SpaceMemberDB.space_id == s.id).count()+ if m_count == 0:+ db.add(SpaceMemberDB(+ id=f"mem-{uuid.uuid4().hex[:8]}",+ space_id=s.id,+ user_id="usr-1",+ role="owner"+ ))+ db.commit()returnspace1_id = "space-product-launch"@@ -30,6 +107,7 @@ class SupabaseSpaceService:icon="π",color="indigo",pinned=True,+ owner_id="usr-1",members=[{"id": "usr-1", "name": "Alex Morgan", "role": "owner"},{"id": "usr-2", "name": "Jordan Lee", "role": "editor"},@@ -45,6 +123,7 @@ class SupabaseSpaceService:icon="brain",color="emerald",pinned=False,+ owner_id="usr-1",members=[{"id": "usr-1", "name": "Alex Morgan", "role": "owner"}],created_at=datetime.utcnow(),updated_at=datetime.utcnow(),@@ -55,6 +134,12 @@ class SupabaseSpaceService:db.add(s2)db.commit()+ # Seed normalized space members+ db.add(SpaceMemberDB(id=f"mem-{uuid.uuid4().hex[:8]}", space_id=space1_id, user_id="usr-1", role="owner"))+ db.add(SpaceMemberDB(id=f"mem-{uuid.uuid4().hex[:8]}", space_id=space1_id, user_id="usr-2", role="editor"))+ db.add(SpaceMemberDB(id=f"mem-{uuid.uuid4().hex[:8]}", space_id=space2_id, user_id="usr-1", role="owner"))+ db.commit()+# Space 1 Agentsdot1 = OpenAgentDB(id="dot-1",@@ -276,6 +361,7 @@ How Dot agents communicate within a shared Space:members = [SpaceMember(**m) for m in (r.members or [])]return Space(id=r.id,+ owner_id=r.owner_id,name=r.name,description=r.description,icon=r.icon,@@ -291,7 +377,7 @@ How Dot agents communicate within a shared Space:finally:db.close()- def create_space(self, space_data: SpaceCreate) -> Space:+ def create_space(self, space_data: SpaceCreate, owner_id: str = "usr-1", owner_name: str = "You") -> Space:db: Session = SessionLocal()try:space_id = f"space-{uuid.uuid4().hex[:8]}"@@ -302,11 +388,19 @@ How Dot agents communicate within a shared Space:icon=space_data.icon or "π",color=space_data.color or "indigo",pinned=space_data.pinned or False,- members=[{"id": "usr-1", "name": "You", "role": "owner"}],+ owner_id=owner_id,+ members=[{"id": owner_id, "name": owner_name, "role": "owner"}],created_at=datetime.utcnow(),updated_at=datetime.utcnow(),)db.add(r)+ # Add normalized membership+ db.add(SpaceMemberDB(+ id=f"mem-{uuid.uuid4().hex[:8]}",+ space_id=space_id,+ user_id=owner_id,+ role="owner"+ ))default_agent = OpenAgentDB(id=f"dot-{uuid.uuid4().hex[:4]}",space_id=space_id,@@ -323,6 +417,136 @@ How Dot agents communicate within a shared Space:finally:db.close()+ def get_space_members(self, space_id: str) -> List[SpaceMemberDetail]:+ db: Session = SessionLocal()+ try:+ records = (+ db.query(SpaceMemberDB, UserDB)+ .join(UserDB, SpaceMemberDB.user_id == UserDB.id)+ .filter(SpaceMemberDB.space_id == space_id)+ .all()+ )+ return [+ SpaceMemberDetail(+ id=m.id,+ space_id=m.space_id,+ user_id=u.id,+ name=u.name,+ email=u.email,+ avatar=u.avatar,+ role=m.role,+ created_at=m.created_at,+ )+ for m, u in records+ ]+ finally:+ db.close()++ def add_space_member(self, space_id: str, user_id: Optional[str] = None, email: Optional[str] = None, role: str = "editor") -> Optional[SpaceMemberDetail]:+ db: Session = SessionLocal()+ try:+ user = None+ if user_id:+ user = db.query(UserDB).filter(UserDB.id == user_id).first()+ if not user and email:+ clean_email = email.strip().lower()+ user = db.query(UserDB).filter(UserDB.email == clean_email).first()+ if not user:+ display_name = clean_email.split("@")[0].replace(".", " ").capitalize()+ user = UserDB(+ id=f"usr-{uuid.uuid4().hex[:6]}",+ name=display_name,+ email=clean_email,+ avatar=f"https://api.dicebear.com/7.x/initials/svg?seed={display_name}"+ )+ db.add(user)+ db.flush()+ if not user:+ return None+ space = db.query(OpenSpaceDB).filter(OpenSpaceDB.id == space_id).first()+ if not space:+ return None++ member = db.query(SpaceMemberDB).filter(+ SpaceMemberDB.space_id == space_id,+ SpaceMemberDB.user_id == user.id+ ).first()++ if member:+ member.role = role+ member.updated_at = datetime.utcnow()+ else:+ member = SpaceMemberDB(+ id=f"mem-{uuid.uuid4().hex[:8]}",+ space_id=space_id,+ user_id=user.id,+ role=role+ )+ db.add(member)++ # Sync cached members list on OpenSpaceDB+ cached = [m for m in (space.members or []) if m.get("id") != user.id]+ cached.append({"id": user.id, "name": user.name, "role": role})+ space.members = cached++ self.record_activity(+ db,+ space_id=space_id,+ user_id=user.id,+ user_name=user.name,+ action_type="member_joined",+ summary=f"{user.name} joined as {role}"+ )++ db.commit()++ return SpaceMemberDetail(+ id=member.id,+ space_id=space_id,+ user_id=user.id,+ name=user.name,+ email=user.email,+ avatar=user.avatar,+ role=role,+ created_at=member.created_at,+ )+ finally:+ db.close()++ def remove_space_member(self, space_id: str, user_id: str) -> bool:+ db: Session = SessionLocal()+ try:+ space = db.query(OpenSpaceDB).filter(OpenSpaceDB.id == space_id).first()+ if not space or space.owner_id == user_id:+ return False # Cannot remove space owner++ member = db.query(SpaceMemberDB).filter(+ SpaceMemberDB.space_id == space_id,+ SpaceMemberDB.user_id == user_id+ ).first()+ if not member:+ return False++ user = db.query(UserDB).filter(UserDB.id == user_id).first()+ user_name = user.name if user else "Member"++ db.delete(member)+ space.members = [m for m in (space.members or []) if m.get("id") != user_id]++ self.record_activity(+ db,+ space_id=space_id,+ user_id=user_id,+ user_name=user_name,+ action_type="member_removed",+ summary=f"{user_name} was removed from the space"+ )++ db.commit()+ return True+ finally:+ db.close()+def update_space(self, space_id: str, update_data: SpaceUpdate) -> Optional[Space]:db: Session = SessionLocal()try:@@ -354,7 +578,7 @@ How Dot agents communicate within a shared Space:def get_pages(self, space_id: str) -> List[Page]:db: Session = SessionLocal()try:- records = db.query(OpenPageDB).filter(OpenPageDB.space_id == space_id).order_by(OpenPageDB.updated_at.desc()).all()+ records = db.query(OpenPageDB).filter(OpenPageDB.space_id == space_id).order_by(OpenPageDB.order.asc(), OpenPageDB.created_at.asc()).all()return [Page(id=p.id,@@ -364,7 +588,9 @@ How Dot agents communicate within a shared Space:icon=p.icon,status=p.status,author=p.author,- version=p.version,+ version=p.version or 1,+ parent_id=p.parent_id,+ order=p.order or 0,created_at=p.created_at,updated_at=p.updated_at,)@@ -387,19 +613,30 @@ How Dot agents communicate within a shared Space:icon=p.icon,status=p.status,author=p.author,- version=p.version,+ version=p.version or 1,+ parent_id=p.parent_id,+ order=p.order or 0,created_at=p.created_at,updated_at=p.updated_at,)finally:db.close()- def create_page(self, space_id: str, page_data: PageCreate) -> Optional[Page]:+ def create_page(self, space_id: str, page_data: PageCreate, author: str = "You") -> Optional[Page]:db: Session = SessionLocal()try:space = db.query(OpenSpaceDB).filter(OpenSpaceDB.id == space_id).first()if not space:return None++ if len(page_data.content or "") > MAX_PAGE_CONTENT_LENGTH:+ raise ValueError("Page content exceeds the maximum limit of 500,000 characters.")++ if page_data.parent_id:+ parent_page = db.query(OpenPageDB).filter(OpenPageDB.space_id == space_id, OpenPageDB.id == page_data.parent_id).first()+ if not parent_page:+ raise ValueError("Specified parent page does not exist in this space.")+page_id = f"page-{uuid.uuid4().hex[:8]}"raw_title = (page_data.title or "Untitled page").strip()@@ -412,16 +649,32 @@ How Dot agents communicate within a shared Space:p = OpenPageDB(id=page_id,space_id=space_id,+ parent_id=page_data.parent_id,+ order=page_data.order or 0,title=clean_title,content=page_data.content or "",icon=(page_data.icon or "π")[:10],status=page_data.status or "draft",- author="You",+ author=author,version=1,created_at=datetime.utcnow(),updated_at=datetime.utcnow(),)db.add(p)++ # Record initial revision snapshot+ rev = PageRevisionDB(+ id=f"rev-{uuid.uuid4().hex[:8]}",+ page_id=page_id,+ space_id=space_id,+ version=1,+ title=clean_title,+ content=page_data.content or "",+ author=author,+ created_at=p.created_at+ )+ db.add(rev)+db.commit()db.refresh(p)return Page(@@ -432,7 +685,9 @@ How Dot agents communicate within a shared Space:icon=p.icon,status=p.status,author=p.author,- version=p.version,+ version=p.version or 1,+ parent_id=p.parent_id,+ order=p.order or 0,created_at=p.created_at,updated_at=p.updated_at,)@@ -442,13 +697,53 @@ How Dot agents communicate within a shared Space:finally:db.close()- def update_page(self, space_id: str, page_id: str, update_data: PageUpdate) -> Optional[Page]:+ def update_page(self, space_id: str, page_id: str, update_data: PageUpdate, author: str = "You") -> Optional[Page]:db: Session = SessionLocal()try:p = db.query(OpenPageDB).filter(OpenPageDB.space_id == space_id, OpenPageDB.id == page_id).first()if not p:return None++ current_ver = p.version or 1++ # Optimistic Concurrency check+ if update_data.expected_revision is not None and update_data.expected_revision != current_ver:+ current_page = Page(+ id=p.id,+ space_id=p.space_id,+ title=p.title,+ content=p.content,+ icon=p.icon,+ status=p.status,+ author=p.author,+ version=current_ver,+ parent_id=p.parent_id,+ order=p.order or 0,+ created_at=p.created_at,+ updated_at=p.updated_at,+ )+ raise PageConflictError(current_version=current_ver, page=current_page)++ # Content length check+ if update_data.content is not None and len(update_data.content) > MAX_PAGE_CONTENT_LENGTH:+ raise ValueError("Page content exceeds the maximum limit of 500,000 characters.")++ # Hierarchy cycle check+ if update_data.parent_id is not None:+ if update_data.parent_id == "":+ p.parent_id = None+ elif update_data.parent_id != p.parent_id:+ parent_page = db.query(OpenPageDB).filter(OpenPageDB.space_id == space_id, OpenPageDB.id == update_data.parent_id).first()+ if not parent_page:+ raise ValueError("Target parent page does not exist in this space.")+ if check_page_cycle(db, page_id, update_data.parent_id):+ raise ValueError("Hierarchy cycle detected: a page cannot be made a child of itself or its descendants.")+ p.parent_id = update_data.parent_id+data = update_data.model_dump(exclude_unset=True)+ data.pop("expected_revision", None)+ data.pop("parent_id", None)+if "title" in data and data["title"] is not None:t = str(data["title"]).strip()if len(t) > 200 or "\n" in t:@@ -456,10 +751,104 @@ How Dot agents communicate within a shared Space:data["title"] = t or "Untitled page"if "icon" in data and data["icon"] is not None:data["icon"] = str(data["icon"])[:10]+for k, v in data.items():setattr(p, k, v)++ p.version = current_ver + 1+ p.updated_at = datetime.utcnow()++ # Record revision snapshot+ rev = PageRevisionDB(+ id=f"rev-{uuid.uuid4().hex[:8]}",+ page_id=p.id,+ space_id=space_id,+ version=p.version,+ title=p.title,+ content=p.content,+ author=author or p.author or "You",+ created_at=p.updated_at+ )+ db.add(rev)++ db.commit()+ db.refresh(p)+ return Page(+ id=p.id,+ space_id=p.space_id,+ title=p.title,+ content=p.content,+ icon=p.icon,+ status=p.status,+ author=p.author,+ version=p.version,+ parent_id=p.parent_id,+ order=p.order or 0,+ created_at=p.created_at,+ updated_at=p.updated_at,+ )+ except (PageConflictError, ValueError):+ db.rollback()+ raise+ except Exception:+ db.rollback()+ raise+ finally:+ db.close()++ def get_page_revisions(self, space_id: str, page_id: str) -> List[PageRevision]:+ db: Session = SessionLocal()+ try:+ revs = db.query(PageRevisionDB).filter(+ PageRevisionDB.space_id == space_id,+ PageRevisionDB.page_id == page_id+ ).order_by(PageRevisionDB.version.desc()).all()+ return [+ PageRevision(+ id=r.id,+ page_id=r.page_id,+ space_id=r.space_id,+ version=r.version,+ title=r.title,+ content=r.content,+ author=r.author,+ created_at=r.created_at,+ )+ for r in revs+ ]+ finally:+ db.close()++ def restore_page_revision(self, space_id: str, page_id: str, target_version: int, author: str = "You") -> Optional[Page]:+ db: Session = SessionLocal()+ try:+ p = db.query(OpenPageDB).filter(OpenPageDB.space_id == space_id, OpenPageDB.id == page_id).first()+ if not p:+ return None+ rev = db.query(PageRevisionDB).filter(+ PageRevisionDB.space_id == space_id,+ PageRevisionDB.page_id == page_id,+ PageRevisionDB.version == target_version+ ).first()+ if not rev:+ return None++ p.title = rev.title+ p.content = rev.contentp.version = (p.version or 1) + 1p.updated_at = datetime.utcnow()++ new_rev = PageRevisionDB(+ id=f"rev-{uuid.uuid4().hex[:8]}",+ page_id=p.id,+ space_id=space_id,+ version=p.version,+ title=p.title,+ content=p.content,+ author=f"{author} (restored v{target_version})",+ created_at=p.updated_at+ )+ db.add(new_rev)db.commit()db.refresh(p)return Page(@@ -471,6 +860,8 @@ How Dot agents communicate within a shared Space:status=p.status,author=p.author,version=p.version,+ parent_id=p.parent_id,+ order=p.order or 0,created_at=p.created_at,updated_at=p.updated_at,)@@ -602,4 +993,256 @@ How Dot agents communicate within a shared Space:finally:db.close()+ # --- Activity Log ---+ def record_activity(+ self,+ db: Session,+ space_id: str,+ user_id: str,+ user_name: str,+ action_type: str,+ summary: str,+ page_id: Optional[str] = None+ ) -> OpenActivityDB:+ act = OpenActivityDB(+ id=f"act-{uuid.uuid4().hex[:8]}",+ space_id=space_id,+ page_id=page_id,+ user_id=user_id,+ user_name=user_name,+ action_type=action_type,+ summary=summary,+ created_at=datetime.utcnow()+ )+ db.add(act)+ return act++ def get_space_activities(self, space_id: str, limit: int = 50) -> List[ActivityItem]:+ db: Session = SessionLocal()+ try:+ records = db.query(OpenActivityDB).filter(+ OpenActivityDB.space_id == space_id+ ).order_by(OpenActivityDB.created_at.desc()).limit(limit).all()+ return [+ ActivityItem(+ id=a.id,+ space_id=a.space_id,+ page_id=a.page_id,+ user_id=a.user_id,+ user_name=a.user_name,+ action_type=a.action_type,+ summary=a.summary,+ created_at=a.created_at,+ )+ for a in records+ ]+ finally:+ db.close()++ # --- Comments ---+ def get_page_comments(self, space_id: str, page_id: str) -> List[Comment]:+ db: Session = SessionLocal()+ try:+ records = db.query(OpenCommentDB).filter(+ OpenCommentDB.space_id == space_id,+ OpenCommentDB.page_id == page_id+ ).order_by(OpenCommentDB.created_at.asc()).all()+ return [+ Comment(+ id=c.id,+ page_id=c.page_id,+ space_id=c.space_id,+ user_id=c.user_id,+ user_name=c.user_name,+ user_avatar=c.user_avatar,+ content=c.content,+ parent_id=c.parent_id,+ resolved=c.resolved,+ created_at=c.created_at,+ updated_at=c.updated_at,+ )+ for c in records+ ]+ finally:+ db.close()++ def add_comment(+ self,+ space_id: str,+ page_id: str,+ user: User,+ payload: CommentCreate+ ) -> Optional[Comment]:+ db: Session = SessionLocal()+ try:+ page = db.query(OpenPageDB).filter(OpenPageDB.space_id == space_id, OpenPageDB.id == page_id).first()+ if not page:+ return None++ comm = OpenCommentDB(+ id=f"cmt-{uuid.uuid4().hex[:8]}",+ space_id=space_id,+ page_id=page_id,+ user_id=user.id,+ user_name=user.name,+ user_avatar=user.avatar,+ content=payload.content,+ parent_id=payload.parent_id,+ resolved=False,+ created_at=datetime.utcnow(),+ updated_at=datetime.utcnow(),+ )+ db.add(comm)++ self.record_activity(+ db,+ space_id=space_id,+ page_id=page_id,+ user_id=user.id,+ user_name=user.name,+ action_type="comment_added",+ summary=f"{user.name} commented on '{page.title}'"+ )+ db.commit()+ db.refresh(comm)+ return Comment(+ id=comm.id,+ page_id=comm.page_id,+ space_id=comm.space_id,+ user_id=comm.user_id,+ user_name=comm.user_name,+ user_avatar=comm.user_avatar,+ content=comm.content,+ parent_id=comm.parent_id,+ resolved=comm.resolved,+ created_at=comm.created_at,+ updated_at=comm.updated_at,+ )+ finally:+ db.close()++ def update_comment(+ self,+ space_id: str,+ page_id: str,+ comment_id: str,+ payload: CommentUpdate,+ user_id: str+ ) -> Optional[Comment]:+ db: Session = SessionLocal()+ try:+ comm = db.query(OpenCommentDB).filter(+ OpenCommentDB.space_id == space_id,+ OpenCommentDB.page_id == page_id,+ OpenCommentDB.id == comment_id+ ).first()+ if not comm:+ return None+ if payload.content is not None and comm.user_id == user_id:+ comm.content = payload.content+ if payload.resolved is not None:+ comm.resolved = payload.resolved+ comm.updated_at = datetime.utcnow()+ db.commit()+ db.refresh(comm)+ return Comment(+ id=comm.id,+ page_id=comm.page_id,+ space_id=comm.space_id,+ user_id=comm.user_id,+ user_name=comm.user_name,+ user_avatar=comm.user_avatar,+ content=comm.content,+ parent_id=comm.parent_id,+ resolved=comm.resolved,+ created_at=comm.created_at,+ updated_at=comm.updated_at,+ )+ finally:+ db.close()++ def delete_comment(+ self,+ space_id: str,+ page_id: str,+ comment_id: str,+ user_id: str+ ) -> bool:+ db: Session = SessionLocal()+ try:+ comm = db.query(OpenCommentDB).filter(+ OpenCommentDB.space_id == space_id,+ OpenCommentDB.page_id == page_id,+ OpenCommentDB.id == comment_id+ ).first()+ if not comm:+ return False+ db.delete(comm)+ db.commit()+ return True+ finally:+ db.close()++ # --- Scoped Search ---+ def search_scoped(self, user_id: str, query: str) -> ScopedSearchResult:+ db: Session = SessionLocal()+ try:+ q = (query or "").strip().lower()+ if not q:+ return ScopedSearchResult(spaces=[], pages=[])++ member_spaces = db.query(SpaceMemberDB.space_id).filter(SpaceMemberDB.user_id == user_id).all()+ allowed_ids = {s[0] for s in member_spaces}++ if not allowed_ids:+ all_s = db.query(OpenSpaceDB.id).all()+ allowed_ids = {s[0] for s in all_s}++ matching_spaces = db.query(OpenSpaceDB).filter(+ OpenSpaceDB.id.in_(allowed_ids),+ (OpenSpaceDB.name.ilike(f"%{q}%") | OpenSpaceDB.description.ilike(f"%{q}%"))+ ).all()++ matching_pages = db.query(OpenPageDB).filter(+ OpenPageDB.space_id.in_(allowed_ids),+ (OpenPageDB.title.ilike(f"%{q}%") | OpenPageDB.content.ilike(f"%{q}%"))+ ).limit(20).all()++ spaces_res = [+ Space(+ id=s.id,+ name=s.name,+ description=s.description,+ icon=s.icon,+ color=s.color,+ pinned=s.pinned,+ owner_id=s.owner_id,+ created_at=s.created_at,+ updated_at=s.updated_at,+ )+ for s in matching_spaces+ ]++ pages_res = [+ Page(+ id=p.id,+ space_id=p.space_id,+ title=p.title,+ content=p.content,+ icon=p.icon,+ status=p.status,+ author=p.author,+ version=p.version,+ parent_id=p.parent_id,+ order=p.order or 0,+ created_at=p.created_at,+ updated_at=p.updated_at,+ )+ for p in matching_pages+ ]++ return ScopedSearchResult(spaces=spaces_res, pages=pages_res)+ finally:+ db.close()+store = SupabaseSpaceService()